FlatCAMApp.py 547 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import webbrowser
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import lzma
  16. import threading
  17. import shutil
  18. import stat
  19. from stat import S_IREAD, S_IRGRP, S_IROTH
  20. import subprocess
  21. import ctypes
  22. import tkinter as tk
  23. from PyQt5 import QtPrintSupport
  24. from contextlib import contextmanager
  25. import gc
  26. from xml.dom.minidom import parseString as parse_xml_string
  27. from multiprocessing.connection import Listener, Client
  28. from multiprocessing import Pool, cpu_count
  29. import socket
  30. from array import array
  31. import vispy.scene as scene
  32. # #######################################
  33. # # Imports part of FlatCAM ##
  34. # #######################################
  35. from ObjectCollection import *
  36. from FlatCAMObj import *
  37. from camlib import to_dict, dict2obj, ET, ParseError
  38. from flatcamGUI.PlotCanvas import *
  39. from flatcamGUI.PlotCanvasLegacy import *
  40. from flatcamGUI.FlatCAMGUI import *
  41. from FlatCAMCommon import LoudDict, BookmarkManager, ToolsDB
  42. from FlatCAMPostProc import load_preprocessors
  43. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  44. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  45. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  46. from flatcamEditors.FlatCAMTextEditor import TextEditor
  47. from FlatCAMProcess import *
  48. from FlatCAMWorkerStack import WorkerStack
  49. # from flatcamGUI.VisPyVisuals import Color
  50. from vispy.gloo.util import _screenshot
  51. from vispy.io import write_png
  52. from flatcamTools import *
  53. import tclCommands
  54. import gettext
  55. import FlatCAMTranslation as fcTranslate
  56. import builtins
  57. if sys.platform == 'win32':
  58. import winreg
  59. fcTranslate.apply_language('strings')
  60. if '_' not in builtins.__dict__:
  61. _ = gettext.gettext
  62. class App(QtCore.QObject):
  63. # ########################################
  64. # # App ###
  65. # ########################################
  66. """
  67. The main application class. The constructor starts the GUI.
  68. """
  69. # Get Cmd Line Options
  70. cmd_line_shellfile = ''
  71. cmd_line_shellvar = ''
  72. cmd_line_headless = None
  73. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  74. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  75. "FlatCam.py --headless=1"
  76. try:
  77. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  78. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  79. "shellvar=",
  80. "headless=",
  81. "multiprocessing-fork="])
  82. except getopt.GetoptError:
  83. print(cmd_line_help)
  84. sys.exit(2)
  85. for opt, arg in cmd_line_options:
  86. if opt == '-h':
  87. print(cmd_line_help)
  88. sys.exit()
  89. elif opt == '--shellfile':
  90. cmd_line_shellfile = arg
  91. elif opt == '--shellvar':
  92. cmd_line_shellvar = arg
  93. elif opt == '--headless':
  94. try:
  95. cmd_line_headless = eval(arg)
  96. except NameError:
  97. pass
  98. # ## Logging ###
  99. log = logging.getLogger('base')
  100. log.setLevel(logging.DEBUG)
  101. # log.setLevel(logging.WARNING)
  102. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  103. handler = logging.StreamHandler()
  104. handler.setFormatter(formatter)
  105. log.addHandler(handler)
  106. # ##########################################################################
  107. # ################## Version and VERSION DATE ##############################
  108. # ##########################################################################
  109. version = 8.99
  110. version_date = "2019/12/12"
  111. beta = True
  112. engine = '3D'
  113. # current date now
  114. date = str(datetime.today()).rpartition('.')[0]
  115. date = ''.join(c for c in date if c not in ':-')
  116. date = date.replace(' ', '_')
  117. # URL for update checks and statistics
  118. version_url = "http://flatcam.org/version"
  119. # App URL
  120. app_url = "http://flatcam.org"
  121. # Manual URL
  122. manual_url = "http://flatcam.org/manual/index.html"
  123. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  124. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  125. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  126. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  127. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  128. # this variable will hold the project status
  129. # if True it will mean that the project was modified and not saved
  130. should_we_save = False
  131. # flag is True if saving action has been triggered
  132. save_in_progress = False
  133. # ###########################################################################
  134. # ############################# Signals ################################
  135. # ###########################################################################
  136. # Inform the user
  137. # Handled by:
  138. # * App.info() --> Print on the status bar
  139. inform = QtCore.pyqtSignal(str)
  140. app_quit = QtCore.pyqtSignal()
  141. # General purpose background task
  142. worker_task = QtCore.pyqtSignal(dict)
  143. # File opened
  144. # Handled by:
  145. # * register_folder()
  146. # * register_recent()
  147. # Note: Setting the parameters to unicode does not seem
  148. # to have an effect. Then are received as Qstring
  149. # anyway.
  150. # File type and filename
  151. file_opened = QtCore.pyqtSignal(str, str)
  152. # File type and filename
  153. file_saved = QtCore.pyqtSignal(str, str)
  154. # Percentage of progress
  155. progress = QtCore.pyqtSignal(int)
  156. plots_updated = QtCore.pyqtSignal()
  157. # Emitted by new_object() and passes the new object as argument, plot flag.
  158. # on_object_created() adds the object to the collection, plots on appropriate flag
  159. # and emits new_object_available.
  160. object_created = QtCore.pyqtSignal(object, bool, bool)
  161. # Emitted when a object has been changed (like scaled, mirrored)
  162. object_changed = QtCore.pyqtSignal(object)
  163. # Emitted after object has been plotted.
  164. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  165. object_plotted = QtCore.pyqtSignal(object)
  166. # Emitted when a new object has been added or deleted from/to the collection
  167. object_status_changed = QtCore.pyqtSignal(object, str, str)
  168. message = QtCore.pyqtSignal(str, str, str)
  169. # Emmited when shell command is finished(one command only)
  170. shell_command_finished = QtCore.pyqtSignal(object)
  171. # Emitted when multiprocess pool has been recreated
  172. pool_recreated = QtCore.pyqtSignal(object)
  173. # Emitted when an unhandled exception happens
  174. # in the worker task.
  175. thread_exception = QtCore.pyqtSignal(object)
  176. # used to signal that there are arguments for the app
  177. args_at_startup = QtCore.pyqtSignal(list)
  178. # a reusable signal to replot a list of objects
  179. # should be disconnected after use so it can be reused
  180. replot_signal = pyqtSignal(list)
  181. def __init__(self, user_defaults=True):
  182. """
  183. Starts the application.
  184. :return: app
  185. :rtype: App
  186. """
  187. App.log.info("FlatCAM Starting...")
  188. self.main_thread = QtWidgets.QApplication.instance().thread()
  189. # ############################################################################
  190. # # ################# OS-specific ############################################
  191. # ############################################################################
  192. portable = False
  193. # Folder for user settings.
  194. if sys.platform == 'win32':
  195. # #########################################################################
  196. # Setup the listening thread for another instance launching with args #####
  197. # #########################################################################
  198. # make sure the thread is stored by using a self. otherwise it's garbage collected
  199. self.th = QtCore.QThread()
  200. self.th.start(priority=QtCore.QThread.LowestPriority)
  201. self.new_launch = ArgsThread()
  202. self.new_launch.open_signal[list].connect(self.on_startup_args)
  203. self.new_launch.moveToThread(self.th)
  204. self.new_launch.start.emit()
  205. from win32com.shell import shell, shellcon
  206. if platform.architecture()[0] == '32bit':
  207. App.log.debug("Win32!")
  208. else:
  209. App.log.debug("Win64!")
  210. # #########################################################################
  211. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  212. # #########################################################################
  213. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  214. try:
  215. with open(config_file, 'r'):
  216. pass
  217. except FileNotFoundError:
  218. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  219. try:
  220. with open(config_file, 'r') as f:
  221. try:
  222. for line in f:
  223. param = str(line).replace('\n', '').rpartition('=')
  224. if param[0] == 'portable':
  225. try:
  226. portable = eval(param[2])
  227. except NameError:
  228. portable = False
  229. if param[0] == 'headless':
  230. if param[2].lower() == 'true':
  231. self.cmd_line_headless = 1
  232. else:
  233. self.cmd_line_headless = None
  234. except Exception as e:
  235. log.debug('App.__init__() -->%s' % str(e))
  236. return
  237. except FileNotFoundError as e:
  238. log.debug(str(e))
  239. pass
  240. if portable is False:
  241. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  242. else:
  243. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  244. self.os = 'windows'
  245. else: # Linux/Unix/MacOS
  246. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  247. self.os = 'unix'
  248. # ##########################################################################
  249. # ################## Setup folders and files ###############################
  250. # ##########################################################################
  251. if not os.path.exists(self.data_path):
  252. os.makedirs(self.data_path)
  253. App.log.debug('Created data folder: ' + self.data_path)
  254. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  255. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  256. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  257. if not os.path.exists(self.preprocessorpaths):
  258. os.makedirs(self.preprocessorpaths)
  259. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  260. # create tools_db.FlatConfig file if there is none
  261. try:
  262. f = open(self.data_path + '/tools_db.FlatConfig')
  263. f.close()
  264. except IOError:
  265. App.log.debug('Creating empty tool_db.FlatConfig')
  266. f = open(self.data_path + '/tools_db.FlatConfig', 'w')
  267. json.dump({}, f)
  268. f.close()
  269. # create current_defaults.FlatConfig file if there is none
  270. try:
  271. f = open(self.data_path + '/current_defaults.FlatConfig')
  272. f.close()
  273. except IOError:
  274. App.log.debug('Creating empty current_defaults.FlatConfig')
  275. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  276. json.dump({}, f)
  277. f.close()
  278. # create factory_defaults.FlatConfig file if there is none
  279. try:
  280. f = open(self.data_path + '/factory_defaults.FlatConfig')
  281. f.close()
  282. except IOError:
  283. App.log.debug('Creating empty factory_defaults.FlatConfig')
  284. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  285. json.dump({}, f)
  286. f.close()
  287. # create a recent files json file if there is none
  288. try:
  289. f = open(self.data_path + '/recent.json')
  290. f.close()
  291. except IOError:
  292. App.log.debug('Creating empty recent.json')
  293. f = open(self.data_path + '/recent.json', 'w')
  294. json.dump([], f)
  295. f.close()
  296. # create a recent projects json file if there is none
  297. try:
  298. fp = open(self.data_path + '/recent_projects.json')
  299. fp.close()
  300. except IOError:
  301. App.log.debug('Creating empty recent_projects.json')
  302. fp = open(self.data_path + '/recent_projects.json', 'w')
  303. json.dump([], fp)
  304. fp.close()
  305. # Application directory. CHDIR to it. Otherwise, trying to load
  306. # GUI icons will fail as their path is relative.
  307. # This will fail under cx_freeze ...
  308. self.app_home = os.path.dirname(os.path.realpath(__file__))
  309. App.log.debug("Application path is " + self.app_home)
  310. App.log.debug("Started in " + os.getcwd())
  311. # cx_freeze workaround
  312. if os.path.isfile(self.app_home):
  313. self.app_home = os.path.dirname(self.app_home)
  314. os.chdir(self.app_home)
  315. # #################################################################################
  316. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  317. # #################################################################################
  318. self.defaults = LoudDict()
  319. self.defaults.update({
  320. # Global APP Preferences
  321. "decimals_inch": 4,
  322. "decimals_metric": 4,
  323. "version": self.version,
  324. "first_run": True,
  325. "units": "MM",
  326. "global_serial": 0,
  327. "global_stats": dict(),
  328. "global_tabs_detachable": True,
  329. "global_graphic_engine": '3D',
  330. "global_app_level": 'b',
  331. "global_portable": False,
  332. "global_language": 'English',
  333. "global_version_check": True,
  334. "global_send_stats": True,
  335. "global_pan_button": '2',
  336. "global_mselect_key": 'Control',
  337. "global_project_at_startup": False,
  338. "global_systray_icon": True,
  339. "global_project_autohide": True,
  340. "global_toggle_tooltips": True,
  341. "global_worker_number": 2,
  342. "global_tolerance": 0.005,
  343. "global_open_style": True,
  344. "global_delete_confirmation": True,
  345. "global_compression_level": 3,
  346. "global_save_compressed": True,
  347. "global_machinist_setting": False,
  348. # Global GUI Preferences
  349. "global_gridx": 1.0,
  350. "global_gridy": 1.0,
  351. "global_snap_max": 0.05,
  352. "global_workspace": False,
  353. "global_workspaceT": "A4",
  354. "global_workspace_orientation": 'p',
  355. "global_grid_context_menu": {
  356. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  357. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  358. },
  359. "global_plot_fill": '#BBF268BF',
  360. "global_plot_line": '#006E20BF',
  361. "global_sel_fill": '#a5a5ffbf',
  362. "global_sel_line": '#0000ffbf',
  363. "global_alt_sel_fill": '#BBF268BF',
  364. "global_alt_sel_line": '#006E20BF',
  365. "global_draw_color": '#FF0000',
  366. "global_sel_draw_color": '#0000FF',
  367. "global_proj_item_color": '#000000',
  368. "global_proj_item_dis_color": '#b7b7cb',
  369. "global_activity_icon": 'Ball green',
  370. "global_toolbar_view": 511,
  371. "global_background_timeout": 300000, # Default value is 5 minutes
  372. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  373. # (python trace only for unknown errors),
  374. # 1 = show trace(show trace always),
  375. # 2 = (For the future).
  376. # Persistence
  377. "global_last_folder": None,
  378. "global_last_save_folder": None,
  379. # Default window geometry
  380. "global_def_win_x": 100,
  381. "global_def_win_y": 100,
  382. "global_def_win_w": 1024,
  383. "global_def_win_h": 650,
  384. "global_def_notebook_width": 1,
  385. # Constants...
  386. "global_defaults_save_period_ms": 20000, # Time between default saves.
  387. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  388. "global_shell_at_startup": False, # Show the shell at startup.
  389. "global_recent_limit": 10, # Max. items in recent list.
  390. "global_bookmarks": dict(),
  391. "global_bookmarks_limit": 10,
  392. "fit_key": 'V',
  393. "zoom_out_key": '-',
  394. "zoom_in_key": '=',
  395. "grid_toggle_key": 'G',
  396. "global_zoom_ratio": 1.5,
  397. "global_point_clipboard_format": "(%.4f, %.4f)",
  398. "global_zdownrate": None,
  399. # General GUI Settings
  400. "global_theme": 'white',
  401. "global_hover": False,
  402. "global_selection_shape": True,
  403. "global_layout": "compact",
  404. "global_cursor_type": "small",
  405. "global_cursor_size": 20,
  406. # Gerber General
  407. "gerber_plot": True,
  408. "gerber_solid": True,
  409. "gerber_multicolored": False,
  410. "gerber_circle_steps": 64,
  411. "gerber_use_buffer_for_union": True,
  412. "gerber_def_units": 'IN',
  413. "gerber_def_zeros": 'L',
  414. "gerber_save_filters": "Gerber File (*.gbr);;Gerber File (*.bot);;Gerber File (*.bsm);;"
  415. "Gerber File (*.cmp);;Gerber File (*.crc);;Gerber File (*.crs);;"
  416. "Gerber File (*.gb0);;Gerber File (*.gb1);;Gerber File (*.gb2);;"
  417. "Gerber File (*.gb3);;Gerber File (*.gb4);;Gerber File (*.gb5);;"
  418. "Gerber File (*.gb6);;Gerber File (*.gb7);;Gerber File (*.gb8);;"
  419. "Gerber File (*.gb9);;Gerber File (*.gbd);;Gerber File (*.gbl);;"
  420. "Gerber File (*.gbo);;Gerber File (*.gbp);;Gerber File (*.gbs);;"
  421. "Gerber File (*.gdo);;Gerber File (*.ger);;Gerber File (*.gko);;"
  422. "Gerber File (*.gm1);;Gerber File (*.gm2);;Gerber File (*.gm3);;"
  423. "Gerber File (*.grb);;Gerber File (*.gtl);;Gerber File (*.gto);;"
  424. "Gerber File (*.gtp);;Gerber File (*.gts);;Gerber File (*.ly15);;"
  425. "Gerber File (*.ly2);;Gerber File (*.mil);;Gerber File (*.pho);;"
  426. "Gerber File (*.plc);;Gerber File (*.pls);;Gerber File (*.smb);;"
  427. "Gerber File (*.smt);;Gerber File (*.sol);;Gerber File (*.spb);;"
  428. "Gerber File (*.spt);;Gerber File (*.ssb);;Gerber File (*.sst);;"
  429. "Gerber File (*.stc);;Gerber File (*.sts);;Gerber File (*.top);;"
  430. "Gerber File (*.tsm);;Gerber File (*.art)"
  431. "All Files (*.*)",
  432. # Gerber Options
  433. "gerber_isotooldia": 0.1,
  434. "gerber_isopasses": 1,
  435. "gerber_isooverlap": 10,
  436. "gerber_milling_type": "cl",
  437. "gerber_combine_passes": False,
  438. "gerber_iso_scope": 'all',
  439. "gerber_noncoppermargin": 0.1,
  440. "gerber_noncopperrounded": False,
  441. "gerber_bboxmargin": 0.1,
  442. "gerber_bboxrounded": False,
  443. # Gerber Advanced Options
  444. "gerber_aperture_display": False,
  445. "gerber_aperture_scale_factor": 1.0,
  446. "gerber_aperture_buffer_factor": 0.0,
  447. "gerber_follow": False,
  448. "gerber_tool_type": 'circular',
  449. "gerber_vtipdia": 0.1,
  450. "gerber_vtipangle": 30,
  451. "gerber_vcutz": -0.05,
  452. "gerber_iso_type": "full",
  453. "gerber_buffering": "full",
  454. "gerber_simplification": False,
  455. "gerber_simp_tolerance": 0.0005,
  456. # Gerber Export
  457. "gerber_exp_units": 'IN',
  458. "gerber_exp_integer": 2,
  459. "gerber_exp_decimals": 4,
  460. "gerber_exp_zeros": 'L',
  461. # Gerber Editor
  462. "gerber_editor_sel_limit": 30,
  463. "gerber_editor_newcode": 10,
  464. "gerber_editor_newsize": 0.8,
  465. "gerber_editor_newtype": 'C',
  466. "gerber_editor_newdim": "0.5, 0.5",
  467. "gerber_editor_array_size": 5,
  468. "gerber_editor_lin_axis": 'X',
  469. "gerber_editor_lin_pitch": 0.1,
  470. "gerber_editor_lin_angle": 0.0,
  471. "gerber_editor_circ_dir": 'CW',
  472. "gerber_editor_circ_angle": 0.0,
  473. "gerber_editor_scale_f": 1.0,
  474. "gerber_editor_buff_f": 0.1,
  475. "gerber_editor_ma_low": 0.0,
  476. "gerber_editor_ma_high": 1.0,
  477. # Excellon General
  478. "excellon_plot": True,
  479. "excellon_solid": True,
  480. "excellon_format_upper_in": 2,
  481. "excellon_format_lower_in": 4,
  482. "excellon_format_upper_mm": 3,
  483. "excellon_format_lower_mm": 3,
  484. "excellon_zeros": "L",
  485. "excellon_units": "INCH",
  486. "excellon_update": True,
  487. "excellon_optimization_type": 'B',
  488. "excellon_search_time": 3,
  489. "excellon_save_filters": "Excellon File (*.txt);;Excellon File (*.drd);;Excellon File (*.drl);;"
  490. "Excellon File (*.exc);;Excellon File (*.ncd);;Excellon File (*.tap);;"
  491. "Excellon File (*.xln);;All Files (*.*)",
  492. # Excellon Options
  493. "excellon_drillz": -1.7,
  494. "excellon_travelz": 2,
  495. "excellon_endz": 0.5,
  496. "excellon_feedrate": 300,
  497. "excellon_spindlespeed": None,
  498. "excellon_dwell": False,
  499. "excellon_dwelltime": 1,
  500. "excellon_toolchange": False,
  501. "excellon_toolchangez": 15,
  502. "excellon_ppname_e": 'default',
  503. "excellon_tooldia": 0.8,
  504. "excellon_slot_tooldia": 1.8,
  505. "excellon_gcode_type": "drills",
  506. # Excellon Advanced Options
  507. "excellon_offset": 0.0,
  508. "excellon_toolchangexy": "0.0, 0.0",
  509. "excellon_startz": None,
  510. "excellon_feedrate_rapid": 1500,
  511. "excellon_z_pdepth": -0.02,
  512. "excellon_feedrate_probe": 75,
  513. "excellon_spindledir": 'CW',
  514. "excellon_f_plunge": False,
  515. "excellon_f_retract": False,
  516. # Excellon Export
  517. "excellon_exp_units": 'INCH',
  518. "excellon_exp_format": 'ndec',
  519. "excellon_exp_integer": 2,
  520. "excellon_exp_decimals": 4,
  521. "excellon_exp_zeros": 'LZ',
  522. "excellon_exp_slot_type": 'routing',
  523. # Excellon Editor
  524. "excellon_editor_sel_limit": 30,
  525. "excellon_editor_newdia": 1.0,
  526. "excellon_editor_array_size": 5,
  527. "excellon_editor_lin_dir": 'X',
  528. "excellon_editor_lin_pitch": 2.54,
  529. "excellon_editor_lin_angle": 0.0,
  530. "excellon_editor_circ_dir": 'CW',
  531. "excellon_editor_circ_angle": 12,
  532. # Excellon Slots
  533. "excellon_editor_slot_direction": 'X',
  534. "excellon_editor_slot_angle": 0.0,
  535. "excellon_editor_slot_length": 5.0,
  536. # Excellon Slot Array
  537. "excellon_editor_slot_array_size": 5,
  538. "excellon_editor_slot_lin_dir": 'X',
  539. "excellon_editor_slot_lin_pitch": 2.54,
  540. "excellon_editor_slot_lin_angle": 0.0,
  541. "excellon_editor_slot_circ_dir": 'CW',
  542. "excellon_editor_slot_circ_angle": 0.0,
  543. # Geometry General
  544. "geometry_plot": True,
  545. "geometry_circle_steps": 64,
  546. "geometry_cnctooldia": "2.4",
  547. # Geometry Options
  548. "geometry_cutz": -2.4,
  549. "geometry_vtipdia": 0.1,
  550. "geometry_vtipangle": 30,
  551. "geometry_multidepth": False,
  552. "geometry_depthperpass": 0.8,
  553. "geometry_travelz": 2,
  554. "geometry_toolchange": False,
  555. "geometry_toolchangez": 15.0,
  556. "geometry_endz": 15.0,
  557. "geometry_feedrate": 120,
  558. "geometry_feedrate_z": 60,
  559. "geometry_spindlespeed": None,
  560. "geometry_dwell": False,
  561. "geometry_dwelltime": 1,
  562. "geometry_ppname_g": 'default',
  563. # Geometry Advanced Options
  564. "geometry_toolchangexy": "0.0, 0.0",
  565. "geometry_startz": None,
  566. "geometry_feedrate_rapid": 1500,
  567. "geometry_extracut": False,
  568. "geometry_z_pdepth": -0.02,
  569. "geometry_f_plunge": False,
  570. "geometry_spindledir": 'CW',
  571. "geometry_feedrate_probe": 75,
  572. "geometry_segx": 0.0,
  573. "geometry_segy": 0.0,
  574. # Geometry Editor
  575. "geometry_editor_sel_limit": 30,
  576. "geometry_editor_milling_type": "cl",
  577. # CNC Job General
  578. "cncjob_plot": True,
  579. "cncjob_plot_kind": 'all',
  580. "cncjob_annotation": True,
  581. "cncjob_tooldia": 1.0,
  582. "cncjob_coords_type": "G90",
  583. "cncjob_coords_decimals": 4,
  584. "cncjob_fr_decimals": 2,
  585. "cncjob_steps_per_circle": 64,
  586. "cncjob_footer": False,
  587. "cncjob_line_ending": False,
  588. "cncjob_save_filters": "G-Code Files (*.nc);;G-Code Files (*.din);;G-Code Files (*.dnc);;"
  589. "G-Code Files (*.ecs);;G-Code Files (*.eia);;G-Code Files (*.fan);;"
  590. "G-Code Files (*.fgc);;G-Code Files (*.fnc);;G-Code Files (*.gc);;"
  591. "G-Code Files (*.gcd);;G-Code Files (*.gcode);;G-Code Files (*.h);;"
  592. "G-Code Files (*.hnc);;G-Code Files (*.i);;G-Code Files (*.min);;"
  593. "G-Code Files (*.mpf);;G-Code Files (*.mpr);;G-Code Files (*.cnc);;"
  594. "G-Code Files (*.ncc);;G-Code Files (*.ncg);;G-Code Files (*.ncp);;"
  595. "G-Code Files (*.ngc);;G-Code Files (*.out);;G-Code Files (*.ply);;"
  596. "G-Code Files (*.sbp);;G-Code Files (*.tap);;G-Code Files (*.xpi);;"
  597. "All Files (*.*)",
  598. # CNC Job Options
  599. "cncjob_prepend": "",
  600. "cncjob_append": "",
  601. # CNC Job Advanced Options
  602. "cncjob_toolchange_macro": "",
  603. "cncjob_toolchange_macro_enable": False,
  604. "cncjob_annotation_fontsize": 9,
  605. "cncjob_annotation_fontcolor": '#990000',
  606. # NCC Tool
  607. "tools_ncctools": "1.0, 0.5",
  608. "tools_nccorder": 'rev',
  609. "tools_nccoverlap": 40,
  610. "tools_nccmargin": 1.0,
  611. "tools_nccmethod": "seed",
  612. "tools_nccconnect": True,
  613. "tools_ncccontour": True,
  614. "tools_nccrest": False,
  615. "tools_ncc_offset_choice": False,
  616. "tools_ncc_offset_value": 0.0000,
  617. "tools_nccref": 'itself',
  618. "tools_ncc_plotting": 'normal',
  619. "tools_nccmilling_type": 'cl',
  620. "tools_ncctool_type": 'V',
  621. "tools_ncccutz": -0.05,
  622. "tools_ncctipdia": 0.1,
  623. "tools_ncctipangle": 30,
  624. "tools_nccnewdia": 1.0,
  625. # Cutout Tool
  626. "tools_cutouttooldia": 2.4,
  627. "tools_cutoutkind": "single",
  628. "tools_cutoutmargin": 0.1,
  629. "tools_cutout_z": -1.8,
  630. "tools_cutout_depthperpass": 0.6,
  631. "tools_cutout_mdepth": True,
  632. "tools_cutoutgapsize": 4,
  633. "tools_gaps_ff": "4",
  634. "tools_cutout_convexshape": False,
  635. # Paint Tool
  636. "tools_painttooldia": 0.3,
  637. "tools_paintorder": 'rev',
  638. "tools_paintoverlap": 20,
  639. "tools_paintmargin": 0.0,
  640. "tools_paintmethod": "seed",
  641. "tools_selectmethod": "all",
  642. "tools_pathconnect": True,
  643. "tools_paintcontour": True,
  644. "tools_paint_plotting": 'normal',
  645. # 2-Sided Tool
  646. "tools_2sided_mirror_axis": "X",
  647. "tools_2sided_axis_loc": "point",
  648. "tools_2sided_drilldia": 3.125,
  649. # Film Tool
  650. "tools_film_type": 'neg',
  651. "tools_film_boundary": 1.0,
  652. "tools_film_scale_stroke": 0,
  653. "tools_film_color": '#000000',
  654. "tools_film_scale_cb": False,
  655. "tools_film_scale_x_entry": 1.0,
  656. "tools_film_scale_y_entry": 1.0,
  657. "tools_film_skew_cb": False,
  658. "tools_film_skew_x_entry": 0.0,
  659. "tools_film_skew_y_entry": 0.0,
  660. "tools_film_skew_ref_radio": 'bottomleft',
  661. "tools_film_mirror_cb": False,
  662. "tools_film_mirror_axis_radio": 'none',
  663. "tools_film_file_type_radio": 'svg',
  664. "tools_film_orientation": 'p',
  665. "tools_film_pagesize": 'A4',
  666. # Panel Tool
  667. "tools_panelize_spacing_columns": 0,
  668. "tools_panelize_spacing_rows": 0,
  669. "tools_panelize_columns": 1,
  670. "tools_panelize_rows": 1,
  671. "tools_panelize_constrain": False,
  672. "tools_panelize_constrainx": 200.0,
  673. "tools_panelize_constrainy": 290.0,
  674. "tools_panelize_panel_type": 'gerber',
  675. # Calculators Tool
  676. "tools_calc_vshape_tip_dia": 0.2,
  677. "tools_calc_vshape_tip_angle": 30,
  678. "tools_calc_vshape_cut_z": 0.05,
  679. "tools_calc_electro_length": 10.0,
  680. "tools_calc_electro_width": 10.0,
  681. "tools_calc_electro_cdensity": 13.0,
  682. "tools_calc_electro_growth": 10.0,
  683. # Transform Tool
  684. "tools_transform_rotate": 90,
  685. "tools_transform_skew_x": 0.0,
  686. "tools_transform_skew_y": 0.0,
  687. "tools_transform_scale_x": 1.0,
  688. "tools_transform_scale_y": 1.0,
  689. "tools_transform_scale_link": True,
  690. "tools_transform_scale_reference": True,
  691. "tools_transform_offset_x": 0.0,
  692. "tools_transform_offset_y": 0.0,
  693. "tools_transform_mirror_reference": False,
  694. "tools_transform_mirror_point": (0, 0),
  695. # SolderPaste Tool
  696. "tools_solderpaste_tools": "1.0, 0.3",
  697. "tools_solderpaste_new": 0.3,
  698. "tools_solderpaste_z_start": 0.05,
  699. "tools_solderpaste_z_dispense": 0.1,
  700. "tools_solderpaste_z_stop": 0.05,
  701. "tools_solderpaste_z_travel": 0.1,
  702. "tools_solderpaste_z_toolchange": 1.0,
  703. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  704. "tools_solderpaste_frxy": 150,
  705. "tools_solderpaste_frz": 150,
  706. "tools_solderpaste_frz_dispense": 1.0,
  707. "tools_solderpaste_speedfwd": 300,
  708. "tools_solderpaste_dwellfwd": 1,
  709. "tools_solderpaste_speedrev": 200,
  710. "tools_solderpaste_dwellrev": 1,
  711. "tools_solderpaste_pp": 'Paste_1',
  712. # Subtract Tool
  713. "tools_sub_close_paths": True,
  714. # ###################################################################################
  715. # ################################ TOOLS 2 ##########################################
  716. # ###################################################################################
  717. # Optimal Tool
  718. "tools_opt_precision": 4,
  719. # Check Rules Tool
  720. "tools_cr_trace_size": True,
  721. "tools_cr_trace_size_val": 0.25,
  722. "tools_cr_c2c": True,
  723. "tools_cr_c2c_val": 0.25,
  724. "tools_cr_c2o": True,
  725. "tools_cr_c2o_val": 1.0,
  726. "tools_cr_s2s": True,
  727. "tools_cr_s2s_val": 0.25,
  728. "tools_cr_s2sm": True,
  729. "tools_cr_s2sm_val": 0.25,
  730. "tools_cr_s2o": True,
  731. "tools_cr_s2o_val": 1.0,
  732. "tools_cr_sm2sm": True,
  733. "tools_cr_sm2sm_val": 0.25,
  734. "tools_cr_ri": True,
  735. "tools_cr_ri_val": 0.3,
  736. "tools_cr_h2h": True,
  737. "tools_cr_h2h_val": 0.3,
  738. "tools_cr_dh": True,
  739. "tools_cr_dh_val": 0.3,
  740. # QRCode Tool
  741. "tools_qrcode_version": 1,
  742. "tools_qrcode_error": 'L',
  743. "tools_qrcode_box_size": 3,
  744. "tools_qrcode_border_size": 4,
  745. "tools_qrcode_qrdata": '',
  746. "tools_qrcode_polarity": 'pos',
  747. "tools_qrcode_rounded": 's',
  748. "tools_qrcode_fill_color": '#000000',
  749. "tools_qrcode_back_color": '#FFFFFF',
  750. "tools_qrcode_sel_limit": 330,
  751. # Copper Thieving Tool
  752. "tools_copper_thieving_clearance": 0.25,
  753. "tools_copper_thieving_margin": 1.0,
  754. "tools_copper_thieving_reference": 'itself',
  755. "tools_copper_thieving_box_type": 'rect',
  756. "tools_copper_thieving_circle_steps": 64,
  757. "tools_copper_thieving_fill_type": 'solid',
  758. "tools_copper_thieving_dots_dia": 1.0,
  759. "tools_copper_thieving_dots_spacing": 2.0,
  760. "tools_copper_thieving_squares_size": 1.0,
  761. "tools_copper_thieving_squares_spacing": 2.0,
  762. "tools_copper_thieving_lines_size": 0.25,
  763. "tools_copper_thieving_lines_spacing": 2.0,
  764. "tools_copper_thieving_rb_margin": 1.0,
  765. "tools_copper_thieving_rb_thickness": 1.0,
  766. "tools_copper_thieving_mask_clearance": 0.0,
  767. # Fiducials Tool
  768. "tools_fiducials_dia": 1.0,
  769. "tools_fiducials_margin": 1.0,
  770. "tools_fiducials_mode": 'auto',
  771. "tools_fiducials_second_pos": 'up',
  772. "tools_fiducials_type": 'circular',
  773. "tools_fiducials_line_thickness": 0.25,
  774. # Calibration Tool
  775. "tools_cal_calsource": 'object',
  776. "tools_cal_travelz": 2.0,
  777. "tools_cal_verz": 0.1,
  778. "tools_cal_zeroz": False,
  779. "tools_cal_toolchangez": 15,
  780. # Utilities
  781. # file associations
  782. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  783. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  784. 'ncg, ncp, ngc, out, plt, ply, rol, sbp, tap, xpi',
  785. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, gb0, gb1, gb2, gb3, gb4, gb5, gb6, gb7, gb8, gb9, gbd, '
  786. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  787. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  788. # Keyword list
  789. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  790. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  791. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  792. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  793. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  794. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  795. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  796. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  797. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  798. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  799. 'toolchange_xy, tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  800. 'z_move',
  801. "script_autocompleter": True,
  802. "script_text": "",
  803. "script_plot": True,
  804. "script_source_file": "",
  805. "document_autocompleter": False,
  806. "document_text": "",
  807. "document_plot": True,
  808. "document_source_file": "",
  809. "document_font_color": '#000000',
  810. "document_sel_color": '#0055ff',
  811. "document_font_size": 6,
  812. "document_tab_size": 80,
  813. })
  814. # ############################################################
  815. # ############### Load defaults from file ####################
  816. # ############################################################
  817. self.old_defaults_found = False
  818. if user_defaults:
  819. self.load_defaults(filename='current_defaults')
  820. if self.defaults['units'] == 'MM':
  821. self.decimals = int(self.defaults['decimals_metric'])
  822. else:
  823. self.decimals = int(self.defaults['decimals_inch'])
  824. self.current_units = self.defaults['units']
  825. # #############################################################################
  826. # ##################### CREATE MULTIPROCESSING POOL ###########################
  827. # #############################################################################
  828. self.pool = Pool(processes=cpu_count())
  829. # ##########################################################################
  830. # ################## Setting the Splash Screen #############################
  831. # ##########################################################################
  832. splash_settings = QSettings("Open Source", "FlatCAM")
  833. if splash_settings.contains("splash_screen"):
  834. show_splash = splash_settings.value("splash_screen")
  835. else:
  836. splash_settings.setValue('splash_screen', 1)
  837. # This will write the setting to the platform specific storage.
  838. del splash_settings
  839. show_splash = 1
  840. if show_splash and self.cmd_line_headless != 1:
  841. splash_pix = QtGui.QPixmap('share/splash.png')
  842. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  843. # self.splash.setMask(splash_pix.mask())
  844. # move splashscreen to the current monitor
  845. desktop = QtWidgets.QApplication.desktop()
  846. screen = desktop.screenNumber(QtGui.QCursor.pos())
  847. current_screen_center = desktop.availableGeometry(screen).center()
  848. self.splash.move(current_screen_center - self.splash.rect().center())
  849. self.splash.show()
  850. self.splash.showMessage(_("FlatCAM is initializing ..."),
  851. alignment=Qt.AlignBottom | Qt.AlignLeft,
  852. color=QtGui.QColor("gray"))
  853. else:
  854. show_splash = 0
  855. # #############################################################################
  856. # ##################### Initialize GUI ########################################
  857. # #############################################################################
  858. # FlatCAM colors used in plotting
  859. self.FC_light_green = '#BBF268BF'
  860. self.FC_dark_green = '#006E20BF'
  861. self.FC_light_blue = '#a5a5ffbf'
  862. self.FC_dark_blue = '#0000ffbf'
  863. QtCore.QObject.__init__(self)
  864. self.ui = FlatCAMGUI(self)
  865. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  866. if theme_settings.contains("theme"):
  867. theme = theme_settings.value('theme', type=str)
  868. else:
  869. theme = 'white'
  870. if theme == 'white':
  871. self.cursor_color_3D = 'black'
  872. else:
  873. self.cursor_color_3D = 'gray'
  874. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  875. self.ui.final_save.connect(self.final_save)
  876. # restore the toolbar view
  877. self.restore_toolbar_view()
  878. # restore the GUI geometry
  879. self.restore_main_win_geom()
  880. # set FlatCAM units in the Status bar
  881. self.set_screen_units(self.defaults['units'])
  882. # #############################################################################
  883. # ######################## UPDATE PREFERENCES GUI FORMS #######################
  884. # #############################################################################
  885. # when adding entries here read the comments in the method found bellow named:
  886. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  887. self.defaults_form_fields = {
  888. # General App
  889. "decimals_inch": self.ui.general_defaults_form.general_app_group.precision_inch_entry,
  890. "decimals_metric": self.ui.general_defaults_form.general_app_group.precision_metric_entry,
  891. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  892. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  893. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  894. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  895. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  896. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  897. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  898. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  899. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  900. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  901. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  902. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  903. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  904. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  905. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_group.bm_limit_spinner,
  906. "global_machinist_setting": self.ui.general_defaults_form.general_app_group.machinist_cb,
  907. # General GUI Preferences
  908. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  909. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  910. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  911. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  912. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  913. "global_workspace_orientation": self.ui.general_defaults_form.general_gui_group.wk_orientation_radio,
  914. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  915. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  916. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  917. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  918. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  919. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  920. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  921. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  922. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  923. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  924. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  925. # General GUI Settings
  926. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  927. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  928. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  929. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  930. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  931. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  932. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  933. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  934. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  935. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  936. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  937. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  938. # Gerber General
  939. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  940. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  941. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  942. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  943. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  944. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  945. # Gerber Options
  946. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  947. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  948. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  949. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  950. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  951. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  952. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  953. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  954. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  955. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  956. # Gerber Advanced Options
  957. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  958. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  959. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  960. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  961. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  962. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  963. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  964. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  965. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  966. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  967. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  968. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  969. # Gerber Export
  970. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  971. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  972. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  973. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  974. # Gerber Editor
  975. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  976. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  977. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  978. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  979. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  980. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  981. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  982. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  983. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  984. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  985. "gerber_editor_circ_angle":
  986. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  987. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  988. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  989. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  990. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  991. # Excellon General
  992. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  993. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  994. "excellon_format_upper_in":
  995. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  996. "excellon_format_lower_in":
  997. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  998. "excellon_format_upper_mm":
  999. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1000. "excellon_format_lower_mm":
  1001. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1002. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  1003. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  1004. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  1005. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  1006. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  1007. # Excellon Options
  1008. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  1009. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  1010. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  1011. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  1012. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  1013. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  1014. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  1015. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  1016. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  1017. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  1018. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  1019. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  1020. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  1021. # Excellon Advanced Options
  1022. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  1023. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  1024. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  1025. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1026. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  1027. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  1028. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  1029. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  1030. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  1031. # Excellon Export
  1032. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  1033. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  1034. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  1035. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  1036. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  1037. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  1038. # Excellon Editor
  1039. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  1040. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  1041. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  1042. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  1043. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  1044. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  1045. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  1046. "excellon_editor_circ_angle":
  1047. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  1048. # Excellon Slots
  1049. "excellon_editor_slot_direction":
  1050. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  1051. "excellon_editor_slot_angle":
  1052. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  1053. "excellon_editor_slot_length":
  1054. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  1055. # Excellon Slots
  1056. "excellon_editor_slot_array_size":
  1057. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  1058. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  1059. "excellon_editor_slot_lin_pitch":
  1060. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  1061. "excellon_editor_slot_lin_angle":
  1062. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  1063. "excellon_editor_slot_circ_dir":
  1064. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  1065. "excellon_editor_slot_circ_angle":
  1066. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  1067. # Geometry General
  1068. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  1069. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  1070. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  1071. # Geometry Options
  1072. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  1073. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  1074. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  1075. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  1076. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  1077. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  1078. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  1079. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  1080. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  1081. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  1082. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  1083. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  1084. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  1085. # Geometry Advanced Options
  1086. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  1087. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  1088. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1089. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  1090. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  1091. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  1092. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  1093. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  1094. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  1095. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  1096. # Geometry Editor
  1097. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  1098. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  1099. # CNCJob General
  1100. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  1101. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  1102. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  1103. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  1104. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  1105. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  1106. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  1107. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  1108. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  1109. # CNC Job Options
  1110. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  1111. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  1112. # CNC Job Advanced Options
  1113. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  1114. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  1115. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  1116. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  1117. # NCC Tool
  1118. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  1119. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  1120. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  1121. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  1122. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  1123. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  1124. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  1125. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  1126. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  1127. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  1128. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  1129. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  1130. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  1131. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  1132. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  1133. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  1134. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  1135. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  1136. # CutOut Tool
  1137. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  1138. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  1139. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  1140. "tools_cutout_z": self.ui.tools_defaults_form.tools_cutout_group.cutz_entry,
  1141. "tools_cutout_depthperpass": self.ui.tools_defaults_form.tools_cutout_group.maxdepth_entry,
  1142. "tools_cutout_mdepth": self.ui.tools_defaults_form.tools_cutout_group.mpass_cb,
  1143. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  1144. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  1145. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  1146. # Paint Area Tool
  1147. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  1148. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  1149. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  1150. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  1151. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  1152. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  1153. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  1154. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  1155. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  1156. # 2-sided Tool
  1157. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  1158. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  1159. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  1160. # Film Tool
  1161. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  1162. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  1163. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  1164. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  1165. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  1166. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  1167. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  1168. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  1169. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  1170. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  1171. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  1172. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  1173. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  1174. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  1175. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  1176. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  1177. # Panelize Tool
  1178. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  1179. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  1180. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  1181. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  1182. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  1183. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  1184. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  1185. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  1186. # Calculators Tool
  1187. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  1188. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  1189. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  1190. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  1191. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  1192. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  1193. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  1194. # Transformations Tool
  1195. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  1196. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  1197. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  1198. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  1199. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  1200. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  1201. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  1202. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  1203. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  1204. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  1205. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  1206. # SolderPaste Dispensing Tool
  1207. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  1208. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  1209. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  1210. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  1211. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  1212. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  1213. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  1214. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  1215. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  1216. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  1217. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  1218. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  1219. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  1220. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  1221. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  1222. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  1223. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  1224. # ###################################################################################
  1225. # ################################ TOOLS 2 ##########################################
  1226. # ###################################################################################
  1227. # Optimal Tool
  1228. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  1229. # Check Rules Tool
  1230. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  1231. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  1232. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  1233. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  1234. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  1235. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  1236. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  1237. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  1238. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  1239. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  1240. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  1241. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  1242. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  1243. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  1244. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  1245. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  1246. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  1247. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  1248. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  1249. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  1250. # QRCode Tool
  1251. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  1252. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  1253. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  1254. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  1255. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  1256. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  1257. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  1258. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  1259. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  1260. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  1261. # Copper Thieving Tool
  1262. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  1263. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  1264. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  1265. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  1266. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  1267. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  1268. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  1269. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  1270. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  1271. "tools_copper_thieving_squares_spacing":
  1272. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  1273. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  1274. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  1275. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  1276. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  1277. "tools_copper_thieving_mask_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_ppm_entry,
  1278. # Fiducials Tool
  1279. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  1280. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  1281. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  1282. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  1283. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  1284. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  1285. # Calibration Tool
  1286. "tools_cal_calsource": self.ui.tools2_defaults_form.tools2_cal_group.cal_source_radio,
  1287. "tools_cal_travelz": self.ui.tools2_defaults_form.tools2_cal_group.travelz_entry,
  1288. "tools_cal_verz": self.ui.tools2_defaults_form.tools2_cal_group.verz_entry,
  1289. "tools_cal_zeroz": self.ui.tools2_defaults_form.tools2_cal_group.zeroz_cb,
  1290. "tools_cal_toolchangez": self.ui.tools2_defaults_form.tools2_cal_group.toolchangez_entry,
  1291. # Utilities
  1292. # File associations
  1293. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  1294. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  1295. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  1296. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  1297. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  1298. }
  1299. # update the Preferences GUI elements with the values in the self.defaults
  1300. self.defaults_write_form()
  1301. # When the self.defaults dictionary changes will update the Preferences GUI forms
  1302. self.defaults.set_change_callback(self.on_defaults_dict_change)
  1303. # #############################################################################
  1304. # ############################## Data #########################################
  1305. # #############################################################################
  1306. self.recent = []
  1307. self.recent_projects = []
  1308. self.clipboard = QtWidgets.QApplication.clipboard()
  1309. self.project_filename = None
  1310. self.toggle_units_ignore = False
  1311. # #############################################################################
  1312. # ########################## LOAD POSTPROCESSORS ##############################
  1313. # #############################################################################
  1314. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  1315. # the preprocessor file
  1316. self.preprocessors = load_preprocessors(self)
  1317. # make sure that always the 'default' preprocessor is the first item in the dictionary
  1318. if 'default' in self.preprocessors.keys():
  1319. new_ppp_dict = dict()
  1320. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  1321. default_pp = self.preprocessors.pop('default')
  1322. new_ppp_dict['default'] = default_pp
  1323. # then add the rest of the keys
  1324. for name, val_class in self.preprocessors.items():
  1325. new_ppp_dict[name] = val_class
  1326. # and now put back the ordered dict with 'default' key first
  1327. self.preprocessors = new_ppp_dict
  1328. for name in list(self.preprocessors.keys()):
  1329. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  1330. if name.partition('_')[0] == 'Paste':
  1331. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  1332. continue
  1333. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1334. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  1335. if name == 'hpgl':
  1336. continue
  1337. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1338. # #############################################################################
  1339. # ########################## LOAD LANGUAGES ##################################
  1340. # #############################################################################
  1341. self.languages = fcTranslate.load_languages()
  1342. for name in sorted(self.languages.values()):
  1343. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  1344. # #############################################################################
  1345. # ############################ APPLY APP LANGUAGE #############################
  1346. # #############################################################################
  1347. ret_val = fcTranslate.apply_language('strings')
  1348. if ret_val == "no language":
  1349. self.inform.emit('[ERROR] %s' %
  1350. _("Could not find the Language files. The App strings are missing."))
  1351. log.debug("Could not find the Language files. The App strings are missing.")
  1352. else:
  1353. # make the current language the current selection on the language combobox
  1354. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1355. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1356. # #############################################################################
  1357. # ########################### CREATE UNIQUE SERIAL NUMBER #####################
  1358. # #############################################################################
  1359. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1360. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1361. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1362. self.save_defaults(silent=True, first_time=True)
  1363. self.propagate_defaults(silent=True)
  1364. # def auto_save_defaults():
  1365. # try:
  1366. # self.save_defaults(silent=True)
  1367. # self.propagate_defaults(silent=True)
  1368. # finally:
  1369. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1370. # the following lines activates automatic defaults save
  1371. # if user_defaults:
  1372. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1373. # #############################################################################
  1374. # ########################### UPDATE THE OPTIONS ##############################
  1375. # #############################################################################
  1376. self.options = LoudDict()
  1377. # ----------------------------------------------------------------------------------------------------
  1378. # Update the self.options from the self.defaults
  1379. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1380. # -----------------------------------------------------------------------------------------------------
  1381. # Copy app defaults to project options
  1382. for def_key, def_val in self.defaults.items():
  1383. self.options[def_key] = deepcopy(def_val)
  1384. # self.options.update(self.defaults)
  1385. self.gen_form = None
  1386. self.ger_form = None
  1387. self.exc_form = None
  1388. self.geo_form = None
  1389. self.cnc_form = None
  1390. self.tools_form = None
  1391. self.tools2_form = None
  1392. self.fa_form = None
  1393. # Will show the Preferences GUI
  1394. self.show_preferences_gui()
  1395. # Initialize the color box's color in Preferences -> Global -> Color
  1396. self.init_color_pickers_in_preferences_gui()
  1397. # ### End of Data ####
  1398. # #############################################################################
  1399. # ######################## SETUP OBJECT COLLECTION ############################
  1400. # #############################################################################
  1401. self.collection = ObjectCollection(self)
  1402. self.ui.project_tab_layout.addWidget(self.collection.view)
  1403. # ### Adjust tabs width ## ##
  1404. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1405. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1406. self.collection.view.setMinimumWidth(290)
  1407. self.log.debug("Finished creating Object Collection.")
  1408. # #############################################################################
  1409. # ############################## SETUP Plot Area ##############################
  1410. # #############################################################################
  1411. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1412. if self.defaults["global_graphic_engine"] == '3D':
  1413. self.is_legacy = False
  1414. else:
  1415. self.is_legacy = True
  1416. # Event signals disconnect id holders
  1417. self.mp = None
  1418. self.mm = None
  1419. self.mr = None
  1420. self.mdc = None
  1421. self.mp_zc = None
  1422. # Matplotlib axis
  1423. self.axes = None
  1424. if show_splash:
  1425. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1426. "Canvas initialization started."),
  1427. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1428. color=QtGui.QColor("gray"))
  1429. start_plot_time = time.time() # debug
  1430. self.plotcanvas = None
  1431. self.app_cursor = None
  1432. self.hover_shapes = None
  1433. # setup the PlotCanvas
  1434. self.on_plotcanvas_setup()
  1435. end_plot_time = time.time()
  1436. self.used_time = end_plot_time - start_plot_time
  1437. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1438. if show_splash:
  1439. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1440. "Canvas initialization started.\n"
  1441. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1442. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1443. color=QtGui.QColor("gray"))
  1444. self.ui.splitter.setStretchFactor(1, 2)
  1445. # #############################################################################
  1446. # ################################### SYS TRAY ################################
  1447. # #############################################################################
  1448. if self.defaults["global_systray_icon"]:
  1449. self.parent_w = QtWidgets.QWidget()
  1450. if self.cmd_line_headless == 1:
  1451. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1452. headless=True,
  1453. parent=self.parent_w)
  1454. else:
  1455. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1456. parent=self.parent_w)
  1457. # #############################################################################
  1458. # ################################## Worker SETUP #############################
  1459. # #############################################################################
  1460. if self.defaults["global_worker_number"]:
  1461. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1462. else:
  1463. self.workers = WorkerStack(workers_number=2)
  1464. self.worker_task.connect(self.workers.add_task)
  1465. self.log.debug("Finished creating Workers crew.")
  1466. # #############################################################################
  1467. # ################################# Activity Monitor ##########################
  1468. # #############################################################################
  1469. self.activity_view = FlatCAMActivityView(app=self)
  1470. self.ui.infobar.addWidget(self.activity_view)
  1471. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1472. # #############################################################################
  1473. # ################################## Signal handling ##########################
  1474. # #############################################################################
  1475. # ################################# Custom signals ###########################
  1476. # signal for displaying messages in status bar
  1477. self.inform.connect(self.info)
  1478. # signal to be called when the app is quiting
  1479. self.app_quit.connect(self.quit_application)
  1480. self.message.connect(self.message_dialog)
  1481. self.progress.connect(self.set_progress_bar)
  1482. # signals that are emitted when object state changes
  1483. self.object_created.connect(self.on_object_created)
  1484. self.object_changed.connect(self.on_object_changed)
  1485. self.object_plotted.connect(self.on_object_plotted)
  1486. self.plots_updated.connect(self.on_plots_updated)
  1487. # signals emitted when file state change
  1488. self.file_opened.connect(self.register_recent)
  1489. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1490. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1491. # ############# Standard signals ###################
  1492. # ### Menu
  1493. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1494. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1495. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1496. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1497. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1498. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1499. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1500. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1501. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1502. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1503. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1504. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1505. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1506. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1507. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1508. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1509. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1510. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1511. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1512. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1513. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1514. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1515. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1516. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1517. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1518. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1519. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1520. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1521. self.ui.menufile_exit.triggered.connect(self.final_save)
  1522. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1523. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1524. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1525. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1526. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1527. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1528. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1529. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1530. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1531. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1532. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1533. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1534. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1535. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1536. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1537. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1538. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1539. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1540. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1541. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1542. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1543. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1544. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1545. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1546. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1547. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1548. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1549. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1550. self.ui.menuoptions_tools_db.triggered.connect(self.on_tools_database)
  1551. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1552. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1553. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1554. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1555. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1556. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1557. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1558. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1559. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1560. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1561. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1562. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1563. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1564. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1565. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1566. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1567. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1568. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1569. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1570. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1571. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1572. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1573. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1574. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1575. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1576. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1577. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1578. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1579. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1580. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1581. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1582. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1583. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1584. # ToolBar signals
  1585. self.connect_toolbar_signals()
  1586. # Notebook and Plot Tab Area signals
  1587. # make the right click on the notebook tab and plot tab area tab raise a menu
  1588. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1589. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1590. self.on_tab_setup_context_menu()
  1591. # activate initial state
  1592. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1593. # Context Menu
  1594. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1595. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1596. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1597. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1598. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1599. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1600. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1601. self.ui.clearplot.triggered.connect(self.clear_plots)
  1602. self.ui.replot.triggered.connect(self.plot_all)
  1603. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1604. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1605. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1606. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1607. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1608. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1609. # Preferences Plot Area TAB
  1610. self.ui.pref_save_button.clicked.connect(lambda: self.on_save_button(save_to_file=True))
  1611. self.ui.pref_apply_button.clicked.connect(lambda: self.on_save_button(save_to_file=False))
  1612. self.ui.pref_close_button.clicked.connect(self.on_pref_close_button)
  1613. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1614. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1615. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1616. # #############################################################################
  1617. # ######################### GUI PREFERENCES SIGNALS ###########################
  1618. # #############################################################################
  1619. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1620. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1621. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1622. )
  1623. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1624. lambda: self.on_toggle_units(no_pref=False))
  1625. # #############################################################################
  1626. # ############################# GUI COLORS SIGNALS ############################
  1627. # #############################################################################
  1628. # Setting plot colors signals
  1629. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1630. self.on_pf_color_entry)
  1631. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1632. self.on_pf_color_button)
  1633. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1634. self.on_pf_color_spinner)
  1635. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1636. self.on_pf_color_slider)
  1637. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1638. self.on_pl_color_entry)
  1639. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1640. self.on_pl_color_button)
  1641. # Setting selection (left - right) colors signals
  1642. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1643. self.on_sf_color_entry)
  1644. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1645. self.on_sf_color_button)
  1646. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1647. self.on_sf_color_spinner)
  1648. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1649. self.on_sf_color_slider)
  1650. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1651. self.on_sl_color_entry)
  1652. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1653. self.on_sl_color_button)
  1654. # Setting selection (right - left) colors signals
  1655. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1656. self.on_alt_sf_color_entry)
  1657. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1658. self.on_alt_sf_color_button)
  1659. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1660. self.on_alt_sf_color_spinner)
  1661. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1662. self.on_alt_sf_color_slider)
  1663. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1664. self.on_alt_sl_color_entry)
  1665. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1666. self.on_alt_sl_color_button)
  1667. # Setting Editor Draw colors signals
  1668. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1669. self.on_draw_color_entry)
  1670. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1671. self.on_draw_color_button)
  1672. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1673. self.on_sel_draw_color_entry)
  1674. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1675. self.on_sel_draw_color_button)
  1676. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1677. self.on_proj_color_entry)
  1678. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1679. self.on_proj_color_button)
  1680. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1681. self.on_proj_color_dis_entry)
  1682. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1683. self.on_proj_color_dis_button)
  1684. # ############################# workspace setting signals #####################
  1685. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1686. self.ui.general_defaults_form.general_gui_group.wk_orientation_radio.activated_custom.connect(
  1687. self.on_workspace_modified
  1688. )
  1689. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1690. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1691. # #############################################################################
  1692. # ############################# GUI SETTINGS SIGNALS ##########################
  1693. # #############################################################################
  1694. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1695. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1696. # ########## CNC Job related signals #############
  1697. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1698. self.on_cnc_custom_parameters)
  1699. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1700. self.on_annotation_fontcolor_entry)
  1701. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1702. self.on_annotation_fontcolor_button)
  1703. # ########## Tools related signals #############
  1704. # Film Tool
  1705. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1706. self.on_film_color_entry)
  1707. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1708. self.on_film_color_button)
  1709. # QRCode Tool
  1710. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1711. self.on_qrcode_fill_color_entry)
  1712. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1713. self.on_qrcode_fill_color_button)
  1714. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1715. self.on_qrcode_back_color_entry)
  1716. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1717. self.on_qrcode_back_color_button)
  1718. # portability changed signal
  1719. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1720. # Object list
  1721. self.collection.view.activated.connect(self.on_row_activated)
  1722. self.collection.item_selected.connect(self.on_row_selected)
  1723. self.object_status_changed.connect(self.on_collection_updated)
  1724. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1725. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1726. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1727. # Export Excellon parameters.
  1728. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1729. self.on_update_exc_export
  1730. )
  1731. # call it once to make sure it is updated at startup
  1732. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1733. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1734. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1735. self.on_excellon_defaults_button)
  1736. # when there are arguments at application startup this get launched
  1737. self.args_at_startup[list].connect(self.on_startup_args)
  1738. # #############################################################################
  1739. # ########################## FILE ASSOCIATIONS SIGNALS ########################
  1740. # #############################################################################
  1741. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1742. lambda: self.restore_extensions(ext_type='excellon'))
  1743. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1744. lambda: self.restore_extensions(ext_type='gcode'))
  1745. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1746. lambda: self.restore_extensions(ext_type='gerber'))
  1747. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1748. lambda: self.delete_all_extensions(ext_type='excellon'))
  1749. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1750. lambda: self.delete_all_extensions(ext_type='gcode'))
  1751. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1752. lambda: self.delete_all_extensions(ext_type='gerber'))
  1753. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1754. lambda: self.add_extension(ext_type='excellon'))
  1755. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1756. lambda: self.add_extension(ext_type='gcode'))
  1757. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1758. lambda: self.add_extension(ext_type='gerber'))
  1759. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1760. lambda: self.del_extension(ext_type='excellon'))
  1761. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1762. lambda: self.del_extension(ext_type='gcode'))
  1763. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1764. lambda: self.del_extension(ext_type='gerber'))
  1765. # connect the 'Apply' buttons from the Preferences/File Associations
  1766. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1767. lambda: self.on_register_files(obj_type='excellon'))
  1768. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1769. lambda: self.on_register_files(obj_type='gcode'))
  1770. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1771. lambda: self.on_register_files(obj_type='gerber'))
  1772. # #############################################################################
  1773. # ################################ KEYWORDS SIGNALS ###########################
  1774. # #############################################################################
  1775. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1776. lambda: self.restore_extensions(ext_type='keyword'))
  1777. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1778. lambda: self.delete_all_extensions(ext_type='keyword'))
  1779. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1780. lambda: self.add_extension(ext_type='keyword'))
  1781. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1782. lambda: self.del_extension(ext_type='keyword'))
  1783. # splash screen button signal
  1784. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1785. # connect the abort_all_tasks related slots to the related signals
  1786. self.proc_container.idle_flag.connect(self.app_is_idle)
  1787. # signal emitted when a tab is closed in the Plot Area
  1788. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1789. # #####################################################################################
  1790. # ########### FINISHED CONNECTING SIGNALS #############################################
  1791. # #####################################################################################
  1792. self.log.debug("Finished connecting Signals.")
  1793. # #####################################################################################
  1794. # ########################## Other setups #############################################
  1795. # #####################################################################################
  1796. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1797. # depending on from where those tools are called different actions can be done
  1798. self.call_source = 'app'
  1799. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1800. self.tool_tab_locked = False
  1801. # decide if to show or hide the Notebook side of the screen at startup
  1802. if self.defaults["global_project_at_startup"] is True:
  1803. self.ui.splitter.setSizes([1, 1])
  1804. else:
  1805. self.ui.splitter.setSizes([0, 1])
  1806. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1807. self.setup_obj_classes()
  1808. self.setup_component_editor()
  1809. # #####################################################################################
  1810. # ######################### Auto-complete KEYWORDS ####################################
  1811. # #####################################################################################
  1812. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1813. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1814. 'delete', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon', 'ee', 'export_exc',
  1815. 'export_gcode', 'export_gerber', 'egr', 'export_svg', 'ext', 'exteriors', 'follow',
  1816. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1817. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1818. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1819. 'mirror', 'ncc',
  1820. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1821. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1822. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1823. 'save', 'save_project',
  1824. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1825. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1826. 'version', 'write_gcode'
  1827. ]
  1828. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1829. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1830. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1831. 'axisoffset',
  1832. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1833. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1834. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1835. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1836. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1837. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1838. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1839. 'spacing_columns',
  1840. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'tooldia', 'use_threads', 'value',
  1841. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1842. ]
  1843. self.tcl_keywords = [
  1844. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1845. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1846. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1847. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1848. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1849. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1850. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1851. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1852. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1853. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1854. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1855. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1856. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1857. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1858. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1859. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1860. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1861. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1862. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1863. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1864. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1865. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1866. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1867. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1868. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1869. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1870. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1871. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1872. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1873. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1874. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1875. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1876. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1877. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1878. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1879. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1880. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1881. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1882. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1883. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1884. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1885. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1886. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1887. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1888. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1889. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1890. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1891. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1892. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1893. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1894. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1895. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1896. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1897. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1898. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1899. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1900. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1901. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1902. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1903. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1904. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1905. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1906. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1907. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1908. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1909. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1910. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1911. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1912. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1913. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1914. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1915. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1916. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1917. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1918. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1919. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1920. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1921. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1922. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1923. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1924. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1925. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1926. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1927. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1928. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1929. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1930. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1931. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1932. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1933. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1934. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1935. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1936. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1937. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1938. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1939. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1940. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1941. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1942. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1943. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1944. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1945. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1946. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1947. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1948. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1949. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1950. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1951. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1952. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1953. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1954. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1955. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1956. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1957. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1958. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1959. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1960. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1961. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1962. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1963. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1964. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1965. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1966. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1967. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1968. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1969. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1970. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1971. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1972. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1973. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1974. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1975. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1976. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1977. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1978. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1979. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1980. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1981. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1982. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1983. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1984. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1985. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1986. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1987. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1988. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1989. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1990. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1991. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1992. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1993. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1994. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1995. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1996. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1997. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1998. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1999. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2000. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2001. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2002. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2003. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2004. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2005. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2006. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2007. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2008. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2009. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2010. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2011. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2012. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2013. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2014. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2015. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2016. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2017. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2018. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2019. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2020. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2021. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2022. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2023. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2024. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2025. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2026. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2027. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2028. ]
  2029. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2030. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2031. # ####################################################################################
  2032. # ####################### Shell SETUP ################################################
  2033. # ####################################################################################
  2034. # this will hold the TCL instance
  2035. self.tcl = None
  2036. self.init_tcl()
  2037. self.shell = FCShell(self, version=self.version)
  2038. self.shell._edit.set_model_data(self.myKeywords)
  2039. self.shell.setWindowIcon(self.ui.app_icon)
  2040. self.shell.setWindowTitle("FlatCAM Shell")
  2041. self.shell.resize(*self.defaults["global_shell_shape"])
  2042. self.shell.append_output("FlatCAM %s - " % self.version)
  2043. self.shell.append_output(_("Type >help< to get started\n\n"))
  2044. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2045. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2046. self.ui.shell_dock.setWidget(self.shell)
  2047. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2048. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2049. QtWidgets.QDockWidget.DockWidgetFloatable |
  2050. QtWidgets.QDockWidget.DockWidgetClosable)
  2051. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2052. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2053. if self.defaults["global_shell_at_startup"]:
  2054. self.ui.shell_dock.show()
  2055. else:
  2056. self.ui.shell_dock.hide()
  2057. # ##################################################################################
  2058. # ###################### Tools and Plugins #########################################
  2059. # ##################################################################################
  2060. self.dblsidedtool = None
  2061. self.distance_tool = None
  2062. self.distance_min_tool = None
  2063. self.panelize_tool = None
  2064. self.film_tool = None
  2065. self.paste_tool = None
  2066. self.calculator_tool = None
  2067. self.rules_tool = None
  2068. self.sub_tool = None
  2069. self.move_tool = None
  2070. self.cutout_tool = None
  2071. self.ncclear_tool = None
  2072. self.optimal_tool = None
  2073. self.paint_tool = None
  2074. self.transform_tool = None
  2075. self.properties_tool = None
  2076. self.pdf_tool = None
  2077. self.image_tool = None
  2078. self.pcb_wizard_tool = None
  2079. self.cal_exc_tool = None
  2080. self.qrcode_tool = None
  2081. self.copper_thieving_tool = None
  2082. self.fiducial_tool = None
  2083. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2084. self.install_tools()
  2085. # ##################################################################################
  2086. # ########################### SETUP RECENT ITEMS ###################################
  2087. # ##################################################################################
  2088. self.setup_recent_items()
  2089. # ##################################################################################
  2090. # ########################### BookMarks Manager ####################################
  2091. # ##################################################################################
  2092. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2093. self.install_bookmarks()
  2094. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2095. # ##################################################################################
  2096. # ############################## Tools Database ####################################
  2097. # ##################################################################################
  2098. self.tools_db_tab = None
  2099. # ### System Font Parsing ###
  2100. # self.f_parse = ParseFont(self)
  2101. # self.parse_system_fonts()
  2102. # #####################################################################################
  2103. # ######################## Check for updates ##########################################
  2104. # #####################################################################################
  2105. # Separate thread (Not worker)
  2106. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2107. if (self.beta is False or self.beta is None) and \
  2108. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2109. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2110. self.thr2 = QtCore.QThread()
  2111. self.worker_task.emit({'fcn': self.version_check,
  2112. 'params': []})
  2113. self.thr2.start(QtCore.QThread.LowPriority)
  2114. # #####################################################################################
  2115. # ######################### Register files with FlatCAM; #############################
  2116. # ######################### It works only for Windows for now ########################
  2117. # #####################################################################################
  2118. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2119. self.on_register_files()
  2120. # #####################################################################################
  2121. # ###################### Variables for global usage ###################################
  2122. # #####################################################################################
  2123. # hold the App units
  2124. self.units = 'MM'
  2125. # coordinates for relative position display
  2126. self.rel_point1 = (0, 0)
  2127. self.rel_point2 = (0, 0)
  2128. # variable to store coordinates
  2129. self.pos = (0, 0)
  2130. self.pos_jump = (0, 0)
  2131. # variable to store mouse coordinates
  2132. self.mouse = [0, 0]
  2133. # decide if we have a double click or single click
  2134. self.doubleclick = False
  2135. # store here the is_dragging value
  2136. self.event_is_dragging = False
  2137. # variable to store if a command is active (then the var is not None) and which one it is
  2138. self.command_active = None
  2139. # variable to store the status of moving selection action
  2140. # None value means that it's not an selection action
  2141. # True value = a selection from left to right
  2142. # False value = a selection from right to left
  2143. self.selection_type = None
  2144. # List to store the objects that are currently loaded in FlatCAM
  2145. # This list is updated on each object creation or object delete
  2146. self.all_objects_list = list()
  2147. # List to store the objects that are selected
  2148. self.sel_objects_list = list()
  2149. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2150. self.key_modifiers = None
  2151. # Variable to hold the status of the axis
  2152. self.toggle_axis = True
  2153. # Variable to hold the status of the grid lines
  2154. self.toggle_grid_lines = True
  2155. # Variable to store the status of the fullscreen event
  2156. self.toggle_fscreen = False
  2157. # Variable to store the status of the code editor
  2158. self.toggle_codeeditor = False
  2159. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2160. self.click_noproject = False
  2161. self.cursor = None
  2162. # Variable to store the GCODE that was edited
  2163. self.gcode_edited = ""
  2164. self.text_editor_tab = None
  2165. # reference for the self.ui.code_editor
  2166. self.reference_code_editor = None
  2167. self.script_code = ''
  2168. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2169. self.preferences_changed_flag = False
  2170. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  2171. self.tools_db_changed_flag = False
  2172. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2173. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2174. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2175. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2176. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2177. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2178. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'plt', 'ply', 'rol',
  2179. 'sbp', 'tap', 'xpi']
  2180. self.svg_list = ['svg']
  2181. self.dxf_list = ['dxf']
  2182. self.pdf_list = ['pdf']
  2183. self.prj_list = ['flatprj']
  2184. self.conf_list = ['flatconfig']
  2185. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2186. # flag for polygons not cleared
  2187. self.poly_not_cleared = False
  2188. # VisPy visuals
  2189. self.isHovering = False
  2190. self.notHovering = True
  2191. # Window geometry
  2192. self.x_pos = None
  2193. self.y_pos = None
  2194. self.width = None
  2195. self.height = None
  2196. # when True, the app has to return from any thread
  2197. self.abort_flag = False
  2198. # set the value used in the Windows Title
  2199. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2200. # this holds a widget that is installed in the Plot Area when View Source option is used
  2201. self.source_editor_tab = None
  2202. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  2203. # VisPy visuals
  2204. if self.is_legacy is False:
  2205. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  2206. else:
  2207. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2208. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  2209. # ###############################################################################
  2210. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2211. # ############# It's done only once after install ###############
  2212. # ###############################################################################
  2213. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2214. fac_def_from_file = factory_file.read()
  2215. factory_defaults = json.loads(fac_def_from_file)
  2216. # if the file contain an empty dictionary then save the factory defaults into the file
  2217. if not factory_defaults:
  2218. self.save_factory_defaults(silent_message=False)
  2219. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2220. initial_lay = 'compact'
  2221. self.on_layout(lay=initial_lay)
  2222. # Set the combobox in Preferences to the current layout
  2223. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2224. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2225. factory_file.close()
  2226. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  2227. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2228. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2229. # after the first run, this object should be False
  2230. self.defaults["first_run"] = False
  2231. # ###############################################################################
  2232. # ################# ADDING FlatCAM EDITORS section ##############################
  2233. # ###############################################################################
  2234. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2235. # at the first launch of the App , the editors will not be functional.
  2236. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2237. self.exc_editor = FlatCAMExcEditor(self)
  2238. self.grb_editor = FlatCAMGrbEditor(self)
  2239. self.log.debug("Finished adding FlatCAM Editor's.")
  2240. self.set_ui_title(name=_("New Project - Not saved"))
  2241. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2242. current_platform = platform.architecture()[0]
  2243. if current_platform != '64bit':
  2244. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2245. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2246. # ###############################################################################
  2247. # ####################### Finished the CONSTRUCTOR ##############################
  2248. # ###############################################################################
  2249. App.log.debug("END of constructor. Releasing control.")
  2250. # #####################################################################################
  2251. # ########################## SHOW GUI #################################################
  2252. # #####################################################################################
  2253. # if the app is not started as headless, show it
  2254. if self.cmd_line_headless != 1:
  2255. if show_splash:
  2256. # finish the splash
  2257. self.splash.finish(self.ui)
  2258. mgui_settings = QSettings("Open Source", "FlatCAM")
  2259. if mgui_settings.contains("maximized_gui"):
  2260. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  2261. if maximized_ui is True:
  2262. self.ui.showMaximized()
  2263. else:
  2264. self.ui.show()
  2265. else:
  2266. self.ui.show()
  2267. if self.defaults["global_systray_icon"]:
  2268. self.trayIcon.show()
  2269. else:
  2270. log.warning("******************* RUNNING HEADLESS *******************")
  2271. # #####################################################################################
  2272. # ########################## START-UP ARGUMENTS #######################################
  2273. # #####################################################################################
  2274. # test if the program was started with a script as parameter
  2275. if self.cmd_line_shellvar:
  2276. try:
  2277. cnt = 0
  2278. command_tcl = 0
  2279. for i in self.cmd_line_shellvar.split(','):
  2280. if i is not None:
  2281. # noinspection PyBroadException
  2282. try:
  2283. command_tcl = eval(i)
  2284. except Exception:
  2285. command_tcl = i
  2286. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2287. cnt += 1
  2288. # if there are Windows paths then replace the path separator with a Unix like one
  2289. if sys.platform == 'win32':
  2290. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2291. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2292. except Exception as ext:
  2293. print("ERROR: ", ext)
  2294. sys.exit(2)
  2295. if self.cmd_line_shellfile:
  2296. try:
  2297. if self.ui.shell_dock.isHidden():
  2298. self.ui.shell_dock.show()
  2299. with open(self.cmd_line_shellfile, "r") as myfile:
  2300. if show_splash:
  2301. self.splash.showMessage('%s: %ssec\n%s' % (
  2302. _("Canvas initialization started.\n"
  2303. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2304. _("Executing Tcl Script ...")),
  2305. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2306. color=QtGui.QColor("gray"))
  2307. cmd_line_shellfile_text = myfile.read()
  2308. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2309. except Exception as ext:
  2310. print("ERROR: ", ext)
  2311. sys.exit(2)
  2312. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2313. # the path/file_name must be enclosed in quotes if it contain spaces
  2314. if App.args:
  2315. self.args_at_startup.emit(App.args)
  2316. if self.old_defaults_found is True:
  2317. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  2318. "Please reboot the application to update."))
  2319. self.old_defaults_found = False
  2320. @staticmethod
  2321. def copy_and_overwrite(from_path, to_path):
  2322. """
  2323. From here:
  2324. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2325. :param from_path: source path
  2326. :param to_path: destination path
  2327. :return: None
  2328. """
  2329. if os.path.exists(to_path):
  2330. shutil.rmtree(to_path)
  2331. try:
  2332. shutil.copytree(from_path, to_path)
  2333. except FileNotFoundError:
  2334. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2335. shutil.copytree(from_new_path, to_path)
  2336. def on_startup_args(self, args, silent=False):
  2337. """
  2338. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2339. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  2340. :param args: a list containing the application args at startup
  2341. :return: None
  2342. """
  2343. if args is not None:
  2344. args_to_process = args
  2345. else:
  2346. args_to_process = App.args
  2347. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2348. for argument in args_to_process:
  2349. if '.FlatPrj'.lower() in argument.lower():
  2350. try:
  2351. project_name = str(argument)
  2352. if project_name == "":
  2353. if silent is False:
  2354. self.inform.emit(_("Open cancelled."))
  2355. else:
  2356. # self.open_project(project_name)
  2357. run_from_arg = True
  2358. # self.worker_task.emit({'fcn': self.open_project,
  2359. # 'params': [project_name, run_from_arg]})
  2360. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2361. except Exception as e:
  2362. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2363. elif '.FlatConfig'.lower() in argument.lower():
  2364. try:
  2365. file_name = str(argument)
  2366. if file_name == "":
  2367. if silent is False:
  2368. self.inform.emit(_("Open Config file failed."))
  2369. else:
  2370. run_from_arg = True
  2371. # self.worker_task.emit({'fcn': self.open_config_file,
  2372. # 'params': [file_name, run_from_arg]})
  2373. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2374. except Exception as e:
  2375. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2376. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2377. try:
  2378. file_name = str(argument)
  2379. if file_name == "":
  2380. if silent is False:
  2381. self.inform.emit(_("Open Script file failed."))
  2382. else:
  2383. if silent is False:
  2384. self.on_fileopenscript(name=file_name)
  2385. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2386. self.on_filerunscript(name=file_name)
  2387. except Exception as e:
  2388. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2389. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2390. log.debug("App.on_startup_args() --> Quit event.")
  2391. sys.exit()
  2392. elif 'save'.lower() in argument.lower():
  2393. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2394. self.save_defaults()
  2395. else:
  2396. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2397. proc_arg = argument.lower()
  2398. for ext in exc_list:
  2399. proc_ext = ext.replace(' ', '')
  2400. proc_ext = '.%s' % proc_ext
  2401. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2402. file_name = str(argument)
  2403. if file_name == "":
  2404. if silent is False:
  2405. self.inform.emit(_("Open Excellon file failed."))
  2406. else:
  2407. self.on_fileopenexcellon(name=file_name)
  2408. return
  2409. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2410. for ext in gco_list:
  2411. proc_ext = ext.replace(' ', '')
  2412. proc_ext = '.%s' % proc_ext
  2413. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2414. file_name = str(argument)
  2415. if file_name == "":
  2416. if silent is False:
  2417. self.inform.emit(_("Open GCode file failed."))
  2418. else:
  2419. self.on_fileopengcode(name=file_name)
  2420. return
  2421. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2422. for ext in grb_list:
  2423. proc_ext = ext.replace(' ', '')
  2424. proc_ext = '.%s' % proc_ext
  2425. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2426. file_name = str(argument)
  2427. if file_name == "":
  2428. if silent is False:
  2429. self.inform.emit(_("Open Gerber file failed."))
  2430. else:
  2431. self.on_fileopengerber(name=file_name)
  2432. return
  2433. # if it reached here without already returning then the app was registered with a file that it does not
  2434. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2435. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2436. # for arg in args_to_process:
  2437. # if 'FlatCAM.exe' in arg:
  2438. # continue
  2439. # else:
  2440. # sys.exit(2)
  2441. def set_ui_title(self, name):
  2442. """
  2443. Sets the title of the main window.
  2444. :param name: String that store the project path and project name
  2445. :return: None
  2446. """
  2447. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2448. (self.version,
  2449. ('BETA' if self.beta else ''),
  2450. platform.architecture()[0],
  2451. self.engine,
  2452. name)
  2453. )
  2454. def on_theme_change(self, val):
  2455. t_settings = QSettings("Open Source", "FlatCAM")
  2456. t_settings.setValue('theme', val)
  2457. # This will write the setting to the platform specific storage.
  2458. del t_settings
  2459. self.on_app_restart()
  2460. def on_app_restart(self):
  2461. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2462. # be left in the SySTray
  2463. try:
  2464. self.trayIcon.hide()
  2465. except Exception:
  2466. pass
  2467. fcTranslate.restart_program(app=self)
  2468. def defaults_read_form(self):
  2469. """
  2470. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2471. :return: None
  2472. """
  2473. for option in self.defaults_form_fields:
  2474. try:
  2475. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2476. except Exception as e:
  2477. log.debug("App.defaults_read_form() --> %s" % str(e))
  2478. def defaults_write_form(self, factor=None, fl_units=None):
  2479. """
  2480. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2481. self.defaults dictionary.
  2482. :param factor: will apply a factor to the values that written in the GUI elements
  2483. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2484. :return: None
  2485. """
  2486. for option in self.defaults:
  2487. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2488. # try:
  2489. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2490. # except KeyError:
  2491. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2492. # # TODO: Rethink this?
  2493. # pass
  2494. def defaults_write_form_field(self, field, factor=None, units=None):
  2495. """
  2496. Basically it is the worker in the self.defaults_write_form()
  2497. :param field: the GUI element in Preferences GUI to be updated
  2498. :param factor: factor to be applied to the field parameter
  2499. :param units: current FLatCAM measuring units
  2500. :return: None, it updates GUI elements
  2501. """
  2502. try:
  2503. if factor is None:
  2504. if units is None:
  2505. self.defaults_form_fields[field].set_value(self.defaults[field])
  2506. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2507. self.defaults_form_fields[field].set_value(self.defaults[field])
  2508. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2509. self.defaults_form_fields[field].set_value(self.defaults[field])
  2510. else:
  2511. if units is None:
  2512. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2513. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2514. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2515. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2516. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2517. except KeyError:
  2518. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2519. # TODO: Rethink this?
  2520. pass
  2521. except AttributeError:
  2522. log.debug(field)
  2523. def clear_pool(self):
  2524. """
  2525. Clear the multiprocessing pool and calls garbage collector.
  2526. :return: None
  2527. """
  2528. self.pool.close()
  2529. self.pool = Pool()
  2530. self.pool_recreated.emit(self.pool)
  2531. gc.collect()
  2532. def install_tools(self):
  2533. """
  2534. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2535. Instantiation of the Tools classes.
  2536. The order that the tools are installed is important as they can depend on each other install position.
  2537. :return: None
  2538. """
  2539. self.dblsidedtool = DblSidedTool(self)
  2540. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2541. self.cal_exc_tool = ToolCalibration(self)
  2542. self.cal_exc_tool.install(icon=QtGui.QIcon('share/drill16.png'), pos=self.ui.menutool,
  2543. before=self.dblsidedtool.menuAction,
  2544. separator=False)
  2545. self.distance_tool = Distance(self)
  2546. self.distance_tool.install(icon=QtGui.QIcon('share/distance16.png'), pos=self.ui.menuedit,
  2547. before=self.ui.menueditorigin,
  2548. separator=False)
  2549. self.distance_min_tool = DistanceMin(self)
  2550. self.distance_min_tool.install(icon=QtGui.QIcon('share/distance_min16.png'), pos=self.ui.menuedit,
  2551. before=self.ui.menueditorigin,
  2552. separator=True)
  2553. self.panelize_tool = Panelize(self)
  2554. self.panelize_tool.install(icon=QtGui.QIcon('share/panelize16.png'))
  2555. self.film_tool = Film(self)
  2556. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2557. self.paste_tool = SolderPaste(self)
  2558. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2559. self.calculator_tool = ToolCalculator(self)
  2560. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator16.png'), separator=True)
  2561. self.sub_tool = ToolSub(self)
  2562. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2563. self.rules_tool = RulesCheck(self)
  2564. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2565. self.optimal_tool = ToolOptimal(self)
  2566. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2567. self.move_tool = ToolMove(self)
  2568. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2569. before=self.ui.menueditorigin, separator=True)
  2570. self.cutout_tool = CutOut(self)
  2571. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2572. before=self.sub_tool.menuAction)
  2573. self.ncclear_tool = NonCopperClear(self)
  2574. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2575. before=self.sub_tool.menuAction, separator=True)
  2576. self.paint_tool = ToolPaint(self)
  2577. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2578. before=self.sub_tool.menuAction, separator=True)
  2579. self.copper_thieving_tool = ToolCopperThieving(self)
  2580. self.copper_thieving_tool.install(icon=QtGui.QIcon('share/copperfill32.png'), pos=self.ui.menutool)
  2581. self.fiducial_tool = ToolFiducials(self)
  2582. self.fiducial_tool.install(icon=QtGui.QIcon('share/fiducials_32.png'), pos=self.ui.menutool)
  2583. self.qrcode_tool = QRCode(self)
  2584. self.qrcode_tool.install(icon=QtGui.QIcon('share/qrcode32.png'), pos=self.ui.menutool)
  2585. self.transform_tool = ToolTransform(self)
  2586. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2587. self.properties_tool = Properties(self)
  2588. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2589. self.pdf_tool = ToolPDF(self)
  2590. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2591. separator=True)
  2592. self.image_tool = ToolImage(self)
  2593. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2594. separator=True)
  2595. self.pcb_wizard_tool = PcbWizard(self)
  2596. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2597. self.log.debug("Tools are installed.")
  2598. def remove_tools(self):
  2599. """
  2600. Will remove all the actions in the Tool menu.
  2601. :return: None
  2602. """
  2603. for act in self.ui.menutool.actions():
  2604. self.ui.menutool.removeAction(act)
  2605. def init_tools(self):
  2606. """
  2607. Initialize the Tool tab in the notebook side of the central widget.
  2608. Remove the actions in the Tools menu.
  2609. Instantiate again the FlatCAM tools (plugins).
  2610. All this is required when changing the layout: standard, compact etc.
  2611. :return: None
  2612. """
  2613. log.debug("init_tools()")
  2614. # delete the data currently in the Tools Tab and the Tab itself
  2615. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2616. if widget is not None:
  2617. widget.deleteLater()
  2618. self.ui.notebook.removeTab(2)
  2619. # rebuild the Tools Tab
  2620. self.ui.tool_tab = QtWidgets.QWidget()
  2621. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2622. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2623. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2624. self.ui.tool_scroll_area = VerticalScrollArea()
  2625. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2626. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2627. # first remove all of them
  2628. self.remove_tools()
  2629. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2630. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2631. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2632. # third install all of them
  2633. self.install_tools()
  2634. self.log.debug("Tools are initialized.")
  2635. # def parse_system_fonts(self):
  2636. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2637. # 'params': []})
  2638. def connect_toolbar_signals(self):
  2639. """
  2640. Reconnect the signals to the actions in the toolbar.
  2641. This has to be done each time after the FlatCAM tools are removed/installed.
  2642. :return: None
  2643. """
  2644. # Toolbar
  2645. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2646. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2647. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2648. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2649. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2650. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2651. self.ui.replot_btn.triggered.connect(self.plot_all)
  2652. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2653. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2654. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2655. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2656. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2657. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2658. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2659. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2660. self.ui.copy_btn.triggered.connect(self.on_copy_object)
  2661. self.ui.delete_btn.triggered.connect(self.on_delete)
  2662. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2663. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2664. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2665. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2666. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2667. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2668. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2669. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2670. # Tools Toolbar Signals
  2671. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2672. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2673. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2674. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2675. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2676. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2677. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2678. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2679. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2680. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2681. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2682. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2683. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2684. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2685. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2686. def object2editor(self):
  2687. """
  2688. Send the current Geometry or Excellon object (if any) into the it's editor.
  2689. :return: None
  2690. """
  2691. self.report_usage("object2editor()")
  2692. # disable the objects menu as it may interfere with the Editors
  2693. self.ui.menuobjects.setDisabled(True)
  2694. edited_object = self.collection.get_active()
  2695. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2696. isinstance(edited_object, FlatCAMExcellon):
  2697. pass
  2698. else:
  2699. self.inform.emit('[WARNING_NOTCL] %s' %
  2700. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2701. return
  2702. if isinstance(edited_object, FlatCAMGeometry):
  2703. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2704. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2705. # we set the notebook to hidden
  2706. self.ui.splitter.setSizes([0, 1])
  2707. if edited_object.multigeo is True:
  2708. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2709. if len(sel_rows) > 1:
  2710. self.inform.emit('[WARNING_NOTCL] %s' %
  2711. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2712. "is not possible.\n"
  2713. "Edit only one geometry at a time."))
  2714. # determine the tool dia of the selected tool
  2715. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2716. # now find the key in the edited_object.tools that has this tooldia
  2717. multi_tool = 1
  2718. for tool in edited_object.tools:
  2719. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2720. multi_tool = tool
  2721. break
  2722. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2723. else:
  2724. self.geo_editor.edit_fcgeometry(edited_object)
  2725. # set call source to the Editor we go into
  2726. self.call_source = 'geo_editor'
  2727. elif isinstance(edited_object, FlatCAMExcellon):
  2728. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2729. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2730. if self.ui.splitter.sizes()[0] == 0:
  2731. self.ui.splitter.setSizes([1, 1])
  2732. self.exc_editor.edit_fcexcellon(edited_object)
  2733. # set call source to the Editor we go into
  2734. self.call_source = 'exc_editor'
  2735. elif isinstance(edited_object, FlatCAMGerber):
  2736. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2737. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2738. if self.ui.splitter.sizes()[0] == 0:
  2739. self.ui.splitter.setSizes([1, 1])
  2740. self.grb_editor.edit_fcgerber(edited_object)
  2741. # set call source to the Editor we go into
  2742. self.call_source = 'grb_editor'
  2743. # make sure that we can't select another object while in Editor Mode:
  2744. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2745. self.ui.project_frame.setDisabled(True)
  2746. # delete any selection shape that might be active as they are not relevant in Editor
  2747. self.delete_selection_shape()
  2748. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2749. self.ui.plot_tab_area.protectTab(0)
  2750. self.inform.emit('[WARNING_NOTCL] %s' %
  2751. _("Editor is activated ..."))
  2752. self.should_we_save = True
  2753. def editor2object(self, cleanup=None):
  2754. """
  2755. Transfers the Geometry or Excellon from it's editor to the current object.
  2756. :return: None
  2757. """
  2758. self.report_usage("editor2object()")
  2759. # re-enable the objects menu that was disabled on entry in Editor mode
  2760. self.ui.menuobjects.setDisabled(False)
  2761. # do not update a geometry or excellon object unless it comes out of an editor
  2762. if self.call_source != 'app':
  2763. edited_obj = self.collection.get_active()
  2764. if cleanup is None:
  2765. msgbox = QtWidgets.QMessageBox()
  2766. msgbox.setText(_("Do you want to save the edited object?"))
  2767. msgbox.setWindowTitle(_("Close Editor"))
  2768. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2769. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2770. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2771. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2772. msgbox.setDefaultButton(bt_yes)
  2773. msgbox.exec_()
  2774. response = msgbox.clickedButton()
  2775. if response == bt_yes:
  2776. # clean the Tools Tab
  2777. self.ui.tool_scroll_area.takeWidget()
  2778. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2779. self.ui.notebook.setTabText(2, "Tool")
  2780. if isinstance(edited_obj, FlatCAMGeometry):
  2781. obj_type = "Geometry"
  2782. if cleanup is None:
  2783. self.geo_editor.update_fcgeometry(edited_obj)
  2784. self.geo_editor.update_options(edited_obj)
  2785. self.geo_editor.deactivate()
  2786. # update the geo object options so it is including the bounding box values
  2787. try:
  2788. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2789. edited_obj.options['xmin'] = xmin
  2790. edited_obj.options['ymin'] = ymin
  2791. edited_obj.options['xmax'] = xmax
  2792. edited_obj.options['ymax'] = ymax
  2793. except AttributeError as e:
  2794. self.inform.emit('[WARNING] %s' %
  2795. _("Object empty after edit."))
  2796. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2797. elif isinstance(edited_obj, FlatCAMGerber):
  2798. obj_type = "Gerber"
  2799. if cleanup is None:
  2800. self.grb_editor.update_fcgerber()
  2801. self.grb_editor.update_options(edited_obj)
  2802. self.grb_editor.deactivate_grb_editor()
  2803. # delete the old object (the source object) if it was an empty one
  2804. try:
  2805. if len(edited_obj.solid_geometry) == 0:
  2806. old_name = edited_obj.options['name']
  2807. self.collection.set_active(old_name)
  2808. self.collection.delete_active()
  2809. except TypeError:
  2810. # if the solid_geometry is a single Polygon the len() will not work
  2811. # in any case, falling here means that we have something in the solid_geometry, even if only
  2812. # a single Polygon, therefore we pass this
  2813. pass
  2814. # restore GUI to the Selected TAB
  2815. # Remove anything else in the GUI
  2816. self.ui.selected_scroll_area.takeWidget()
  2817. # Switch notebook to Selected page
  2818. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2819. elif isinstance(edited_obj, FlatCAMExcellon):
  2820. obj_type = "Excellon"
  2821. if cleanup is None:
  2822. self.exc_editor.update_fcexcellon(edited_obj)
  2823. self.exc_editor.update_options(edited_obj)
  2824. self.exc_editor.deactivate()
  2825. # delete the old object (the source object) if it was an empty one
  2826. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2827. old_name = edited_obj.options['name']
  2828. self.collection.set_active(old_name)
  2829. self.collection.delete_active()
  2830. # restore GUI to the Selected TAB
  2831. # Remove anything else in the GUI
  2832. self.ui.tool_scroll_area.takeWidget()
  2833. # Switch notebook to Selected page
  2834. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2835. else:
  2836. self.inform.emit('[WARNING_NOTCL] %s' %
  2837. _("Select a Gerber, Geometry or Excellon Object to update."))
  2838. return
  2839. self.inform.emit('[selected] %s %s' %
  2840. (obj_type, _("is updated, returning to App...")))
  2841. elif response == bt_no:
  2842. # clean the Tools Tab
  2843. self.ui.tool_scroll_area.takeWidget()
  2844. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2845. self.ui.notebook.setTabText(2, "Tool")
  2846. if isinstance(edited_obj, FlatCAMGeometry):
  2847. self.geo_editor.deactivate()
  2848. elif isinstance(edited_obj, FlatCAMGerber):
  2849. self.grb_editor.deactivate_grb_editor()
  2850. elif isinstance(edited_obj, FlatCAMExcellon):
  2851. self.exc_editor.deactivate()
  2852. # set focus on the project tab
  2853. else:
  2854. self.inform.emit('[WARNING_NOTCL] %s' %
  2855. _("Select a Gerber, Geometry or Excellon Object to update."))
  2856. return
  2857. edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2858. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2859. elif response == bt_cancel:
  2860. return
  2861. else:
  2862. if isinstance(edited_obj, FlatCAMGeometry):
  2863. self.geo_editor.deactivate()
  2864. elif isinstance(edited_obj, FlatCAMGerber):
  2865. self.grb_editor.deactivate_grb_editor()
  2866. elif isinstance(edited_obj, FlatCAMExcellon):
  2867. self.exc_editor.deactivate()
  2868. else:
  2869. self.inform.emit('[WARNING_NOTCL] %s' %
  2870. _("Select a Gerber, Geometry or Excellon Object to update."))
  2871. return
  2872. # if notebook is hidden we show it
  2873. if self.ui.splitter.sizes()[0] == 0:
  2874. self.ui.splitter.setSizes([1, 1])
  2875. # restore the call_source to app
  2876. self.call_source = 'app'
  2877. edited_obj.plot()
  2878. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2879. self.ui.plot_tab_area.protectTab(0)
  2880. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2881. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2882. self.ui.project_frame.setDisabled(False)
  2883. def get_last_folder(self):
  2884. """
  2885. Get the folder path from where the last file was opened.
  2886. :return: String, last opened folder path
  2887. """
  2888. return self.defaults["global_last_folder"]
  2889. def get_last_save_folder(self):
  2890. """
  2891. Get the folder path from where the last file was saved.
  2892. :return: String, last saved folder path
  2893. """
  2894. loc = self.defaults["global_last_save_folder"]
  2895. if loc is None:
  2896. loc = self.defaults["global_last_folder"]
  2897. if loc is None:
  2898. loc = os.path.dirname(__file__)
  2899. return loc
  2900. def report_usage(self, resource):
  2901. """
  2902. Increments usage counter for the given resource
  2903. in self.defaults['global_stats'].
  2904. :param resource: Name of the resource.
  2905. :return: None
  2906. """
  2907. if resource in self.defaults['global_stats']:
  2908. self.defaults['global_stats'][resource] += 1
  2909. else:
  2910. self.defaults['global_stats'][resource] = 1
  2911. def init_tcl(self):
  2912. """
  2913. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2914. :return: None
  2915. """
  2916. if hasattr(self, 'tcl') and self.tcl is not None:
  2917. # self.tcl = None
  2918. # TODO we need to clean non default variables and procedures here
  2919. # new object cannot be used here as it will not remember values created for next passes,
  2920. # because tcl was execudted in old instance of TCL
  2921. pass
  2922. else:
  2923. self.tcl = tk.Tcl()
  2924. self.setup_shell()
  2925. self.log.debug("TCL Shell has been initialized.")
  2926. # TODO: This shouldn't be here.
  2927. class TclErrorException(Exception):
  2928. """
  2929. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2930. """
  2931. pass
  2932. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2933. """
  2934. Shows a message on the FlatCAM Shell
  2935. :param msg: Message to display.
  2936. :param show: Opens the shell.
  2937. :param error: Shows the message as an error.
  2938. :param warning: Shows the message as an warning.
  2939. :param success: Shows the message as an success.
  2940. :param selected: Indicate that something was selected on canvas
  2941. :return: None
  2942. """
  2943. if show:
  2944. self.ui.shell_dock.show()
  2945. try:
  2946. if error:
  2947. self.shell.append_error(msg + "\n")
  2948. elif warning:
  2949. self.shell.append_warning(msg + "\n")
  2950. elif success:
  2951. self.shell.append_success(msg + "\n")
  2952. elif selected:
  2953. self.shell.append_selected(msg + "\n")
  2954. else:
  2955. self.shell.append_output(msg + "\n")
  2956. except AttributeError:
  2957. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2958. def raise_tcl_unknown_error(self, unknownException):
  2959. """
  2960. Raise exception if is different type than TclErrorException
  2961. this is here mainly to show unknown errors inside TCL shell console.
  2962. :param unknownException:
  2963. :return:
  2964. """
  2965. if not isinstance(unknownException, self.TclErrorException):
  2966. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2967. else:
  2968. raise unknownException
  2969. def display_tcl_error(self, error, error_info=None):
  2970. """
  2971. Escape bracket [ with '\' otherwise there is error
  2972. "ERROR: missing close-bracket" instead of real error
  2973. :param error: it may be text or exception
  2974. :param error_info: Some informations about the error
  2975. :return: None
  2976. """
  2977. if isinstance(error, Exception):
  2978. exc_type, exc_value, exc_traceback = error_info
  2979. if not isinstance(error, self.TclErrorException):
  2980. show_trace = 1
  2981. else:
  2982. show_trace = int(self.defaults['global_verbose_error_level'])
  2983. if show_trace > 0:
  2984. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2985. trc_formated = []
  2986. for a in reversed(trc):
  2987. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2988. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2989. else:
  2990. text = "%s" % error
  2991. else:
  2992. text = error
  2993. text = text.replace('[', '\\[').replace('"', '\\"')
  2994. self.tcl.eval('return -code error "%s"' % text)
  2995. def raise_tcl_error(self, text):
  2996. """
  2997. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2998. :param text: text of error
  2999. :return: raise exception
  3000. """
  3001. self.display_tcl_error(text)
  3002. raise self.TclErrorException(text)
  3003. def exec_command(self, text, no_echo=False):
  3004. """
  3005. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3006. Also handles execution in separated threads
  3007. :param text: FlatCAM TclCommand with parameters
  3008. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3009. will create crashes of the _Expandable_Edit widget
  3010. :return: output if there was any
  3011. """
  3012. self.report_usage('exec_command')
  3013. result = self.exec_command_test(text, False, no_echo=no_echo)
  3014. # MS: added this method call so the geometry is updated once the TCL command is executed
  3015. # if no_plot is None:
  3016. # self.plot_all()
  3017. return result
  3018. def exec_command_test(self, text, reraise=True, no_echo=False):
  3019. """
  3020. Same as exec_command(...) with additional control over exceptions.
  3021. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3022. :param text: Input command
  3023. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  3024. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3025. will create crashes of the _Expandable_Edit widget
  3026. :return: Output from the command
  3027. """
  3028. tcl_command_string = str(text)
  3029. try:
  3030. if no_echo is False:
  3031. self.shell.open_proccessing() # Disables input box.
  3032. result = self.tcl.eval(str(tcl_command_string))
  3033. if result != 'None' and no_echo is False:
  3034. self.shell.append_output(result + '\n')
  3035. except tk.TclError as e:
  3036. # This will display more precise answer if something in TCL shell fails
  3037. result = self.tcl.eval("set errorInfo")
  3038. self.log.error("Exec command Exception: %s" % (result + '\n'))
  3039. if no_echo is False:
  3040. self.shell.append_error('ERROR: ' + result + '\n')
  3041. # Show error in console and just return or in test raise exception
  3042. if reraise:
  3043. raise e
  3044. finally:
  3045. if no_echo is False:
  3046. self.shell.close_proccessing()
  3047. pass
  3048. return result
  3049. # """
  3050. # Code below is unsused. Saved for later.
  3051. # """
  3052. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3053. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3054. # self.log.debug(parts)
  3055. # try:
  3056. # if parts[0] not in commands:
  3057. # self.shell.append_error("Unknown command\n")
  3058. # return
  3059. #
  3060. # #import inspect
  3061. # #inspect.getargspec(someMethod)
  3062. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3063. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3064. # self.shell.append_error(
  3065. # "Command %s takes %d arguments. %d given.\n" %
  3066. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3067. # )
  3068. # return
  3069. #
  3070. # cmdfcn = commands[parts[0]]["fcn"]
  3071. # cmdconv = commands[parts[0]]["converters"]
  3072. # if len(parts) - 1 > 0:
  3073. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3074. # else:
  3075. # retval = cmdfcn()
  3076. # retfcn = commands[parts[0]]["retfcn"]
  3077. # if retval and retfcn(retval):
  3078. # self.shell.append_output(retfcn(retval) + "\n")
  3079. #
  3080. # except Exception as e:
  3081. # #self.shell.append_error(''.join(traceback.format_exc()))
  3082. # #self.shell.append_error("?\n")
  3083. # self.shell.append_error(str(e) + "\n")
  3084. def info(self, msg):
  3085. """
  3086. Informs the user. Normally on the status bar, optionally
  3087. also on the shell.
  3088. :param msg: Text to write.
  3089. :return: None
  3090. """
  3091. # Type of message in brackets at the beginning of the message.
  3092. match = re.search("\[([^\]]+)\](.*)", msg)
  3093. if match:
  3094. level = match.group(1)
  3095. msg_ = match.group(2)
  3096. self.ui.fcinfo.set_status(str(msg_), level=level)
  3097. if level.lower() == "error":
  3098. self.shell_message(msg, error=True, show=True)
  3099. elif level.lower() == "warning":
  3100. self.shell_message(msg, warning=True, show=True)
  3101. elif level.lower() == "error_notcl":
  3102. self.shell_message(msg, error=True, show=False)
  3103. elif level.lower() == "warning_notcl":
  3104. self.shell_message(msg, warning=True, show=False)
  3105. elif level.lower() == "success":
  3106. self.shell_message(msg, success=True, show=False)
  3107. elif level.lower() == "selected":
  3108. self.shell_message(msg, selected=True, show=False)
  3109. else:
  3110. self.shell_message(msg, show=False)
  3111. else:
  3112. self.ui.fcinfo.set_status(str(msg), level="info")
  3113. # make sure that if the message is to clear the infobar with a space
  3114. # is not printed over and over on the shell
  3115. if msg != '':
  3116. self.shell_message(msg)
  3117. def restore_toolbar_view(self):
  3118. """
  3119. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3120. was saved in the defaults dictionary.
  3121. :return: None
  3122. """
  3123. tb = self.defaults["global_toolbar_view"]
  3124. if tb & 1:
  3125. self.ui.toolbarfile.setVisible(True)
  3126. else:
  3127. self.ui.toolbarfile.setVisible(False)
  3128. if tb & 2:
  3129. self.ui.toolbargeo.setVisible(True)
  3130. else:
  3131. self.ui.toolbargeo.setVisible(False)
  3132. if tb & 4:
  3133. self.ui.toolbarview.setVisible(True)
  3134. else:
  3135. self.ui.toolbarview.setVisible(False)
  3136. if tb & 8:
  3137. self.ui.toolbartools.setVisible(True)
  3138. else:
  3139. self.ui.toolbartools.setVisible(False)
  3140. if tb & 16:
  3141. self.ui.exc_edit_toolbar.setVisible(True)
  3142. else:
  3143. self.ui.exc_edit_toolbar.setVisible(False)
  3144. if tb & 32:
  3145. self.ui.geo_edit_toolbar.setVisible(True)
  3146. else:
  3147. self.ui.geo_edit_toolbar.setVisible(False)
  3148. if tb & 64:
  3149. self.ui.grb_edit_toolbar.setVisible(True)
  3150. else:
  3151. self.ui.grb_edit_toolbar.setVisible(False)
  3152. if tb & 128:
  3153. self.ui.snap_toolbar.setVisible(True)
  3154. else:
  3155. self.ui.snap_toolbar.setVisible(False)
  3156. if tb & 256:
  3157. self.ui.toolbarshell.setVisible(True)
  3158. else:
  3159. self.ui.toolbarshell.setVisible(False)
  3160. def load_defaults(self, filename):
  3161. """
  3162. Loads the aplication's default settings from current_defaults.FlatConfig into
  3163. ``self.defaults``.
  3164. :return: None
  3165. """
  3166. try:
  3167. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3168. options = f.read()
  3169. f.close()
  3170. except IOError:
  3171. self.log.error("Could not load defaults file.")
  3172. self.inform.emit('[ERROR] %s' % _("Could not load defaults file."))
  3173. # in case the defaults file can't be loaded, show all toolbars
  3174. self.defaults["global_toolbar_view"] = 511
  3175. return
  3176. try:
  3177. defaults = json.loads(options)
  3178. except Exception:
  3179. # in case the defaults file can't be loaded, show all toolbars
  3180. self.defaults["global_toolbar_view"] = 511
  3181. e = sys.exc_info()[0]
  3182. App.log.error(str(e))
  3183. self.inform.emit('[ERROR] %s' % _("Failed to parse defaults file."))
  3184. return
  3185. if 'version' not in defaults or defaults['version'] != self.defaults['version']:
  3186. for k, v in defaults.items():
  3187. if k in self.defaults:
  3188. self.defaults[k] = v
  3189. # delete old factory defaults
  3190. try:
  3191. fact_def_file_path = os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  3192. os.chmod(fact_def_file_path, stat.S_IRWXO | stat.S_IWRITE | stat.S_IWGRP)
  3193. os.remove(fact_def_file_path)
  3194. # recreate a new factory defaults file and save the factory defaults data into it
  3195. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  3196. json.dump(self.defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3197. f_f_def_s.close()
  3198. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  3199. os.chmod(fact_def_file_path, S_IREAD | S_IRGRP | S_IROTH)
  3200. except Exception as e:
  3201. log.debug("App.load_defaults() -> deleting old factory defaults file -> %s" % str(e))
  3202. self.old_defaults_found = True
  3203. else:
  3204. self.defaults.update(defaults)
  3205. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3206. def on_import_preferences(self):
  3207. """
  3208. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3209. ``self.defaults``.
  3210. :return: None
  3211. """
  3212. self.report_usage("on_import_preferences")
  3213. App.log.debug("on_import_preferences()")
  3214. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3215. try:
  3216. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3217. directory=self.data_path,
  3218. filter=filter_)
  3219. except TypeError:
  3220. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3221. filter=filter_)
  3222. filename = str(filename)
  3223. if filename == "":
  3224. self.inform.emit('[WARNING_NOTCL] %s' %
  3225. _("FlatCAM preferences import cancelled."))
  3226. else:
  3227. try:
  3228. f = open(filename)
  3229. options = f.read()
  3230. f.close()
  3231. except IOError:
  3232. self.log.error("Could not load defaults file.")
  3233. self.inform.emit('[ERROR_NOTCL] %s' %
  3234. _("Could not load defaults file."))
  3235. return
  3236. try:
  3237. defaults_from_file = json.loads(options)
  3238. except Exception:
  3239. e = sys.exc_info()[0]
  3240. App.log.error(str(e))
  3241. self.inform.emit('[ERROR_NOTCL] %s' %
  3242. _("Failed to parse defaults file."))
  3243. return
  3244. self.defaults.update(defaults_from_file)
  3245. self.on_preferences_edited()
  3246. self.inform.emit('[success] %s: %s' %
  3247. (_("Imported Defaults from"), filename))
  3248. def on_export_preferences(self):
  3249. """
  3250. Save the defaults dictionary to a file.
  3251. :return: None
  3252. """
  3253. self.report_usage("on_export_preferences")
  3254. App.log.debug("on_export_preferences()")
  3255. defaults_file_content = None
  3256. self.date = str(datetime.today()).rpartition('.')[0]
  3257. self.date = ''.join(c for c in self.date if c not in ':-')
  3258. self.date = self.date.replace(' ', '_')
  3259. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3260. try:
  3261. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3262. caption=_("Export FlatCAM Preferences"),
  3263. directory=self.data_path + '/preferences_' + self.date,
  3264. filter=filter__
  3265. )
  3266. except TypeError:
  3267. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3268. filter=filter__)
  3269. filename = str(filename)
  3270. defaults_from_file = {}
  3271. if filename == "":
  3272. self.inform.emit('[WARNING_NOTCL] %s' %
  3273. _("FlatCAM preferences export cancelled."))
  3274. return
  3275. else:
  3276. try:
  3277. f = open(filename, 'w')
  3278. defaults_file_content = f.read()
  3279. f.close()
  3280. except PermissionError:
  3281. self.inform.emit('[WARNING] %s' %
  3282. _("Permission denied, saving not possible.\n"
  3283. "Most likely another app is holding the file open and not accessible."))
  3284. return
  3285. except IOError:
  3286. App.log.debug('Creating a new preferences file ...')
  3287. f = open(filename, 'w')
  3288. json.dump({}, f)
  3289. f.close()
  3290. except Exception:
  3291. e = sys.exc_info()[0]
  3292. App.log.error("Could not load defaults file.")
  3293. App.log.error(str(e))
  3294. self.inform.emit('[ERROR_NOTCL] %s' %
  3295. _("Could not load preferences file."))
  3296. return
  3297. try:
  3298. defaults_from_file = json.loads(defaults_file_content)
  3299. except Exception:
  3300. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3301. # Update options
  3302. self.defaults_read_form()
  3303. defaults_from_file.update(self.defaults)
  3304. self.propagate_defaults(silent=True)
  3305. # Save update options
  3306. try:
  3307. f = open(filename, "w")
  3308. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3309. f.close()
  3310. except Exception:
  3311. self.inform.emit('[ERROR_NOTCL] %s' %
  3312. _("Failed to write defaults to file."))
  3313. return
  3314. if self.defaults["global_open_style"] is False:
  3315. self.file_opened.emit("preferences", filename)
  3316. self.file_saved.emit("preferences", filename)
  3317. self.inform.emit('[success] %s: %s' %
  3318. (_("Exported preferences to"), filename))
  3319. def on_preferences_open_folder(self):
  3320. """
  3321. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3322. :return: None
  3323. """
  3324. self.report_usage("on_preferences_open_folder()")
  3325. if sys.platform == 'win32':
  3326. subprocess.Popen('explorer %s' % self.data_path)
  3327. elif sys.platform == 'darwin':
  3328. os.system('open "%s"' % self.data_path)
  3329. else:
  3330. subprocess.Popen(['xdg-open', self.data_path])
  3331. self.inform.emit('[success] %s' %
  3332. _("FlatCAM Preferences Folder opened."))
  3333. def save_geometry(self, x, y, width, height, notebook_width):
  3334. """
  3335. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3336. launch of the application.
  3337. :param x: X position of the main window
  3338. :param y: Y position of the main window
  3339. :param width: width of the main window
  3340. :param height: height of the main window
  3341. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3342. :return: None
  3343. """
  3344. self.defaults["global_def_win_x"] = x
  3345. self.defaults["global_def_win_y"] = y
  3346. self.defaults["global_def_win_w"] = width
  3347. self.defaults["global_def_win_h"] = height
  3348. self.defaults["global_def_notebook_width"] = notebook_width
  3349. self.save_defaults()
  3350. def restore_main_win_geom(self):
  3351. try:
  3352. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3353. self.defaults["global_def_win_y"],
  3354. self.defaults["global_def_win_w"],
  3355. self.defaults["global_def_win_h"])
  3356. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3357. except KeyError as e:
  3358. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3359. def message_dialog(self, title, message, kind="info"):
  3360. """
  3361. Builds and show a custom QMessageBox to be used in FlatCAM.
  3362. :param title: title of the QMessageBox
  3363. :param message: message to be displayed
  3364. :param kind: type of QMessageBox; will display a specific icon.
  3365. :return:
  3366. """
  3367. icon = {"info": QtWidgets.QMessageBox.Information,
  3368. "warning": QtWidgets.QMessageBox.Warning,
  3369. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3370. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3371. dlg.setText(message)
  3372. dlg.exec_()
  3373. def register_recent(self, kind, filename):
  3374. """
  3375. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3376. dictionary.
  3377. :param kind: type of file that was opened
  3378. :param filename: the path and file name for the file that was opened
  3379. :return:
  3380. """
  3381. self.log.debug("register_recent()")
  3382. self.log.debug(" %s" % kind)
  3383. self.log.debug(" %s" % filename)
  3384. record = {'kind': str(kind), 'filename': str(filename)}
  3385. if record in self.recent:
  3386. return
  3387. if record in self.recent_projects:
  3388. return
  3389. if record['kind'] == 'project':
  3390. self.recent_projects.insert(0, record)
  3391. else:
  3392. self.recent.insert(0, record)
  3393. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3394. self.recent.pop()
  3395. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3396. self.recent_projects.pop()
  3397. try:
  3398. f = open(self.data_path + '/recent.json', 'w')
  3399. except IOError:
  3400. App.log.error("Failed to open recent items file for writing.")
  3401. self.inform.emit('[ERROR_NOTCL] %s' %
  3402. _('Failed to open recent files file for writing.'))
  3403. return
  3404. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3405. f.close()
  3406. try:
  3407. fp = open(self.data_path + '/recent_projects.json', 'w')
  3408. except IOError:
  3409. App.log.error("Failed to open recent items file for writing.")
  3410. self.inform.emit('[ERROR_NOTCL] %s' %
  3411. _('Failed to open recent projects file for writing.'))
  3412. return
  3413. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3414. fp.close()
  3415. # Re-build the recent items menu
  3416. self.setup_recent_items()
  3417. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3418. """
  3419. Creates a new specialized FlatCAMObj and attaches it to the application,
  3420. this is, updates the GUI accordingly, any other records and plots it.
  3421. This method is thread-safe.
  3422. Notes:
  3423. * If the name is in use, the self.collection will modify it
  3424. when appending it to the collection. There is no need to handle
  3425. name conflicts here.
  3426. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3427. :type kind: str
  3428. :param name: Name for the object.
  3429. :type name: str
  3430. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3431. The function is called with 2 parameters: the new object and the App instance.
  3432. :type initialize: function
  3433. :param active:
  3434. :param fit:
  3435. :param plot: If to plot the resulting object
  3436. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3437. self.colleaction
  3438. :return: None
  3439. :rtype: None
  3440. """
  3441. App.log.debug("new_object()")
  3442. obj_plot = plot
  3443. obj_autoselected = autoselected
  3444. t0 = time.time() # Debug
  3445. # ## Create object
  3446. classdict = {
  3447. "gerber": FlatCAMGerber,
  3448. "excellon": FlatCAMExcellon,
  3449. "cncjob": FlatCAMCNCjob,
  3450. "geometry": FlatCAMGeometry,
  3451. "script": FlatCAMScript,
  3452. "document": FlatCAMDocument
  3453. }
  3454. App.log.debug("Calling object constructor...")
  3455. # Object creation/instantiation
  3456. obj = classdict[kind](name)
  3457. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3458. # IMPORTANT
  3459. # The key names in defaults and options dictionary's are not random:
  3460. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3461. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  3462. # copied to self.options. After that, below, depending on the type of
  3463. # object that is created, it will strip the name of the object and the underline (if the original key was
  3464. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3465. # "toolchange"
  3466. for option in self.options:
  3467. if option.find(kind + "_") == 0:
  3468. oname = option[len(kind) + 1:]
  3469. obj.options[oname] = self.options[option]
  3470. obj.isHovering = False
  3471. obj.notHovering = True
  3472. # Initialize as per user request
  3473. # User must take care to implement initialize
  3474. # in a thread-safe way as is is likely that we
  3475. # have been invoked in a separate thread.
  3476. t1 = time.time()
  3477. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3478. try:
  3479. return_value = initialize(obj, self)
  3480. except Exception as e:
  3481. msg = '[ERROR_NOTCL] %s' % \
  3482. _("An internal error has ocurred. See shell.\n")
  3483. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3484. msg += traceback.format_exc()
  3485. self.inform.emit(msg)
  3486. # if str(e) == "Empty Geometry":
  3487. # self.inform.emit("[ERROR_NOTCL] )
  3488. # else:
  3489. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3490. return "fail"
  3491. t2 = time.time()
  3492. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3493. if return_value == 'fail':
  3494. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3495. return "fail"
  3496. # Check units and convert if necessary
  3497. # This condition CAN be true because initialize() can change obj.units
  3498. if self.options["units"].upper() != obj.units.upper():
  3499. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  3500. obj.convert_units(self.options["units"])
  3501. t3 = time.time()
  3502. self.log.debug("%f seconds converting units." % (t3 - t2))
  3503. # Create the bounding box for the object and then add the results to the obj.options
  3504. # But not for Scripts or for Documents
  3505. if kind != 'document' and kind != 'script':
  3506. try:
  3507. xmin, ymin, xmax, ymax = obj.bounds()
  3508. obj.options['xmin'] = xmin
  3509. obj.options['ymin'] = ymin
  3510. obj.options['xmax'] = xmax
  3511. obj.options['ymax'] = ymax
  3512. except Exception as e:
  3513. log.warning("The object has no bounds properties. %s" % str(e))
  3514. return "fail"
  3515. # update the KeyWords list with the name of the file
  3516. self.myKeywords.append(obj.options['name'])
  3517. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3518. # Move the object to the main thread and let the app know that it is available.
  3519. obj.moveToThread(self.main_thread)
  3520. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3521. return obj
  3522. def new_excellon_object(self):
  3523. """
  3524. Creates a new, blank Excellon object.
  3525. :return: None
  3526. """
  3527. self.report_usage("new_excellon_object()")
  3528. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3529. def new_geometry_object(self):
  3530. """
  3531. Creates a new, blank and single-tool Geometry object.
  3532. :return: None
  3533. """
  3534. self.report_usage("new_geometry_object()")
  3535. def initialize(obj, app):
  3536. obj.multitool = False
  3537. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3538. def new_gerber_object(self):
  3539. """
  3540. Creates a new, blank Gerber object.
  3541. :return: None
  3542. """
  3543. self.report_usage("new_gerber_object()")
  3544. def initialize(grb_obj, app):
  3545. grb_obj.multitool = False
  3546. grb_obj.source_file = []
  3547. grb_obj.multigeo = False
  3548. grb_obj.follow = False
  3549. grb_obj.apertures = {}
  3550. grb_obj.solid_geometry = []
  3551. try:
  3552. grb_obj.options['xmin'] = 0
  3553. grb_obj.options['ymin'] = 0
  3554. grb_obj.options['xmax'] = 0
  3555. grb_obj.options['ymax'] = 0
  3556. except KeyError:
  3557. pass
  3558. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3559. def new_script_object(self, name=None, text=None):
  3560. """
  3561. Creates a new, blank TCL Script object.
  3562. :param name: a name for the new object
  3563. :param text: pass a source file to the newly created script to be loaded in it
  3564. :return: None
  3565. """
  3566. self.report_usage("new_script_object()")
  3567. if text is not None:
  3568. new_source_file = text
  3569. else:
  3570. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3571. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n"\
  3572. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  3573. "ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n"\
  3574. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3575. "ListSys, MillDrills,\n"\
  3576. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3577. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"\
  3578. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3579. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3580. "# SubtractRectangle, Version, WriteGCode\n"
  3581. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3582. '# %s:\n' % _('TCL Tutorial is here') + \
  3583. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3584. '# %s:\n' % _("FlatCAM commands list")
  3585. new_source_file += commands_list + '\n'
  3586. def initialize(obj, app):
  3587. obj.source_file = deepcopy(new_source_file)
  3588. if name is None:
  3589. outname = 'new_script'
  3590. else:
  3591. outname = name
  3592. self.new_object('script', outname, initialize, plot=False)
  3593. def new_document_object(self):
  3594. """
  3595. Creates a new, blank Document object.
  3596. :return: None
  3597. """
  3598. self.report_usage("new_document_object()")
  3599. def initialize(obj, app):
  3600. obj.source_file = ""
  3601. self.new_object('document', 'new_document', initialize, plot=False)
  3602. def on_object_created(self, obj, plot, auto_select):
  3603. """
  3604. Event callback for object creation.
  3605. It will add the new object to the collection. After that it will plot the object in a threaded way
  3606. :param obj: The newly created FlatCAM object.
  3607. :param plot: if the newly create object t obe plotted
  3608. :param auto_select: if the newly created object to be autoselected after creation
  3609. :return: None
  3610. """
  3611. t0 = time.time() # DEBUG
  3612. self.log.debug("on_object_created()")
  3613. # The Collection might change the name if there is a collision
  3614. self.collection.append(obj)
  3615. # after adding the object to the collection always update the list of objects that are in the collection
  3616. self.all_objects_list = self.collection.get_list()
  3617. # self.inform.emit('[selected] %s created & selected: %s' %
  3618. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3619. if obj.kind == 'gerber':
  3620. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3621. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3622. elif obj.kind == 'excellon':
  3623. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3624. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3625. elif obj.kind == 'cncjob':
  3626. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3627. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3628. elif obj.kind == 'geometry':
  3629. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3630. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3631. elif obj.kind == 'script':
  3632. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3633. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3634. elif obj.kind == 'document':
  3635. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3636. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3637. # update the SHELL auto-completer model with the name of the new object
  3638. self.shell._edit.set_model_data(self.myKeywords)
  3639. if auto_select:
  3640. # select the just opened object but deselect the previous ones
  3641. self.collection.set_all_inactive()
  3642. self.collection.set_active(obj.options["name"])
  3643. else:
  3644. self.collection.set_all_inactive()
  3645. # here it is done the object plotting
  3646. def worker_task(t_obj):
  3647. with self.proc_container.new(_("Plotting")):
  3648. if isinstance(t_obj, FlatCAMCNCjob):
  3649. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3650. else:
  3651. t_obj.plot()
  3652. t1 = time.time() # DEBUG
  3653. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3654. self.object_plotted.emit(t_obj)
  3655. # Send to worker
  3656. # self.worker.add_task(worker_task, [self])
  3657. if plot is True:
  3658. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3659. def on_object_changed(self, obj):
  3660. """
  3661. Called whenever the geometry of the object was changed in some way.
  3662. This require the update of it's bounding values so it can be the selected on canvas.
  3663. Update the bounding box data from obj.options
  3664. :param obj: the object that was changed
  3665. :return: None
  3666. """
  3667. xmin, ymin, xmax, ymax = obj.bounds()
  3668. obj.options['xmin'] = xmin
  3669. obj.options['ymin'] = ymin
  3670. obj.options['xmax'] = xmax
  3671. obj.options['ymax'] = ymax
  3672. log.debug("Object changed, updating the bounding box data on self.options")
  3673. # delete the old selection shape
  3674. self.delete_selection_shape()
  3675. self.should_we_save = True
  3676. def on_object_plotted(self):
  3677. """
  3678. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3679. :return: None
  3680. """
  3681. self.on_zoom_fit(None)
  3682. def on_about(self):
  3683. """
  3684. Displays the "about" dialog found in the Menu --> Help.
  3685. :return: None
  3686. """
  3687. self.report_usage("on_about")
  3688. version = self.version
  3689. version_date = self.version_date
  3690. beta = self.beta
  3691. class AboutDialog(QtWidgets.QDialog):
  3692. def __init__(self, parent=None):
  3693. QtWidgets.QDialog.__init__(self, parent)
  3694. # Icon and title
  3695. self.setWindowIcon(parent.app_icon)
  3696. self.setWindowTitle(_("About FlatCAM"))
  3697. self.resize(600, 200)
  3698. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3699. # self.setStyleSheet(
  3700. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3701. # "background-attachment: fixed"
  3702. # )
  3703. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3704. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3705. # palette = QtGui.QPalette()
  3706. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3707. # self.setPalette(palette)
  3708. logo = QtWidgets.QLabel()
  3709. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3710. title = QtWidgets.QLabel(
  3711. "<font size=8><B>FlatCAM</B></font><BR>"
  3712. "{title}<BR>"
  3713. "<BR>"
  3714. "<BR>"
  3715. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3716. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3717. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3718. "<B>{issue}</B></a><BR>".format(
  3719. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3720. devel=_("Development"),
  3721. down=_("DOWNLOAD"),
  3722. issue=_("Issue tracker"))
  3723. )
  3724. title.setOpenExternalLinks(True)
  3725. closebtn = QtWidgets.QPushButton(_("Close"))
  3726. tab_widget = QtWidgets.QTabWidget()
  3727. description_label = QtWidgets.QLabel(
  3728. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3729. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3730. version=version,
  3731. beta=('BETA' if beta else ''),
  3732. date=version_date,
  3733. arch=platform.architecture()[0])
  3734. )
  3735. description_label.setOpenExternalLinks(True)
  3736. lic_lbl_header = QtWidgets.QLabel(
  3737. '%s:<br>%s<br>' % (
  3738. _('Licensed under the MIT license'),
  3739. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3740. "http://www.opensource.org/licenses/mit-license.php</a>"
  3741. )
  3742. )
  3743. lic_lbl_header.setOpenExternalLinks(True)
  3744. lic_lbl_body = QtWidgets.QLabel(
  3745. _(
  3746. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3747. 'of this software and associated documentation files (the "Software"), to deal\n'
  3748. 'in the Software without restriction, including without limitation the rights\n'
  3749. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3750. 'copies of the Software, and to permit persons to whom the Software is\n'
  3751. 'furnished to do so, subject to the following conditions:\n\n'
  3752. 'The above copyright notice and this permission notice shall be included in\n'
  3753. 'all copies or substantial portions of the Software.\n\n'
  3754. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3755. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3756. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3757. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3758. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3759. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3760. 'THE SOFTWARE.'
  3761. )
  3762. )
  3763. attributions_label = QtWidgets.QLabel(
  3764. _(
  3765. 'Some of the icons used are from the following sources:<br>'
  3766. '<div>Icons made by <a href="https://www.flaticon.com/authors/freepik" '
  3767. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3768. 'title="Flaticon">www.flaticon.com</a></div>'
  3769. 'Icons by <a target="_blank" href="https://icons8.com">Icons8</a>'
  3770. )
  3771. )
  3772. # layouts
  3773. layout1 = QtWidgets.QVBoxLayout()
  3774. layout1_1 = QtWidgets.QHBoxLayout()
  3775. layout1_2 = QtWidgets.QHBoxLayout()
  3776. layout2 = QtWidgets.QHBoxLayout()
  3777. layout3 = QtWidgets.QHBoxLayout()
  3778. self.setLayout(layout1)
  3779. layout1.addLayout(layout1_1)
  3780. layout1.addLayout(layout1_2)
  3781. layout1.addLayout(layout2)
  3782. layout1.addLayout(layout3)
  3783. layout1_1.addStretch()
  3784. layout1_1.addWidget(description_label)
  3785. layout1_2.addWidget(tab_widget)
  3786. self.splash_tab = QtWidgets.QWidget()
  3787. self.splash_tab.setObjectName("splash_about")
  3788. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3789. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3790. tab_widget.addTab(self.splash_tab, _("Splash"))
  3791. self.programmmers_tab = QtWidgets.QWidget()
  3792. self.programmmers_tab.setObjectName("programmers_about")
  3793. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3794. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3795. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3796. self.translators_tab = QtWidgets.QWidget()
  3797. self.translators_tab.setObjectName("translators_about")
  3798. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3799. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3800. tab_widget.addTab(self.translators_tab, _("Translators"))
  3801. self.license_tab = QtWidgets.QWidget()
  3802. self.license_tab.setObjectName("license_about")
  3803. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3804. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3805. tab_widget.addTab(self.license_tab, _("License"))
  3806. self.attributions_tab = QtWidgets.QWidget()
  3807. self.attributions_tab.setObjectName("attributions_about")
  3808. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3809. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3810. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3811. self.splash_tab_layout.addWidget(logo, stretch=0)
  3812. self.splash_tab_layout.addWidget(title, stretch=1)
  3813. pal = QtGui.QPalette()
  3814. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3815. self.prog_grid_lay = QtWidgets.QGridLayout()
  3816. self.prog_grid_lay.setHorizontalSpacing(20)
  3817. self.prog_grid_lay.setColumnStretch(0, 0)
  3818. self.prog_grid_lay.setColumnStretch(2, 1)
  3819. prog_widget = QtWidgets.QWidget()
  3820. prog_widget.setLayout(self.prog_grid_lay)
  3821. prog_scroll = QtWidgets.QScrollArea()
  3822. prog_scroll.setWidget(prog_widget)
  3823. prog_scroll.setWidgetResizable(True)
  3824. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3825. prog_scroll.setPalette(pal)
  3826. self.programmmers_tab_layout.addWidget(prog_scroll)
  3827. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3828. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3829. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3830. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3831. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3832. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3833. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3834. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3835. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3836. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3837. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3838. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3839. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3840. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3841. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3842. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3843. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3844. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3845. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3846. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3847. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3848. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3849. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3850. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3851. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  3852. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  3853. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  3854. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  3855. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  3856. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  3857. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  3858. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  3859. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  3860. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  3861. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  3862. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 28, 0)
  3863. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 29, 0)
  3864. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 30, 0)
  3865. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 31, 0)
  3866. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 32, 0)
  3867. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 33, 0)
  3868. self.translator_grid_lay = QtWidgets.QGridLayout()
  3869. self.translator_grid_lay.setColumnStretch(0, 0)
  3870. self.translator_grid_lay.setColumnStretch(1, 0)
  3871. self.translator_grid_lay.setColumnStretch(2, 1)
  3872. self.translator_grid_lay.setColumnStretch(3, 0)
  3873. # trans_widget = QtWidgets.QWidget()
  3874. # trans_widget.setLayout(self.translator_grid_lay)
  3875. # self.translators_tab_layout.addWidget(trans_widget)
  3876. # self.translators_tab_layout.addStretch()
  3877. trans_widget = QtWidgets.QWidget()
  3878. trans_widget.setLayout(self.translator_grid_lay)
  3879. trans_scroll = QtWidgets.QScrollArea()
  3880. trans_scroll.setWidget(trans_widget)
  3881. trans_scroll.setWidgetResizable(True)
  3882. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3883. trans_scroll.setPalette(pal)
  3884. self.translators_tab_layout.addWidget(trans_scroll)
  3885. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3886. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3887. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  3888. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  3889. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  3890. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3891. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  3892. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3893. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 2, 1)
  3894. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 2, 2)
  3895. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  3896. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3897. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3898. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt"), 3, 2)
  3899. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  3900. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3901. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3902. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  3903. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3904. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3905. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  3906. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3907. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  3908. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 6, 2)
  3909. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  3910. self.translator_grid_lay.setColumnStretch(0, 0)
  3911. self.translators_tab_layout.addStretch()
  3912. self.license_tab_layout.addWidget(lic_lbl_header)
  3913. self.license_tab_layout.addWidget(lic_lbl_body)
  3914. self.license_tab_layout.addStretch()
  3915. self.attributions_tab_layout.addWidget(attributions_label)
  3916. self.attributions_tab_layout.addStretch()
  3917. layout3.addStretch()
  3918. layout3.addWidget(closebtn)
  3919. closebtn.clicked.connect(self.accept)
  3920. AboutDialog(self.ui).exec_()
  3921. def install_bookmarks(self, book_dict=None):
  3922. """
  3923. Install the bookmarks actions in the Help menu -> Bookmarks
  3924. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  3925. :return: None
  3926. """
  3927. if book_dict is None:
  3928. self.defaults["global_bookmarks"].update(
  3929. {
  3930. '1': ['FlatCAM', "http://flatcam.org"],
  3931. '2': ['Backup Site', ""]
  3932. }
  3933. )
  3934. else:
  3935. self.defaults["global_bookmarks"].clear()
  3936. self.defaults["global_bookmarks"].update(book_dict)
  3937. # first try to disconnect if somehow they get connected from elsewhere
  3938. for act in self.ui.menuhelp_bookmarks.actions():
  3939. try:
  3940. act.triggered.disconnect()
  3941. except TypeError:
  3942. pass
  3943. # clear all actions except the last one who is the Bookmark manager
  3944. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  3945. pass
  3946. else:
  3947. self.ui.menuhelp_bookmarks.removeAction(act)
  3948. bm_limit = int(self.defaults["global_bookmarks_limit"])
  3949. if self.defaults["global_bookmarks"]:
  3950. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  3951. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  3952. # the JSON is first making the keys as strings (therefore I have to use strings too
  3953. # or do the conversion :(
  3954. # )
  3955. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  3956. # the '10' entry jsut after '1' therefore ordering as strings
  3957. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  3958. key=lambda x: int(x[0]))
  3959. for entry, bookmark in sorted_bookmarks:
  3960. title = bookmark[0]
  3961. weblink = bookmark[1]
  3962. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  3963. act.setText(title)
  3964. act.setIcon(QtGui.QIcon('share/link16.png'))
  3965. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  3966. if title == 'Backup Site' and weblink == "":
  3967. act.triggered.connect(self.on_backup_site)
  3968. else:
  3969. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  3970. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  3971. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  3972. def on_bookmarks_manager(self):
  3973. """
  3974. Adds the bookmark manager in a Tab in Plot Area
  3975. :return:
  3976. """
  3977. for idx in range(self.ui.plot_tab_area.count()):
  3978. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  3979. # there can be only one instance of Bookmark Manager at one time
  3980. return
  3981. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  3982. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  3983. # add the tab if it was closed
  3984. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  3985. # delete the absolute and relative position and messages in the infobar
  3986. self.ui.position_label.setText("")
  3987. self.ui.rel_position_label.setText("")
  3988. # Switch plot_area to preferences page
  3989. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  3990. @staticmethod
  3991. def on_backup_site():
  3992. msgbox = QtWidgets.QMessageBox()
  3993. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  3994. "1. FlatCAM.org website is down\n"
  3995. "2. Someone forked FlatCAM project and wants to point\n"
  3996. "to his own website\n\n"
  3997. "If you can't get any informations about FlatCAM beta\n"
  3998. "use the YouTube channel link from the Help menu."))
  3999. msgbox.setWindowTitle(_("Alternative website"))
  4000. msgbox.setWindowIcon(QtGui.QIcon('share/globe16.png'))
  4001. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  4002. msgbox.setDefaultButton(bt_yes)
  4003. msgbox.exec_()
  4004. # response = msgbox.clickedButton()
  4005. def on_file_savedefaults(self):
  4006. """
  4007. Callback for menu item File->Save Defaults. Saves application default options
  4008. ``self.defaults`` to current_defaults.FlatConfig.
  4009. :return: None
  4010. """
  4011. self.save_defaults()
  4012. # def on_app_exit(self):
  4013. # self.report_usage("on_app_exit()")
  4014. #
  4015. # if self.collection.get_list():
  4016. # msgbox = QtWidgets.QMessageBox()
  4017. # # msgbox.setText("<B>Save changes ...</B>")
  4018. # msgbox.setText("There are files/objects opened in FlatCAM. "
  4019. # "\n"
  4020. # "Do you want to Save the project?")
  4021. # msgbox.setWindowTitle("Save changes")
  4022. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4023. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  4024. # QtWidgets.QMessageBox.Cancel)
  4025. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  4026. #
  4027. # response = msgbox.exec_()
  4028. #
  4029. # if response == QtWidgets.QMessageBox.Yes:
  4030. # self.on_file_saveprojectas(thread=False)
  4031. # elif response == QtWidgets.QMessageBox.Cancel:
  4032. # return
  4033. # self.save_defaults()
  4034. # else:
  4035. # self.save_defaults()
  4036. # log.debug("Application defaults saved ... Exit event.")
  4037. # QtWidgets.qApp.quit()
  4038. def save_defaults(self, silent=False, data_path=None, first_time=False):
  4039. """
  4040. Saves application default options
  4041. ``self.defaults`` to current_defaults.FlatConfig file.
  4042. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  4043. used at the next launch of the application.
  4044. :param silent: whether to display a message in status bar or not; boolean
  4045. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  4046. When the application is portable it should be a mobile location.
  4047. :return: None
  4048. """
  4049. self.report_usage("save_defaults")
  4050. if data_path is None:
  4051. data_path = self.data_path
  4052. # Read options from file
  4053. try:
  4054. f = open(data_path + "/current_defaults.FlatConfig")
  4055. defaults_file_content = f.read()
  4056. f.close()
  4057. except Exception:
  4058. e = sys.exc_info()[0]
  4059. App.log.error("Could not load defaults file.")
  4060. App.log.error(str(e))
  4061. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  4062. return
  4063. try:
  4064. defaults = json.loads(defaults_file_content)
  4065. except Exception:
  4066. e = sys.exc_info()[0]
  4067. App.log.error("Failed to parse defaults file.")
  4068. App.log.error(str(e))
  4069. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  4070. return
  4071. # Update options
  4072. self.defaults_read_form()
  4073. defaults.update(self.defaults)
  4074. self.propagate_defaults(silent=True)
  4075. # Save the toolbar view
  4076. tb_status = 0
  4077. if self.ui.toolbarfile.isVisible():
  4078. tb_status += 1
  4079. if self.ui.toolbargeo.isVisible():
  4080. tb_status += 2
  4081. if self.ui.toolbarview.isVisible():
  4082. tb_status += 4
  4083. if self.ui.toolbartools.isVisible():
  4084. tb_status += 8
  4085. if self.ui.exc_edit_toolbar.isVisible():
  4086. tb_status += 16
  4087. if self.ui.geo_edit_toolbar.isVisible():
  4088. tb_status += 32
  4089. if self.ui.grb_edit_toolbar.isVisible():
  4090. tb_status += 64
  4091. if self.ui.snap_toolbar.isVisible():
  4092. tb_status += 128
  4093. if self.ui.toolbarshell.isVisible():
  4094. tb_status += 256
  4095. if first_time is False:
  4096. self.defaults["global_toolbar_view"] = tb_status
  4097. # Save update options
  4098. try:
  4099. f = open(data_path + "/current_defaults.FlatConfig", "w")
  4100. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4101. f.close()
  4102. except Exception as e:
  4103. log.debug("App.save_defaults() --> %s" % str(e))
  4104. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write defaults to file."))
  4105. return
  4106. if not silent:
  4107. self.inform.emit('[success] %s' % _("Preferences saved."))
  4108. def save_factory_defaults(self, silent_message=False, data_path=None):
  4109. """
  4110. Saves application factory default options
  4111. ``self.defaults`` to factory_defaults.FlatConfig.
  4112. It's a one time job done just after the first install.
  4113. :param silent_message: whether to display a message in status bar or not; boolean
  4114. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4115. When the application is portable it should be a mobile location.
  4116. :return: None
  4117. """
  4118. self.report_usage("save_factory_defaults")
  4119. if data_path is None:
  4120. data_path = self.data_path
  4121. # Read options from file
  4122. try:
  4123. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4124. factory_defaults_file_content = f_f_def.read()
  4125. f_f_def.close()
  4126. except Exception:
  4127. e = sys.exc_info()[0]
  4128. App.log.error("Could not load factory defaults file.")
  4129. App.log.error(str(e))
  4130. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  4131. return
  4132. try:
  4133. factory_defaults = json.loads(factory_defaults_file_content)
  4134. except Exception:
  4135. e = sys.exc_info()[0]
  4136. App.log.error("Failed to parse factory defaults file.")
  4137. App.log.error(str(e))
  4138. if silent_message is False:
  4139. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  4140. return
  4141. # Update options
  4142. self.defaults_read_form()
  4143. factory_defaults.update(self.defaults)
  4144. self.propagate_defaults(silent=True)
  4145. # Save update options
  4146. try:
  4147. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4148. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4149. f_f_def_s.close()
  4150. except Exception as e:
  4151. log.debug("App.save_factory_default() save update --> %s" % str(e))
  4152. if silent_message is False:
  4153. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write factory defaults to file."))
  4154. return
  4155. if silent_message is False:
  4156. self.inform.emit(_("Factory defaults saved."))
  4157. def final_save(self):
  4158. """
  4159. Callback for doing a preferences save to file whenever the application is about to quit.
  4160. If the project has changes, it will ask the user to save the project.
  4161. :return: None
  4162. """
  4163. if self.save_in_progress:
  4164. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  4165. return
  4166. if self.should_we_save and self.collection.get_list():
  4167. msgbox = QtWidgets.QMessageBox()
  4168. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4169. "\n"
  4170. "Do you want to Save the project?"))
  4171. msgbox.setWindowTitle(_("Save changes"))
  4172. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4173. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4174. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4175. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4176. msgbox.setDefaultButton(bt_yes)
  4177. msgbox.exec_()
  4178. response = msgbox.clickedButton()
  4179. if response == bt_yes:
  4180. try:
  4181. self.trayIcon.hide()
  4182. except Exception:
  4183. pass
  4184. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4185. elif response == bt_no:
  4186. try:
  4187. self.trayIcon.hide()
  4188. except Exception:
  4189. pass
  4190. self.quit_application()
  4191. elif response == bt_cancel:
  4192. return
  4193. else:
  4194. try:
  4195. self.trayIcon.hide()
  4196. except Exception:
  4197. pass
  4198. self.quit_application()
  4199. def quit_application(self):
  4200. """
  4201. Called (as a pyslot or not) when the application is quit.
  4202. :return: None
  4203. """
  4204. self.save_defaults()
  4205. log.debug("App.final_save() --> App Defaults saved.")
  4206. if self.cmd_line_headless != 1:
  4207. # save app state to file
  4208. stgs = QSettings("Open Source", "FlatCAM")
  4209. stgs.setValue('saved_gui_state', self.ui.saveState())
  4210. stgs.setValue('maximized_gui', self.ui.isMaximized())
  4211. stgs.setValue(
  4212. 'language',
  4213. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  4214. )
  4215. stgs.setValue(
  4216. 'notebook_font_size',
  4217. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4218. )
  4219. stgs.setValue(
  4220. 'axis_font_size',
  4221. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4222. )
  4223. stgs.setValue(
  4224. 'textbox_font_size',
  4225. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4226. )
  4227. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4228. stgs.setValue(
  4229. 'machinist',
  4230. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  4231. )
  4232. # This will write the setting to the platform specific storage.
  4233. del stgs
  4234. log.debug("App.final_save() --> App UI state saved.")
  4235. QtWidgets.qApp.quit()
  4236. def on_portable_checked(self, state):
  4237. """
  4238. Callback called when the checkbox in Preferences GUI is checked.
  4239. It will set the application as portable by creating the preferences and recent files in the
  4240. 'config' folder found in the FlatCAM installation folder.
  4241. :param state: boolean, the state of the checkbox when clicked/checked
  4242. :return:
  4243. """
  4244. line_no = 0
  4245. data = None
  4246. if sys.platform != 'win32':
  4247. # this won't work in Linux or MacOS
  4248. return
  4249. # test if the app was frozen and choose the path for the configuration file
  4250. if getattr(sys, "frozen", False) is True:
  4251. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4252. else:
  4253. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4254. config_file = current_data_path + '\\configuration.txt'
  4255. try:
  4256. with open(config_file, 'r') as f:
  4257. try:
  4258. data = f.readlines()
  4259. except Exception as e:
  4260. log.debug('App.__init__() -->%s' % str(e))
  4261. return
  4262. except FileNotFoundError:
  4263. pass
  4264. for line in data:
  4265. line = line.strip('\n')
  4266. param = str(line).rpartition('=')
  4267. if param[0] == 'portable':
  4268. break
  4269. line_no += 1
  4270. if state:
  4271. data[line_no] = 'portable=True\n'
  4272. # create the new defauults files
  4273. # create current_defaults.FlatConfig file if there is none
  4274. try:
  4275. f = open(current_data_path + '/current_defaults.FlatConfig')
  4276. f.close()
  4277. except IOError:
  4278. App.log.debug('Creating empty current_defaults.FlatConfig')
  4279. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4280. json.dump({}, f)
  4281. f.close()
  4282. # create factory_defaults.FlatConfig file if there is none
  4283. try:
  4284. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4285. f.close()
  4286. except IOError:
  4287. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4288. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4289. json.dump({}, f)
  4290. f.close()
  4291. try:
  4292. f = open(current_data_path + '/recent.json')
  4293. f.close()
  4294. except IOError:
  4295. App.log.debug('Creating empty recent.json')
  4296. f = open(current_data_path + '/recent.json', 'w')
  4297. json.dump([], f)
  4298. f.close()
  4299. try:
  4300. fp = open(current_data_path + '/recent_projects.json')
  4301. fp.close()
  4302. except IOError:
  4303. App.log.debug('Creating empty recent_projects.json')
  4304. fp = open(current_data_path + '/recent_projects.json', 'w')
  4305. json.dump([], fp)
  4306. fp.close()
  4307. # save the current defaults to the new defaults file
  4308. self.save_defaults(silent=True, data_path=current_data_path)
  4309. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4310. else:
  4311. data[line_no] = 'portable=False\n'
  4312. with open(config_file, 'w') as f:
  4313. f.writelines(data)
  4314. def on_toggle_shell(self):
  4315. """
  4316. Toggle shell: if is visible close it, if it is closed then open it
  4317. :return: None
  4318. """
  4319. self.report_usage("on_toggle_shell()")
  4320. if self.ui.shell_dock.isVisible():
  4321. self.ui.shell_dock.hide()
  4322. else:
  4323. self.ui.shell_dock.show()
  4324. def on_register_files(self, obj_type=None):
  4325. """
  4326. Called whenever there is a need to register file extensions with FlatCAM.
  4327. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4328. :param obj_type: the type of object to be register for.
  4329. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4330. :return: None
  4331. """
  4332. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4333. new_reg_path = 'Software\\Classes\\'
  4334. # find if the current user is admin
  4335. try:
  4336. is_admin = os.getuid() == 0
  4337. except AttributeError:
  4338. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4339. if is_admin is True:
  4340. root_path = winreg.HKEY_LOCAL_MACHINE
  4341. else:
  4342. root_path = winreg.HKEY_CURRENT_USER
  4343. # create the keys
  4344. def set_reg(name, root_path, new_reg_path, value):
  4345. try:
  4346. winreg.CreateKey(root_path, new_reg_path)
  4347. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4348. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4349. return True
  4350. except WindowsError:
  4351. return False
  4352. # delete key in registry
  4353. def delete_reg(root_path, reg_path, key_to_del):
  4354. key_to_del_path = reg_path + key_to_del
  4355. try:
  4356. winreg.DeleteKey(root_path, key_to_del_path)
  4357. return True
  4358. except WindowsError:
  4359. return False
  4360. if obj_type is None or obj_type == 'excellon':
  4361. exc_list = \
  4362. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4363. exc_list = [x for x in exc_list if x != '']
  4364. # register all keys in the Preferences window
  4365. for ext in exc_list:
  4366. new_k = new_reg_path + '.%s' % ext
  4367. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4368. # and unregister those that are no longer in the Preferences windows but are in the file
  4369. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4370. if ext not in exc_list:
  4371. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4372. # now write the updated extensions to the self.defaults
  4373. # new_ext = ''
  4374. # for ext in exc_list:
  4375. # new_ext = new_ext + ext + ', '
  4376. # self.defaults["fa_excellon"] = new_ext
  4377. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4378. if obj_type is None or obj_type == 'gcode':
  4379. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4380. gco_list = [x for x in gco_list if x != '']
  4381. # register all keys in the Preferences window
  4382. for ext in gco_list:
  4383. new_k = new_reg_path + '.%s' % ext
  4384. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4385. # and unregister those that are no longer in the Preferences windows but are in the file
  4386. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4387. if ext not in gco_list:
  4388. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4389. # now write the updated extensions to the self.defaults
  4390. # new_ext = ''
  4391. # for ext in gco_list:
  4392. # new_ext = new_ext + ext + ', '
  4393. # self.defaults["fa_gcode"] = new_ext
  4394. self.inform.emit('[success] %s' %
  4395. _("Selected GCode file extensions registered with FlatCAM."))
  4396. if obj_type is None or obj_type == 'gerber':
  4397. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4398. grb_list = [x for x in grb_list if x != '']
  4399. # register all keys in the Preferences window
  4400. for ext in grb_list:
  4401. new_k = new_reg_path + '.%s' % ext
  4402. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4403. # and unregister those that are no longer in the Preferences windows but are in the file
  4404. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4405. if ext not in grb_list:
  4406. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4407. # now write the updated extensions to the self.defaults
  4408. # new_ext = ''
  4409. # for ext in grb_list:
  4410. # new_ext = new_ext + ext + ', '
  4411. # self.defaults["fa_gerber"] = new_ext
  4412. self.inform.emit('[success] %s' %
  4413. _("Selected Gerber file extensions registered with FlatCAM."))
  4414. def add_extension(self, ext_type):
  4415. """
  4416. Add a file extension to the list for a specific object
  4417. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4418. :return:
  4419. """
  4420. if ext_type == 'excellon':
  4421. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4422. if new_ext == '':
  4423. return
  4424. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4425. if new_ext in old_val:
  4426. return
  4427. old_val.append(new_ext)
  4428. old_val.sort()
  4429. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4430. if ext_type == 'gcode':
  4431. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4432. if new_ext == '':
  4433. return
  4434. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4435. if new_ext in old_val:
  4436. return
  4437. old_val.append(new_ext)
  4438. old_val.sort()
  4439. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4440. if ext_type == 'gerber':
  4441. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4442. if new_ext == '':
  4443. return
  4444. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4445. if new_ext in old_val:
  4446. return
  4447. old_val.append(new_ext)
  4448. old_val.sort()
  4449. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4450. if ext_type == 'keyword':
  4451. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4452. if new_kw == '':
  4453. return
  4454. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4455. if new_kw in old_val:
  4456. return
  4457. old_val.append(new_kw)
  4458. old_val.sort()
  4459. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4460. # update the self.myKeywords so the model is updated
  4461. self.autocomplete_kw_list = \
  4462. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4463. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4464. self.shell._edit.set_model_data(self.myKeywords)
  4465. def del_extension(self, ext_type):
  4466. """
  4467. Remove a file extension from the list for a specific object
  4468. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4469. :return:
  4470. """
  4471. if ext_type == 'excellon':
  4472. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4473. if new_ext == '':
  4474. return
  4475. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4476. if new_ext not in old_val:
  4477. return
  4478. old_val.remove(new_ext)
  4479. old_val.sort()
  4480. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4481. if ext_type == 'gcode':
  4482. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4483. if new_ext == '':
  4484. return
  4485. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4486. if new_ext not in old_val:
  4487. return
  4488. old_val.remove(new_ext)
  4489. old_val.sort()
  4490. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4491. if ext_type == 'gerber':
  4492. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4493. if new_ext == '':
  4494. return
  4495. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4496. if new_ext not in old_val:
  4497. return
  4498. old_val.remove(new_ext)
  4499. old_val.sort()
  4500. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4501. if ext_type == 'keyword':
  4502. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4503. if new_kw == '':
  4504. return
  4505. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4506. if new_kw not in old_val:
  4507. return
  4508. old_val.remove(new_kw)
  4509. old_val.sort()
  4510. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4511. # update the self.myKeywords so the model is updated
  4512. self.autocomplete_kw_list = \
  4513. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4514. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4515. self.shell._edit.set_model_data(self.myKeywords)
  4516. def restore_extensions(self, ext_type):
  4517. """
  4518. Restore all file extensions associations with FlatCAM, for a specific object
  4519. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4520. :return:
  4521. """
  4522. if ext_type == 'excellon':
  4523. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4524. # for the ability to open Excellon files with .txt extension
  4525. new_exc_list = deepcopy(self.exc_list)
  4526. try:
  4527. new_exc_list.remove('txt')
  4528. except ValueError:
  4529. pass
  4530. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4531. if ext_type == 'gcode':
  4532. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4533. if ext_type == 'gerber':
  4534. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4535. if ext_type == 'keyword':
  4536. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4537. # update the self.myKeywords so the model is updated
  4538. self.autocomplete_kw_list = self.default_keywords
  4539. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4540. self.shell._edit.set_model_data(self.myKeywords)
  4541. def delete_all_extensions(self, ext_type):
  4542. """
  4543. Delete all file extensions associations with FlatCAM, for a specific object
  4544. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4545. :return:
  4546. """
  4547. if ext_type == 'excellon':
  4548. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4549. if ext_type == 'gcode':
  4550. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4551. if ext_type == 'gerber':
  4552. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4553. if ext_type == 'keyword':
  4554. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4555. # update the self.myKeywords so the model is updated
  4556. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4557. self.shell._edit.set_model_data(self.myKeywords)
  4558. def on_edit_join(self, name=None):
  4559. """
  4560. Callback for Edit->Join. Joins the selected geometry objects into
  4561. a new one.
  4562. :return: None
  4563. """
  4564. self.report_usage("on_edit_join()")
  4565. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4566. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4567. geo_type_set = set()
  4568. objs = self.collection.get_selected()
  4569. if len(objs) < 2:
  4570. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4571. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4572. return 'fail'
  4573. for obj in objs:
  4574. geo_type_set.add(obj.multigeo)
  4575. # if len(geo_type_list) == 1 means that all list elements are the same
  4576. if len(geo_type_set) != 1:
  4577. self.inform.emit('[ERROR] %s' %
  4578. _("Failed join. The Geometry objects are of different types.\n"
  4579. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4580. "convert from one to another and retry joining \n"
  4581. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4582. "the result may not be what was expected. \n"
  4583. "Check the generated GCODE."))
  4584. return
  4585. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4586. if True in geo_type_set:
  4587. def initialize(geo_obj, app):
  4588. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4589. app.inform.emit('[success] %s.' % _("Multigeo. Geometry merging finished"))
  4590. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4591. for v in obj.tools.values():
  4592. v['data']['name'] = obj_name_multi
  4593. self.new_object("geometry", obj_name_multi, initialize)
  4594. else:
  4595. def initialize(geo_obj, app):
  4596. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4597. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4598. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4599. for v in obj.tools.values():
  4600. v['data']['name'] = obj_name_single
  4601. self.new_object("geometry", obj_name_single, initialize)
  4602. self.should_we_save = True
  4603. def on_edit_join_exc(self):
  4604. """
  4605. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4606. a new Excellon.
  4607. :return: None
  4608. """
  4609. self.report_usage("on_edit_join_exc()")
  4610. objs = self.collection.get_selected()
  4611. for obj in objs:
  4612. if not isinstance(obj, FlatCAMExcellon):
  4613. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4614. return
  4615. if len(objs) < 2:
  4616. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4617. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4618. return 'fail'
  4619. def initialize(exc_obj, app):
  4620. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=exc_obj)
  4621. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4622. self.new_object("excellon", 'Combo_Excellon', initialize)
  4623. self.should_we_save = True
  4624. def on_edit_join_grb(self):
  4625. """
  4626. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4627. a new Gerber object.
  4628. :return: None
  4629. """
  4630. self.report_usage("on_edit_join_grb()")
  4631. objs = self.collection.get_selected()
  4632. for obj in objs:
  4633. if not isinstance(obj, FlatCAMGerber):
  4634. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4635. return
  4636. if len(objs) < 2:
  4637. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4638. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4639. return 'fail'
  4640. def initialize(grb_obj, app):
  4641. FlatCAMGerber.merge(self, grb_list=objs, grb_final=grb_obj)
  4642. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4643. self.new_object("gerber", 'Combo_Gerber', initialize)
  4644. self.should_we_save = True
  4645. def on_convert_singlegeo_to_multigeo(self):
  4646. """
  4647. Called for converting a Geometry object from single-geo to multi-geo.
  4648. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4649. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4650. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4651. the solid-geometry of that tool.
  4652. :return: None
  4653. """
  4654. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4655. obj = self.collection.get_active()
  4656. if obj is None:
  4657. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4658. return
  4659. if not isinstance(obj, FlatCAMGeometry):
  4660. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4661. return
  4662. obj.multigeo = True
  4663. for tooluid, dict_value in obj.tools.items():
  4664. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4665. if not isinstance(obj.solid_geometry, list):
  4666. obj.solid_geometry = [obj.solid_geometry]
  4667. obj.solid_geometry[:] = []
  4668. obj.plot()
  4669. self.should_we_save = True
  4670. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4671. def on_convert_multigeo_to_singlegeo(self):
  4672. """
  4673. Called for converting a Geometry object from multi-geo to single-geo.
  4674. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4675. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4676. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4677. the solid-geometry of that tool.
  4678. :return: None
  4679. """
  4680. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4681. obj = self.collection.get_active()
  4682. if obj is None:
  4683. self.inform.emit('[ERROR_NOTCL] %s' %
  4684. _("Failed. Select a Geometry Object and try again."))
  4685. return
  4686. if not isinstance(obj, FlatCAMGeometry):
  4687. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4688. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4689. return
  4690. obj.multigeo = False
  4691. total_solid_geometry = []
  4692. for tooluid, dict_value in obj.tools.items():
  4693. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4694. # clear the original geometry
  4695. dict_value['solid_geometry'][:] = []
  4696. obj.solid_geometry = deepcopy(total_solid_geometry)
  4697. obj.plot()
  4698. self.should_we_save = True
  4699. self.inform.emit('[success] %s' %
  4700. _("A Geometry object was converted to SingleGeo type."))
  4701. def on_defaults_dict_change(self, field):
  4702. """
  4703. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4704. Edit -> Preferences tab window.
  4705. :param field: the key of the self.defaults dictionary that was changed.
  4706. :return: None
  4707. """
  4708. self.defaults_write_form_field(field)
  4709. if field == "units":
  4710. self.set_screen_units(self.defaults['units'])
  4711. def set_screen_units(self, units):
  4712. """
  4713. Set the FlatCAM units on the status bar.
  4714. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4715. :return: None
  4716. """
  4717. self.ui.units_label.setText("[" + units.lower() + "]")
  4718. def on_toggle_units_click(self):
  4719. try:
  4720. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4721. except (TypeError, AttributeError):
  4722. pass
  4723. if self.defaults["units"] == 'MM':
  4724. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4725. else:
  4726. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4727. self.on_toggle_units(no_pref=True)
  4728. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4729. lambda: self.on_toggle_units(no_pref=False))
  4730. def on_toggle_units(self, no_pref=False):
  4731. """
  4732. Callback for the Units radio-button change in the Preferences tab.
  4733. Changes the application's default units adn for the project too.
  4734. If changing the project's units, the change propagates to all of
  4735. the objects in the project.
  4736. :return: None
  4737. """
  4738. self.report_usage("on_toggle_units")
  4739. if self.toggle_units_ignore:
  4740. return
  4741. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4742. # If option is the same, then ignore
  4743. if new_units == self.defaults["units"].upper():
  4744. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4745. return
  4746. # Options to scale
  4747. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4748. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4749. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4750. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4751. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4752. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4753. "excellon_editor_slot_lin_pitch",
  4754. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4755. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4756. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4757. "geometry_feedrate_probe", "geometry_startz",
  4758. 'cncjob_tooldia',
  4759. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4760. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4761. "tools_nccnewdia",
  4762. "tools_2sided_drilldia", "tools_film_boundary",
  4763. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4764. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4765. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4766. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4767. "tools_transform_offset_y",
  4768. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4769. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4770. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4771. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4772. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4773. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4774. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4775. "tools_fiducials_mode", "tools_fiducials_second_pos", "tools_fiducials_type",
  4776. "tools_fiducials_line_thickness",
  4777. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4778. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4779. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4780. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4781. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4782. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4783. def scale_defaults(sfactor):
  4784. for dim in dimensions:
  4785. if dim == 'excellon_toolchangexy':
  4786. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4787. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4788. coords_xy[0] *= sfactor
  4789. coords_xy[1] *= sfactor
  4790. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4791. self.decimals, coords_xy[1])
  4792. elif dim == 'geometry_toolchangexy':
  4793. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4794. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4795. coords_xy[0] *= sfactor
  4796. coords_xy[1] *= sfactor
  4797. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4798. self.decimals, coords_xy[1])
  4799. elif dim == 'geometry_cnctooldia':
  4800. tools_diameters = []
  4801. try:
  4802. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4803. tools_diameters = [eval(a) for a in tools_string if a != '']
  4804. except Exception as e:
  4805. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4806. self.defaults['geometry_cnctooldia'] = ''
  4807. for t in range(len(tools_diameters)):
  4808. tools_diameters[t] *= sfactor
  4809. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  4810. elif dim == 'tools_ncctools':
  4811. ncctools = []
  4812. try:
  4813. tools_string = self.defaults["tools_ncctools"].split(",")
  4814. ncctools = [eval(a) for a in tools_string if a != '']
  4815. except Exception as e:
  4816. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4817. self.defaults['tools_ncctools'] = ''
  4818. for t in range(len(ncctools)):
  4819. ncctools[t] *= sfactor
  4820. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  4821. elif dim == 'tools_solderpaste_tools':
  4822. sptools = []
  4823. try:
  4824. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4825. sptools = [eval(a) for a in tools_string if a != '']
  4826. except Exception as e:
  4827. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4828. self.defaults['tools_solderpaste_tools'] = ""
  4829. for t in range(len(sptools)):
  4830. sptools[t] *= sfactor
  4831. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  4832. elif dim == 'tools_solderpaste_xy_toolchange':
  4833. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4834. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4835. sp_coords[0] *= sfactor
  4836. sp_coords[1] *= sfactor
  4837. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  4838. self.decimals, sp_coords[1])
  4839. elif dim == 'global_gridx' or dim == 'global_gridy':
  4840. if new_units == 'IN':
  4841. val = 0.1
  4842. try:
  4843. val = float(self.defaults[dim]) * sfactor
  4844. except Exception as e:
  4845. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4846. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4847. else:
  4848. val = 0.1
  4849. try:
  4850. val = float(self.defaults[dim]) * sfactor
  4851. except Exception as e:
  4852. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4853. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4854. else:
  4855. val = 0.1
  4856. if self.defaults[dim]:
  4857. try:
  4858. val = float(self.defaults[dim]) * sfactor
  4859. except Exception as e:
  4860. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4861. self.defaults[dim] = val
  4862. # The scaling factor depending on choice of units.
  4863. factor = 25.4 if new_units == 'MM' else 1/25.4
  4864. # Changing project units. Warn user.
  4865. msgbox = QtWidgets.QMessageBox()
  4866. msgbox.setWindowTitle(_("Toggle Units"))
  4867. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4868. msgbox.setText(_("Changing the units of the project\n"
  4869. "will scale all objects.\n\n"
  4870. "Do you want to continue?"))
  4871. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4872. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4873. msgbox.setDefaultButton(bt_ok)
  4874. msgbox.exec_()
  4875. response = msgbox.clickedButton()
  4876. if response == bt_ok:
  4877. if no_pref is False:
  4878. self.defaults_read_form()
  4879. scale_defaults(factor)
  4880. self.defaults_write_form(fl_units=new_units)
  4881. self.defaults["units"] = new_units
  4882. # update the defaults from form, some may assume that the conversion is enough and it's not
  4883. self.on_options_app2project()
  4884. # update the objects
  4885. for obj in self.collection.get_list():
  4886. obj.convert_units(new_units)
  4887. # make that the properties stored in the object are also updated
  4888. self.object_changed.emit(obj)
  4889. # rebuild the object UI
  4890. obj.build_ui()
  4891. # change this only if the workspace is active
  4892. if self.defaults['global_workspace'] is True:
  4893. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  4894. # adjust the grid values on the main toolbar
  4895. val_x = float(self.defaults['global_gridx']) * factor
  4896. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  4897. current = self.collection.get_active()
  4898. if current is not None:
  4899. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4900. if not isinstance(current, FlatCAMGeometry):
  4901. current.to_form()
  4902. # replot all objects
  4903. self.plot_all()
  4904. # set the status labels to reflect the current FlatCAM units
  4905. self.set_screen_units(new_units)
  4906. # signal to the app that we changed the object properties and it shoud save the project
  4907. self.should_we_save = True
  4908. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  4909. else:
  4910. # Undo toggling
  4911. self.toggle_units_ignore = True
  4912. if self.defaults['units'].upper() == 'MM':
  4913. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4914. else:
  4915. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4916. self.toggle_units_ignore = False
  4917. # store the grid values so they are not changed in the next step
  4918. val_x = float(self.defaults['global_gridx'])
  4919. val_y = float(self.defaults['global_gridy'])
  4920. self.inform.emit('[WARNING_NOTCL]%s' % _("Units conversion cancelled."))
  4921. self.defaults_read_form()
  4922. # the self.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  4923. # I don't want it for the grid values, so I update them here
  4924. self.defaults['global_gridx'] = val_x
  4925. self.defaults['global_gridy'] = val_y
  4926. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  4927. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  4928. def on_fullscreen(self, disable=False):
  4929. self.report_usage("on_fullscreen()")
  4930. if self.toggle_fscreen is False and disable is False:
  4931. # self.ui.showFullScreen()
  4932. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4933. a = self.ui.geometry()
  4934. self.x_pos = a.x()
  4935. self.y_pos = a.y()
  4936. self.width = a.width()
  4937. self.height = a.height()
  4938. # set new geometry to full desktop rect
  4939. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4940. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4941. # everything else will not work without this hack. This happen in Windows.
  4942. # https://bugreports.qt.io/browse/QTBUG-41309
  4943. desktop = QtWidgets.QApplication.desktop()
  4944. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4945. rec = desktop.screenGeometry(screen)
  4946. x = rec.x() - 1
  4947. y = rec.y() - 1
  4948. h = rec.height() + 2
  4949. w = rec.width() + 2
  4950. self.ui.setGeometry(x, y, w, h)
  4951. self.ui.show()
  4952. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4953. tb.setVisible(False)
  4954. self.ui.splitter_left.setVisible(False)
  4955. self.toggle_fscreen = True
  4956. elif self.toggle_fscreen is True or disable is True:
  4957. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4958. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4959. self.ui.showNormal()
  4960. self.restore_toolbar_view()
  4961. self.ui.splitter_left.setVisible(True)
  4962. self.toggle_fscreen = False
  4963. def on_toggle_plotarea(self):
  4964. self.report_usage("on_toggle_plotarea()")
  4965. try:
  4966. name = self.ui.plot_tab_area.widget(0).objectName()
  4967. except AttributeError:
  4968. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4969. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4970. self.ui.plot_tab_area.protectTab(0)
  4971. return
  4972. if name != 'plotarea':
  4973. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4974. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4975. self.ui.plot_tab_area.protectTab(0)
  4976. else:
  4977. self.ui.plot_tab_area.closeTab(0)
  4978. def on_toggle_notebook(self):
  4979. if self.ui.splitter.sizes()[0] == 0:
  4980. self.ui.splitter.setSizes([1, 1])
  4981. self.ui.menu_toggle_nb.setChecked(True)
  4982. else:
  4983. self.ui.splitter.setSizes([0, 1])
  4984. self.ui.menu_toggle_nb.setChecked(False)
  4985. def on_toggle_axis(self):
  4986. self.report_usage("on_toggle_axis()")
  4987. if self.toggle_axis is False:
  4988. if self.is_legacy is False:
  4989. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4990. parent=self.plotcanvas.view.scene)
  4991. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4992. parent=self.plotcanvas.view.scene)
  4993. else:
  4994. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  4995. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  4996. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4997. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4998. self.plotcanvas.canvas.draw()
  4999. self.toggle_axis = True
  5000. else:
  5001. if self.is_legacy is False:
  5002. self.plotcanvas.v_line.parent = None
  5003. self.plotcanvas.h_line.parent = None
  5004. else:
  5005. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  5006. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  5007. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  5008. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  5009. self.plotcanvas.canvas.draw()
  5010. self.toggle_axis = False
  5011. def on_toggle_grid(self):
  5012. self.report_usage("on_toggle_grid()")
  5013. self.ui.grid_snap_btn.trigger()
  5014. def on_toggle_grid_lines(self):
  5015. self.report_usage("on_toggle_grd_lines()")
  5016. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  5017. if tt_settings.contains("theme"):
  5018. theme = tt_settings.value('theme', type=str)
  5019. else:
  5020. theme = 'white'
  5021. if self.toggle_grid_lines is False:
  5022. if self.is_legacy is False:
  5023. if theme == 'white':
  5024. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  5025. else:
  5026. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  5027. else:
  5028. self.plotcanvas.axes.grid(True)
  5029. try:
  5030. self.plotcanvas.canvas.draw()
  5031. except IndexError:
  5032. pass
  5033. pass
  5034. self.toggle_grid_lines = True
  5035. else:
  5036. if self.is_legacy is False:
  5037. if theme == 'white':
  5038. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  5039. else:
  5040. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  5041. else:
  5042. self.plotcanvas.axes.grid(False)
  5043. try:
  5044. self.plotcanvas.canvas.draw()
  5045. except IndexError:
  5046. pass
  5047. self.toggle_grid_lines = False
  5048. if self.is_legacy is False:
  5049. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  5050. # - perhaps is a bug in VisPy implementation
  5051. if self.grid_status() is True:
  5052. self.app_cursor.enabled = False
  5053. self.app_cursor.enabled = True
  5054. else:
  5055. self.app_cursor.enabled = True
  5056. self.app_cursor.enabled = False
  5057. def show_preferences_gui(self):
  5058. """
  5059. Called to initialize and show the Preferences GUI
  5060. :return: None
  5061. """
  5062. self.gen_form = self.ui.general_defaults_form
  5063. self.ger_form = self.ui.gerber_defaults_form
  5064. self.exc_form = self.ui.excellon_defaults_form
  5065. self.geo_form = self.ui.geometry_defaults_form
  5066. self.cnc_form = self.ui.cncjob_defaults_form
  5067. self.tools_form = self.ui.tools_defaults_form
  5068. self.tools2_form = self.ui.tools2_defaults_form
  5069. self.fa_form = self.ui.util_defaults_form
  5070. try:
  5071. self.ui.general_scroll_area.takeWidget()
  5072. except Exception:
  5073. self.log.debug("Nothing to remove")
  5074. self.ui.general_scroll_area.setWidget(self.gen_form)
  5075. self.gen_form.show()
  5076. try:
  5077. self.ui.gerber_scroll_area.takeWidget()
  5078. except Exception:
  5079. self.log.debug("Nothing to remove")
  5080. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5081. self.ger_form.show()
  5082. try:
  5083. self.ui.excellon_scroll_area.takeWidget()
  5084. except Exception:
  5085. self.log.debug("Nothing to remove")
  5086. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5087. self.exc_form.show()
  5088. try:
  5089. self.ui.geometry_scroll_area.takeWidget()
  5090. except Exception:
  5091. self.log.debug("Nothing to remove")
  5092. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5093. self.geo_form.show()
  5094. try:
  5095. self.ui.cncjob_scroll_area.takeWidget()
  5096. except Exception:
  5097. self.log.debug("Nothing to remove")
  5098. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5099. self.cnc_form.show()
  5100. try:
  5101. self.ui.tools_scroll_area.takeWidget()
  5102. except Exception:
  5103. self.log.debug("Nothing to remove")
  5104. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5105. self.tools_form.show()
  5106. try:
  5107. self.ui.tools2_scroll_area.takeWidget()
  5108. except Exception:
  5109. self.log.debug("Nothing to remove")
  5110. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5111. self.tools2_form.show()
  5112. try:
  5113. self.ui.fa_scroll_area.takeWidget()
  5114. except Exception:
  5115. self.log.debug("Nothing to remove")
  5116. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5117. self.fa_form.show()
  5118. self.log.debug("Finished Preferences GUI form initialization.")
  5119. # self.options2form()
  5120. def init_color_pickers_in_preferences_gui(self):
  5121. # Init Plot Colors
  5122. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  5123. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5124. "background-color:%s;"
  5125. "border-color: dimgray" % str(self.defaults['global_plot_fill'])[:7])
  5126. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  5127. int(self.defaults['global_plot_fill'][7:9], 16))
  5128. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  5129. int(self.defaults['global_plot_fill'][7:9], 16))
  5130. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  5131. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5132. "background-color:%s;"
  5133. "border-color: dimgray" % str(self.defaults['global_plot_line'])[:7])
  5134. # Init Left-Right Selection colors
  5135. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  5136. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5137. "background-color:%s;"
  5138. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  5139. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  5140. int(self.defaults['global_sel_fill'][7:9], 16))
  5141. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  5142. int(self.defaults['global_sel_fill'][7:9], 16))
  5143. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  5144. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5145. "background-color:%s;"
  5146. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  5147. # Init Right-Left Selection colors
  5148. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  5149. self.defaults['global_alt_sel_fill'])
  5150. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5151. "background-color:%s;"
  5152. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  5153. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  5154. int(self.defaults['global_sel_fill'][7:9], 16))
  5155. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  5156. int(self.defaults['global_sel_fill'][7:9], 16))
  5157. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  5158. self.defaults['global_alt_sel_line'])
  5159. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5160. "background-color:%s;"
  5161. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  5162. # Init Draw color and Selection Draw Color
  5163. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  5164. self.defaults['global_draw_color'])
  5165. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5166. "background-color:%s;"
  5167. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  5168. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  5169. self.defaults['global_sel_draw_color'])
  5170. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5171. "background-color:%s;"
  5172. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  5173. # Init Project Items color
  5174. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  5175. self.defaults['global_proj_item_color'])
  5176. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5177. "background-color:%s;"
  5178. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  5179. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  5180. self.defaults['global_proj_item_dis_color'])
  5181. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5182. "background-color:%s;"
  5183. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  5184. # Init the Annotation CNC Job color
  5185. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  5186. self.defaults['cncjob_annotation_fontcolor'])
  5187. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5188. "background-color:%s;"
  5189. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  5190. # Init the Tool Film color
  5191. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  5192. self.defaults['tools_film_color'])
  5193. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5194. "background-color:%s;"
  5195. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  5196. )
  5197. # Init the Tool QRCode colors
  5198. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  5199. self.defaults['tools_qrcode_fill_color'])
  5200. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5201. "background-color:%s;"
  5202. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  5203. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  5204. self.defaults['tools_qrcode_back_color'])
  5205. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5206. "background-color:%s;"
  5207. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  5208. def on_excellon_defaults_button(self):
  5209. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  5210. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5211. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5212. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5213. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5214. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5215. log.debug("Excellon app defaults loaded ...")
  5216. def on_update_exc_export(self, state):
  5217. """
  5218. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5219. if the update_excellon_cb checkbox is checked
  5220. :param state: state of the checkbox whose signals is tied to his slot
  5221. :return:
  5222. """
  5223. if state:
  5224. # first try to disconnect
  5225. try:
  5226. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5227. disconnect(self.on_excellon_format_changed)
  5228. except TypeError:
  5229. pass
  5230. try:
  5231. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5232. disconnect(self.on_excellon_format_changed)
  5233. except TypeError:
  5234. pass
  5235. try:
  5236. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5237. disconnect(self.on_excellon_format_changed)
  5238. except TypeError:
  5239. pass
  5240. try:
  5241. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5242. disconnect(self.on_excellon_format_changed)
  5243. except TypeError:
  5244. pass
  5245. try:
  5246. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5247. disconnect(self.on_excellon_zeros_changed)
  5248. except TypeError:
  5249. pass
  5250. try:
  5251. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5252. disconnect(self.on_excellon_zeros_changed)
  5253. except TypeError:
  5254. pass
  5255. # the connect them
  5256. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5257. self.on_excellon_format_changed)
  5258. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5259. self.on_excellon_format_changed)
  5260. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5261. self.on_excellon_format_changed)
  5262. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5263. self.on_excellon_format_changed)
  5264. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5265. self.on_excellon_zeros_changed)
  5266. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5267. self.on_excellon_units_changed)
  5268. else:
  5269. # disconnect the signals
  5270. try:
  5271. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5272. disconnect(self.on_excellon_format_changed)
  5273. except TypeError:
  5274. pass
  5275. try:
  5276. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5277. disconnect(self.on_excellon_format_changed)
  5278. except TypeError:
  5279. pass
  5280. try:
  5281. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5282. disconnect(self.on_excellon_format_changed)
  5283. except TypeError:
  5284. pass
  5285. try:
  5286. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5287. disconnect(self.on_excellon_format_changed)
  5288. except TypeError:
  5289. pass
  5290. try:
  5291. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5292. disconnect(self.on_excellon_zeros_changed)
  5293. except TypeError:
  5294. pass
  5295. try:
  5296. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5297. disconnect(self.on_excellon_zeros_changed)
  5298. except TypeError:
  5299. pass
  5300. def on_excellon_format_changed(self):
  5301. """
  5302. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5303. :return: None
  5304. """
  5305. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5306. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5307. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5308. )
  5309. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5310. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5311. )
  5312. else:
  5313. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5314. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5315. )
  5316. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5317. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5318. )
  5319. def on_excellon_zeros_changed(self):
  5320. """
  5321. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5322. :return: None
  5323. """
  5324. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5325. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5326. )
  5327. def on_excellon_units_changed(self):
  5328. """
  5329. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5330. :return: None
  5331. """
  5332. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5333. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5334. )
  5335. self.on_excellon_format_changed()
  5336. # Setting plot colors handlers
  5337. def on_pf_color_entry(self):
  5338. self.defaults['global_plot_fill'] = \
  5339. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5340. self.defaults['global_plot_fill'][7:9]
  5341. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5342. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5343. def on_pf_color_button(self):
  5344. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5345. c_dialog = QtWidgets.QColorDialog()
  5346. plot_fill_color = c_dialog.getColor(initial=current_color)
  5347. if plot_fill_color.isValid() is False:
  5348. return
  5349. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5350. "background-color:%s" % str(plot_fill_color.name()))
  5351. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5352. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5353. self.defaults['global_plot_fill'] = new_val
  5354. def on_pf_color_spinner(self):
  5355. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5356. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5357. self.defaults['global_plot_fill'] = \
  5358. self.defaults['global_plot_fill'][:7] + \
  5359. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5360. self.defaults['global_plot_line'] = \
  5361. self.defaults['global_plot_line'][:7] + \
  5362. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5363. def on_pf_color_slider(self):
  5364. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5365. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5366. def on_pl_color_entry(self):
  5367. self.defaults['global_plot_line'] = \
  5368. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5369. self.defaults['global_plot_line'][7:9]
  5370. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5371. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5372. def on_pl_color_button(self):
  5373. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5374. # print(current_color)
  5375. c_dialog = QtWidgets.QColorDialog()
  5376. plot_line_color = c_dialog.getColor(initial=current_color)
  5377. if plot_line_color.isValid() is False:
  5378. return
  5379. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5380. "background-color:%s" % str(plot_line_color.name()))
  5381. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5382. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5383. self.defaults['global_plot_line'] = new_val_line
  5384. # Setting selection colors (left - right) handlers
  5385. def on_sf_color_entry(self):
  5386. self.defaults['global_sel_fill'] = \
  5387. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5388. self.defaults['global_sel_fill'][7:9]
  5389. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5390. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5391. def on_sf_color_button(self):
  5392. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5393. c_dialog = QtWidgets.QColorDialog()
  5394. plot_fill_color = c_dialog.getColor(initial=current_color)
  5395. if plot_fill_color.isValid() is False:
  5396. return
  5397. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5398. "background-color:%s" % str(plot_fill_color.name()))
  5399. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5400. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5401. self.defaults['global_sel_fill'] = new_val
  5402. def on_sf_color_spinner(self):
  5403. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5404. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5405. self.defaults['global_sel_fill'] = \
  5406. self.defaults['global_sel_fill'][:7] + \
  5407. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5408. self.defaults['global_sel_line'] = \
  5409. self.defaults['global_sel_line'][:7] + \
  5410. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5411. def on_sf_color_slider(self):
  5412. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5413. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5414. def on_sl_color_entry(self):
  5415. self.defaults['global_sel_line'] = \
  5416. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5417. self.defaults['global_sel_line'][7:9]
  5418. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5419. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5420. def on_sl_color_button(self):
  5421. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5422. c_dialog = QtWidgets.QColorDialog()
  5423. plot_line_color = c_dialog.getColor(initial=current_color)
  5424. if plot_line_color.isValid() is False:
  5425. return
  5426. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5427. "background-color:%s" % str(plot_line_color.name()))
  5428. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5429. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5430. self.defaults['global_sel_line'] = new_val_line
  5431. # Setting selection colors (right - left) handlers
  5432. def on_alt_sf_color_entry(self):
  5433. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5434. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5435. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5436. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5437. def on_alt_sf_color_button(self):
  5438. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5439. c_dialog = QtWidgets.QColorDialog()
  5440. plot_fill_color = c_dialog.getColor(initial=current_color)
  5441. if plot_fill_color.isValid() is False:
  5442. return
  5443. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5444. "background-color:%s" % str(plot_fill_color.name()))
  5445. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5446. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5447. self.defaults['global_alt_sel_fill'] = new_val
  5448. def on_alt_sf_color_spinner(self):
  5449. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5450. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5451. self.defaults['global_alt_sel_fill'] = \
  5452. self.defaults['global_alt_sel_fill'][:7] + \
  5453. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5454. self.defaults['global_alt_sel_line'] = \
  5455. self.defaults['global_alt_sel_line'][:7] + \
  5456. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5457. def on_alt_sf_color_slider(self):
  5458. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5459. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5460. def on_alt_sl_color_entry(self):
  5461. self.defaults['global_alt_sel_line'] = \
  5462. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5463. self.defaults['global_alt_sel_line'][7:9]
  5464. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5465. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5466. def on_alt_sl_color_button(self):
  5467. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5468. c_dialog = QtWidgets.QColorDialog()
  5469. plot_line_color = c_dialog.getColor(initial=current_color)
  5470. if plot_line_color.isValid() is False:
  5471. return
  5472. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5473. "background-color:%s" % str(plot_line_color.name()))
  5474. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5475. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5476. self.defaults['global_alt_sel_line'] = new_val_line
  5477. # Setting Editor colors
  5478. def on_draw_color_entry(self):
  5479. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5480. .draw_color_entry.get_value()
  5481. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5482. "background-color:%s" % str(self.defaults['global_draw_color']))
  5483. def on_draw_color_button(self):
  5484. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5485. c_dialog = QtWidgets.QColorDialog()
  5486. draw_color = c_dialog.getColor(initial=current_color)
  5487. if draw_color.isValid() is False:
  5488. return
  5489. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5490. "background-color:%s" % str(draw_color.name()))
  5491. new_val = str(draw_color.name())
  5492. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5493. self.defaults['global_draw_color'] = new_val
  5494. def on_sel_draw_color_entry(self):
  5495. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5496. .sel_draw_color_entry.get_value()
  5497. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5498. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5499. def on_sel_draw_color_button(self):
  5500. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5501. c_dialog = QtWidgets.QColorDialog()
  5502. sel_draw_color = c_dialog.getColor(initial=current_color)
  5503. if sel_draw_color.isValid() is False:
  5504. return
  5505. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5506. "background-color:%s" % str(sel_draw_color.name()))
  5507. new_val_sel = str(sel_draw_color.name())
  5508. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5509. self.defaults['global_sel_draw_color'] = new_val_sel
  5510. def on_proj_color_entry(self):
  5511. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5512. .proj_color_entry.get_value()
  5513. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5514. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5515. def on_proj_color_button(self):
  5516. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5517. c_dialog = QtWidgets.QColorDialog()
  5518. proj_color = c_dialog.getColor(initial=current_color)
  5519. if proj_color.isValid() is False:
  5520. return
  5521. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5522. "background-color:%s" % str(proj_color.name()))
  5523. new_val_sel = str(proj_color.name())
  5524. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5525. self.defaults['global_proj_item_color'] = new_val_sel
  5526. def on_proj_color_dis_entry(self):
  5527. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5528. .proj_color_dis_entry.get_value()
  5529. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5530. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5531. def on_proj_color_dis_button(self):
  5532. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5533. c_dialog = QtWidgets.QColorDialog()
  5534. proj_color = c_dialog.getColor(initial=current_color)
  5535. if proj_color.isValid() is False:
  5536. return
  5537. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5538. "background-color:%s" % str(proj_color.name()))
  5539. new_val_sel = str(proj_color.name())
  5540. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5541. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5542. def on_annotation_fontcolor_entry(self):
  5543. self.defaults['cncjob_annotation_fontcolor'] = \
  5544. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5545. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5546. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5547. def on_annotation_fontcolor_button(self):
  5548. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5549. c_dialog = QtWidgets.QColorDialog()
  5550. annotation_color = c_dialog.getColor(initial=current_color)
  5551. if annotation_color.isValid() is False:
  5552. return
  5553. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5554. "background-color:%s" % str(annotation_color.name()))
  5555. new_val_sel = str(annotation_color.name())
  5556. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5557. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5558. def on_film_color_entry(self):
  5559. self.defaults['tools_film_color'] = \
  5560. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5561. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5562. "background-color:%s;"
  5563. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5564. )
  5565. def on_film_color_button(self):
  5566. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5567. c_dialog = QtWidgets.QColorDialog()
  5568. film_color = c_dialog.getColor(initial=current_color)
  5569. if film_color.isValid() is False:
  5570. return
  5571. # if new color is different then mark that the Preferences are changed
  5572. if film_color != current_color:
  5573. self.on_preferences_edited()
  5574. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5575. "background-color:%s;"
  5576. "border-color: dimgray" % str(film_color.name())
  5577. )
  5578. new_val_sel = str(film_color.name())
  5579. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5580. self.defaults['tools_film_color'] = new_val_sel
  5581. def on_qrcode_fill_color_entry(self):
  5582. self.defaults['tools_qrcode_fill_color'] = \
  5583. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5584. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5585. "background-color:%s;"
  5586. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5587. )
  5588. def on_qrcode_fill_color_button(self):
  5589. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5590. c_dialog = QtWidgets.QColorDialog()
  5591. fill_color = c_dialog.getColor(initial=current_color)
  5592. if fill_color.isValid() is False:
  5593. return
  5594. # if new color is different then mark that the Preferences are changed
  5595. if fill_color != current_color:
  5596. self.on_preferences_edited()
  5597. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5598. "background-color:%s;"
  5599. "border-color: dimgray" % str(fill_color.name())
  5600. )
  5601. new_val_sel = str(fill_color.name())
  5602. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5603. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5604. def on_qrcode_back_color_entry(self):
  5605. self.defaults['tools_qrcode_back_color'] = \
  5606. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5607. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5608. "background-color:%s;"
  5609. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5610. )
  5611. def on_qrcode_back_color_button(self):
  5612. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5613. c_dialog = QtWidgets.QColorDialog()
  5614. back_color = c_dialog.getColor(initial=current_color)
  5615. if back_color.isValid() is False:
  5616. return
  5617. # if new color is different then mark that the Preferences are changed
  5618. if back_color != current_color:
  5619. self.on_preferences_edited()
  5620. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5621. "background-color:%s;"
  5622. "border-color: dimgray" % str(back_color.name())
  5623. )
  5624. new_val_sel = str(back_color.name())
  5625. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5626. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5627. def on_splash_changed(self, state):
  5628. settings = QSettings("Open Source", "FlatCAM")
  5629. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5630. # This will write the setting to the platform specific storage.
  5631. del settings
  5632. def on_tab_rmb_click(self, checked):
  5633. self.ui.notebook.set_detachable(val=checked)
  5634. self.defaults["global_tabs_detachable"] = checked
  5635. self.ui.plot_tab_area.set_detachable(val=checked)
  5636. self.defaults["global_tabs_detachable"] = checked
  5637. def on_tab_setup_context_menu(self):
  5638. initial_checked = self.defaults["global_tabs_detachable"]
  5639. action_name = str(_("Detachable Tabs"))
  5640. action = QtWidgets.QAction(self)
  5641. action.setCheckable(True)
  5642. action.setText(action_name)
  5643. action.setChecked(initial_checked)
  5644. self.ui.notebook.tabBar.addAction(action)
  5645. self.ui.plot_tab_area.tabBar.addAction(action)
  5646. try:
  5647. action.triggered.disconnect()
  5648. except TypeError:
  5649. pass
  5650. action.triggered.connect(self.on_tab_rmb_click)
  5651. def on_deselect_all(self):
  5652. self.collection.set_all_inactive()
  5653. self.delete_selection_shape()
  5654. def on_workspace_modified(self):
  5655. # self.save_defaults(silent=True)
  5656. if self.is_legacy is True:
  5657. self.plotcanvas.delete_workspace()
  5658. self.defaults_read_form()
  5659. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5660. def on_workspace(self):
  5661. if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value():
  5662. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5663. else:
  5664. self.plotcanvas.delete_workspace()
  5665. self.defaults_read_form()
  5666. # self.save_defaults(silent=True)
  5667. def on_workspace_toggle(self):
  5668. state = False if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value() else True
  5669. try:
  5670. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  5671. except TypeError:
  5672. pass
  5673. self.ui.general_defaults_form.general_gui_group.workspace_cb.set_value(state)
  5674. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  5675. self.on_workspace()
  5676. def on_layout(self, index=None, lay=None):
  5677. """
  5678. Set the toolbars layout (location)
  5679. :param index:
  5680. :param lay: type of layout to be set on the toolbard
  5681. :return: None
  5682. """
  5683. self.report_usage("on_layout()")
  5684. if lay:
  5685. current_layout = lay
  5686. else:
  5687. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5688. lay_settings = QSettings("Open Source", "FlatCAM")
  5689. lay_settings.setValue('layout', current_layout)
  5690. # This will write the setting to the platform specific storage.
  5691. del lay_settings
  5692. # first remove the toolbars:
  5693. try:
  5694. self.ui.removeToolBar(self.ui.toolbarfile)
  5695. self.ui.removeToolBar(self.ui.toolbargeo)
  5696. self.ui.removeToolBar(self.ui.toolbarview)
  5697. self.ui.removeToolBar(self.ui.toolbarshell)
  5698. self.ui.removeToolBar(self.ui.toolbartools)
  5699. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5700. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5701. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5702. self.ui.removeToolBar(self.ui.snap_toolbar)
  5703. self.ui.removeToolBar(self.ui.toolbarshell)
  5704. except Exception:
  5705. pass
  5706. if current_layout == 'standard':
  5707. # ## TOOLBAR INSTALLATION # ##
  5708. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5709. self.ui.toolbarfile.setObjectName('File_TB')
  5710. self.ui.addToolBar(self.ui.toolbarfile)
  5711. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5712. self.ui.toolbargeo.setObjectName('Edit_TB')
  5713. self.ui.addToolBar(self.ui.toolbargeo)
  5714. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5715. self.ui.toolbarview.setObjectName('View_TB')
  5716. self.ui.addToolBar(self.ui.toolbarview)
  5717. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5718. self.ui.toolbarshell.setObjectName('Shell_TB')
  5719. self.ui.addToolBar(self.ui.toolbarshell)
  5720. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5721. self.ui.toolbartools.setObjectName('Tools_TB')
  5722. self.ui.addToolBar(self.ui.toolbartools)
  5723. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5724. # self.ui.exc_edit_toolbar.setVisible(False)
  5725. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5726. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5727. self.ui.addToolBarBreak()
  5728. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5729. # self.ui.geo_edit_toolbar.setVisible(False)
  5730. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5731. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5732. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5733. # self.ui.grb_edit_toolbar.setVisible(False)
  5734. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5735. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5736. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5737. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5738. # self.ui.snap_toolbar.setMaximumHeight(30)
  5739. self.ui.addToolBar(self.ui.snap_toolbar)
  5740. self.ui.corner_snap_btn.setVisible(False)
  5741. self.ui.snap_magnet.setVisible(False)
  5742. elif current_layout == 'compact':
  5743. # ## TOOLBAR INSTALLATION # ##
  5744. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5745. self.ui.toolbarfile.setObjectName('File_TB')
  5746. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5747. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5748. self.ui.toolbargeo.setObjectName('Edit_TB')
  5749. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5750. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5751. self.ui.toolbarshell.setObjectName('Shell_TB')
  5752. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5753. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5754. self.ui.toolbartools.setObjectName('Tools_TB')
  5755. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5756. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5757. # self.ui.geo_edit_toolbar.setVisible(False)
  5758. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5759. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5760. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5761. self.ui.toolbarview.setObjectName('View_TB')
  5762. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5763. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5764. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5765. # self.ui.grb_edit_toolbar.setVisible(False)
  5766. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5767. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5768. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5769. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5770. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5771. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5772. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5773. self.ui.snap_toolbar.setMaximumHeight(30)
  5774. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5775. self.ui.corner_snap_btn.setVisible(True)
  5776. self.ui.snap_magnet.setVisible(True)
  5777. # add all the actions to the toolbars
  5778. self.ui.populate_toolbars()
  5779. # reconnect all the signals to the toolbar actions
  5780. self.connect_toolbar_signals()
  5781. self.ui.grid_snap_btn.setChecked(True)
  5782. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5783. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5784. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5785. self.ui.grid_gap_link_cb.setChecked(True)
  5786. def on_cursor_type(self, val):
  5787. """
  5788. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5789. :return: None
  5790. """
  5791. self.app_cursor.enabled = False
  5792. if val == 'small':
  5793. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5794. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5795. self.app_cursor = self.plotcanvas.new_cursor()
  5796. else:
  5797. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5798. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5799. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5800. if self.ui.grid_snap_btn.isChecked():
  5801. self.app_cursor.enabled = True
  5802. else:
  5803. self.app_cursor.enabled = False
  5804. def on_cnc_custom_parameters(self, signal_text):
  5805. if signal_text == 'Parameters':
  5806. return
  5807. else:
  5808. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5809. def on_save_button(self, save_to_file=True):
  5810. log.debug("App.on_save_button() --> Applying preferences to file.")
  5811. # Preferences saved, update flag
  5812. self.preferences_changed_flag = False
  5813. # Preferences save, update the color of the Preferences Tab text
  5814. for idx in range(self.ui.plot_tab_area.count()):
  5815. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5816. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5817. self.inform.emit('%s' % _("Preferences applied."))
  5818. if save_to_file:
  5819. self.save_defaults(silent=False)
  5820. # load the defaults so they are updated into the app
  5821. self.load_defaults(filename='current_defaults')
  5822. # Re-fresh project options
  5823. self.on_options_app2project()
  5824. settgs = QSettings("Open Source", "FlatCAM")
  5825. # save the notebook font size
  5826. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5827. settgs.setValue('notebook_font_size', fsize)
  5828. # save the axis font size
  5829. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5830. settgs.setValue('axis_font_size', g_fsize)
  5831. # save the textbox font size
  5832. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5833. settgs.setValue('textbox_font_size', tb_fsize)
  5834. settgs.setValue(
  5835. 'machinist',
  5836. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  5837. )
  5838. # This will write the setting to the platform specific storage.
  5839. del settgs
  5840. def on_pref_close_button(self):
  5841. # Preferences saved, update flag
  5842. self.preferences_changed_flag = False
  5843. try:
  5844. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_plot_area_tab_closed)
  5845. except TypeError:
  5846. pass
  5847. self.defaults_write_form()
  5848. # Preferences save, update the color of the Preferences Tab text
  5849. for idx in range(self.ui.plot_tab_area.count()):
  5850. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5851. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5852. self.ui.plot_tab_area.closeTab(idx)
  5853. break
  5854. self.inform.emit('%s' % _("Preferences closed without saving."))
  5855. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  5856. def on_tool_add_keypress(self):
  5857. # ## Current application units in Upper Case
  5858. self.units = self.defaults['units'].upper()
  5859. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5860. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5861. if notebook_widget_name == 'selected_tab':
  5862. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5863. # Tool add works for Geometry only if Advanced is True in Preferences
  5864. if self.defaults["global_app_level"] == 'a':
  5865. tool_add_popup = FCInputDialog(title="New Tool ...",
  5866. text='Enter a Tool Diameter:',
  5867. min=0.0000, max=99.9999, decimals=4)
  5868. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5869. val, ok = tool_add_popup.get_value()
  5870. if ok:
  5871. if float(val) == 0:
  5872. self.inform.emit('[WARNING_NOTCL] %s' %
  5873. _("Please enter a tool diameter with non-zero value, in Float format."))
  5874. return
  5875. self.collection.get_active().on_tool_add(dia=float(val))
  5876. else:
  5877. self.inform.emit('[WARNING_NOTCL] %s...' %
  5878. _("Adding Tool cancelled"))
  5879. else:
  5880. msgbox = QtWidgets.QMessageBox()
  5881. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5882. "Go to Preferences -> General - Show Advanced Options."))
  5883. msgbox.setWindowTitle("Tool adding ...")
  5884. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5885. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5886. msgbox.setDefaultButton(bt_ok)
  5887. msgbox.exec_()
  5888. # work only if the notebook tab on focus is the Tools_Tab
  5889. if notebook_widget_name == 'tool_tab':
  5890. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5891. # and only if the tool is NCC Tool
  5892. if tool_widget == self.ncclear_tool.toolName:
  5893. self.ncclear_tool.on_add_tool_by_key()
  5894. # and only if the tool is Paint Area Tool
  5895. elif tool_widget == self.paint_tool.toolName:
  5896. self.paint_tool.on_add_tool_by_key()
  5897. # and only if the tool is Solder Paste Dispensing Tool
  5898. elif tool_widget == self.paste_tool.toolName:
  5899. self.paste_tool.on_add_tool_by_key()
  5900. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5901. # See description bellow.
  5902. def on_delete_keypress(self):
  5903. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5904. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5905. if notebook_widget_name == 'selected_tab':
  5906. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5907. self.collection.get_active().on_tool_delete()
  5908. # work only if the notebook tab on focus is the Tools_Tab
  5909. elif notebook_widget_name == 'tool_tab':
  5910. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5911. # and only if the tool is NCC Tool
  5912. if tool_widget == self.ncclear_tool.toolName:
  5913. self.ncclear_tool.on_tool_delete()
  5914. # and only if the tool is Paint Tool
  5915. elif tool_widget == self.paint_tool.toolName:
  5916. self.paint_tool.on_tool_delete()
  5917. # and only if the tool is Solder Paste Dispensing Tool
  5918. elif tool_widget == self.paste_tool.toolName:
  5919. self.paste_tool.on_tool_delete()
  5920. else:
  5921. self.on_delete()
  5922. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5923. # some screens you have to be careful where you hover with your mouse.
  5924. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5925. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5926. # Complicated, I know :)
  5927. def on_delete(self):
  5928. """
  5929. Delete the currently selected FlatCAMObjs.
  5930. :return: None
  5931. """
  5932. self.report_usage("on_delete()")
  5933. response = None
  5934. bt_ok = None
  5935. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5936. # a geometry object before we update it.
  5937. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5938. and self.grb_editor.editor_active is False:
  5939. if self.defaults["global_delete_confirmation"] is True:
  5940. msgbox = QtWidgets.QMessageBox()
  5941. msgbox.setWindowTitle(_("Delete objects"))
  5942. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5943. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5944. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5945. "the selected objects?"))
  5946. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5947. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5948. msgbox.setDefaultButton(bt_ok)
  5949. msgbox.exec_()
  5950. response = msgbox.clickedButton()
  5951. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5952. if self.collection.get_active():
  5953. self.log.debug("App.on_delete()")
  5954. while self.collection.get_active():
  5955. obj_active = self.collection.get_active()
  5956. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5957. if isinstance(obj_active, FlatCAMGerber):
  5958. for el in obj_active.mark_shapes:
  5959. obj_active.mark_shapes[el].clear(update=True)
  5960. obj_active.mark_shapes[el].enabled = False
  5961. # obj_active.mark_shapes[el] = None
  5962. del el
  5963. elif isinstance(obj_active, FlatCAMCNCjob):
  5964. try:
  5965. obj_active.annotation.clear(update=True)
  5966. obj_active.annotation.enabled = False
  5967. except AttributeError:
  5968. pass
  5969. self.delete_first_selected()
  5970. self.inform.emit('%s...' %
  5971. _("Object(s) deleted"))
  5972. # make sure that the selection shape is deleted, too
  5973. self.delete_selection_shape()
  5974. else:
  5975. self.inform.emit(_("Failed. No object(s) selected..."))
  5976. else:
  5977. self.inform.emit(_("Save the work in Editor and try again ..."))
  5978. def delete_first_selected(self):
  5979. # Keep this for later
  5980. try:
  5981. sel_obj = self.collection.get_active()
  5982. name = sel_obj.options["name"]
  5983. isPlotted = sel_obj.options["plot"]
  5984. except AttributeError:
  5985. self.log.debug("Nothing selected for deletion")
  5986. return
  5987. if self.is_legacy is True:
  5988. # Remove plot only if the object was plotted otherwise delaxes will fail
  5989. if isPlotted:
  5990. try:
  5991. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5992. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5993. except Exception as e:
  5994. log.debug("App.delete_first_selected() --> %s" % str(e))
  5995. self.plotcanvas.auto_adjust_axes()
  5996. # Remove from dictionary
  5997. self.collection.delete_active()
  5998. # Clear form
  5999. self.setup_component_editor()
  6000. self.inform.emit('%s: %s' %
  6001. (_("Object deleted"), name))
  6002. def on_set_origin(self):
  6003. """
  6004. Set the origin to the left mouse click position
  6005. :return: None
  6006. """
  6007. # display the message for the user
  6008. # and ask him to click on the desired position
  6009. self.report_usage("on_set_origin()")
  6010. def origin_replot():
  6011. def worker_task():
  6012. with self.proc_container.new('%s...' % _("Plotting")):
  6013. for obj in self.collection.get_list():
  6014. obj.plot()
  6015. self.plotcanvas.fit_view()
  6016. if self.is_legacy:
  6017. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  6018. else:
  6019. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  6020. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6021. self.inform.emit(_('Click to set the origin ...'))
  6022. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  6023. # first disconnect it as it may have been used by something else
  6024. try:
  6025. self.replot_signal.disconnect()
  6026. except TypeError:
  6027. pass
  6028. self.replot_signal[list].connect(origin_replot)
  6029. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  6030. """
  6031. :param event:
  6032. :param location:
  6033. :param noplot:
  6034. :param use_thread:
  6035. :return:
  6036. """
  6037. noplot_sig = noplot
  6038. def worker_task():
  6039. with self.proc_container.new(_("Setting Origin...")):
  6040. for obj in self.collection.get_list():
  6041. obj.offset((x, y))
  6042. self.object_changed.emit(obj)
  6043. # Update the object bounding box options
  6044. a, b, c, d = obj.bounds()
  6045. obj.options['xmin'] = a
  6046. obj.options['ymin'] = b
  6047. obj.options['xmax'] = c
  6048. obj.options['ymax'] = d
  6049. self.inform.emit('[success] %s...' %
  6050. _('Origin set'))
  6051. if noplot_sig is False:
  6052. self.replot_signal.emit([])
  6053. if location is not None:
  6054. if len(location) != 2:
  6055. self.inform.emit('[ERROR_NOTCL] %s...' %
  6056. _("Origin coordinates specified but incomplete."))
  6057. return 'fail'
  6058. x, y = location
  6059. if use_thread is True:
  6060. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6061. else:
  6062. worker_task()
  6063. self.should_we_save = True
  6064. return
  6065. if event.button == 1:
  6066. if self.is_legacy is False:
  6067. event_pos = event.pos
  6068. else:
  6069. event_pos = (event.xdata, event.ydata)
  6070. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6071. if self.grid_status() == True:
  6072. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6073. else:
  6074. pos = pos_canvas
  6075. x = 0 - pos[0]
  6076. y = 0 - pos[1]
  6077. if use_thread is True:
  6078. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6079. else:
  6080. worker_task()
  6081. self.should_we_save = True
  6082. def on_jump_to(self, custom_location=None, fit_center=True):
  6083. """
  6084. Jump to a location by setting the mouse cursor location
  6085. :return:
  6086. """
  6087. self.report_usage("on_jump_to()")
  6088. # if self.is_legacy is True:
  6089. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  6090. # return
  6091. if not custom_location:
  6092. dia_box_location = None
  6093. try:
  6094. dia_box_location = eval(self.clipboard.text())
  6095. except Exception:
  6096. pass
  6097. if type(dia_box_location) == tuple:
  6098. dia_box_location = str(dia_box_location)
  6099. else:
  6100. dia_box_location = None
  6101. dia_box = Dialog_box(title=_("Jump to ..."),
  6102. label=_("Enter the coordinates in format X,Y:"),
  6103. icon=QtGui.QIcon('share/jump_to16.png'),
  6104. initial_text=dia_box_location)
  6105. if dia_box.ok is True:
  6106. try:
  6107. location = eval(dia_box.location)
  6108. if not isinstance(location, tuple):
  6109. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6110. return
  6111. except Exception:
  6112. return
  6113. else:
  6114. return
  6115. else:
  6116. location = custom_location
  6117. units = self.defaults['units'].upper()
  6118. if fit_center:
  6119. self.plotcanvas.fit_center(loc=location)
  6120. cursor = QtGui.QCursor()
  6121. if self.is_legacy is False:
  6122. # I don't know where those differences come from but they are constant for the current
  6123. # execution of the application and they are multiples of a value around 0.0263mm.
  6124. # In a random way sometimes they are more sometimes they are less
  6125. # if units == 'MM':
  6126. # cal_factor = 0.0263
  6127. # else:
  6128. # cal_factor = 0.0263 / 25.4
  6129. cal_location = (location[0], location[1])
  6130. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6131. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  6132. j_pos = (
  6133. int(canvas_origin.x() + round(jump_loc[0])),
  6134. int(canvas_origin.y() + round(jump_loc[1]))
  6135. )
  6136. cursor.setPos(j_pos[0], j_pos[1])
  6137. else:
  6138. # find the canvas origin which is in the top left corner
  6139. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6140. # determine the coordinates for the lowest left point of the canvas
  6141. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6142. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6143. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6144. # canvas) and the point (width, height) is in the top-right location
  6145. loc = self.plotcanvas.axes.transData.transform_point(location)
  6146. j_pos = (
  6147. int(x0 + loc[0]),
  6148. int(y0 - loc[1])
  6149. )
  6150. cursor.setPos(j_pos[0], j_pos[1])
  6151. self.plotcanvas.mouse = [location[0], location[1]]
  6152. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  6153. if self.grid_status():
  6154. # Update cursor
  6155. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6156. symbol='++', edge_color=self.cursor_color_3D,
  6157. size=self.defaults["global_cursor_size"])
  6158. # Set the position label
  6159. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6160. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6161. # Set the relative position label
  6162. dx = location[0] - float(self.rel_point1[0])
  6163. dy = location[1] - float(self.rel_point1[1])
  6164. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6165. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6166. self.inform.emit('[success] %s' %
  6167. _("Done."))
  6168. return location
  6169. def on_copy_object(self):
  6170. self.report_usage("on_copy_object()")
  6171. def initialize(obj_init, app):
  6172. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6173. try:
  6174. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6175. except AttributeError:
  6176. pass
  6177. try:
  6178. obj_init.apertures = deepcopy(obj.apertures)
  6179. except AttributeError:
  6180. pass
  6181. try:
  6182. if obj.tools:
  6183. obj_init.tools = deepcopy(obj.tools)
  6184. except Exception as e:
  6185. log.debug("App.on_copy_object() --> %s" % str(e))
  6186. try:
  6187. obj_init.source_file = deepcopy(obj.source_file)
  6188. except (AttributeError, TypeError):
  6189. pass
  6190. def initialize_excellon(obj_init, app):
  6191. obj_init.source_file = deepcopy(obj.source_file)
  6192. obj_init.tools = deepcopy(obj.tools)
  6193. # drills are offset, so they need to be deep copied
  6194. obj_init.drills = deepcopy(obj.drills)
  6195. # slots are offset, so they need to be deep copied
  6196. obj_init.slots = deepcopy(obj.slots)
  6197. obj_init.create_geometry()
  6198. def initialize_script(obj_init, app_obj):
  6199. obj_init.source_file = deepcopy(obj.source_file)
  6200. def initialize_document(obj_init, app_obj):
  6201. obj_init.source_file = deepcopy(obj.source_file)
  6202. for obj in self.collection.get_selected():
  6203. obj_name = obj.options["name"]
  6204. try:
  6205. if isinstance(obj, FlatCAMExcellon):
  6206. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6207. elif isinstance(obj, FlatCAMGerber):
  6208. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6209. elif isinstance(obj, FlatCAMGeometry):
  6210. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6211. elif isinstance(obj, FlatCAMScript):
  6212. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6213. elif isinstance(obj, FlatCAMDocument):
  6214. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6215. except Exception as e:
  6216. return "Operation failed: %s" % str(e)
  6217. def on_copy_object2(self, custom_name):
  6218. def initialize_geometry(obj_init, app):
  6219. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6220. try:
  6221. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6222. except AttributeError:
  6223. pass
  6224. try:
  6225. obj_init.apertures = deepcopy(obj.apertures)
  6226. except AttributeError:
  6227. pass
  6228. try:
  6229. if obj.tools:
  6230. obj_init.tools = deepcopy(obj.tools)
  6231. except Exception as ee:
  6232. log.debug("on_copy_object2() --> %s" % str(ee))
  6233. def initialize_gerber(obj_init, app):
  6234. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6235. obj_init.apertures = deepcopy(obj.apertures)
  6236. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6237. def initialize_excellon(obj_init, app):
  6238. obj_init.tools = deepcopy(obj.tools)
  6239. # drills are offset, so they need to be deep copied
  6240. obj_init.drills = deepcopy(obj.drills)
  6241. # slots are offset, so they need to be deep copied
  6242. obj_init.slots = deepcopy(obj.slots)
  6243. obj_init.create_geometry()
  6244. for obj in self.collection.get_selected():
  6245. obj_name = obj.options["name"]
  6246. try:
  6247. if isinstance(obj, FlatCAMExcellon):
  6248. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6249. elif isinstance(obj, FlatCAMGerber):
  6250. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6251. elif isinstance(obj, FlatCAMGeometry):
  6252. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6253. except Exception as e:
  6254. return "Operation failed: %s" % str(e)
  6255. def on_rename_object(self, text):
  6256. self.report_usage("on_rename_object()")
  6257. named_obj = self.collection.get_active()
  6258. for obj in named_obj:
  6259. if obj is list:
  6260. self.on_rename_object(text)
  6261. else:
  6262. try:
  6263. obj.options['name'] = text
  6264. except Exception as e:
  6265. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6266. def convert_any2geo(self):
  6267. self.report_usage("convert_any2geo()")
  6268. def initialize(obj_init, app):
  6269. obj_init.solid_geometry = obj.solid_geometry
  6270. try:
  6271. obj_init.follow_geometry = obj.follow_geometry
  6272. except AttributeError:
  6273. pass
  6274. try:
  6275. obj_init.apertures = obj.apertures
  6276. except AttributeError:
  6277. pass
  6278. try:
  6279. if obj.tools:
  6280. obj_init.tools = obj.tools
  6281. except AttributeError:
  6282. pass
  6283. def initialize_excellon(obj_init, app):
  6284. # objs = self.collection.get_selected()
  6285. # FlatCAMGeometry.merge(objs, obj)
  6286. solid_geo = []
  6287. for tool in obj.tools:
  6288. for geo in obj.tools[tool]['solid_geometry']:
  6289. solid_geo.append(geo)
  6290. obj_init.solid_geometry = deepcopy(solid_geo)
  6291. if not self.collection.get_selected():
  6292. log.warning("App.convert_any2geo --> No object selected")
  6293. self.inform.emit('[WARNING_NOTCL] %s' %
  6294. _("No object is selected. Select an object and try again."))
  6295. return
  6296. for obj in self.collection.get_selected():
  6297. obj_name = obj.options["name"]
  6298. try:
  6299. if isinstance(obj, FlatCAMExcellon):
  6300. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6301. else:
  6302. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6303. except Exception as e:
  6304. return "Operation failed: %s" % str(e)
  6305. def convert_any2gerber(self):
  6306. self.report_usage("convert_any2gerber()")
  6307. def initialize_geometry(obj_init, app):
  6308. apertures = {}
  6309. apid = 0
  6310. apertures[str(apid)] = {}
  6311. apertures[str(apid)]['geometry'] = []
  6312. for obj_orig in obj.solid_geometry:
  6313. new_elem = dict()
  6314. new_elem['solid'] = obj_orig
  6315. try:
  6316. new_elem['follow'] = obj_orig.exterior
  6317. except AttributeError:
  6318. pass
  6319. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6320. apertures[str(apid)]['size'] = 0.0
  6321. apertures[str(apid)]['type'] = 'C'
  6322. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6323. obj_init.apertures = deepcopy(apertures)
  6324. def initialize_excellon(obj_init, app):
  6325. apertures = {}
  6326. apid = 10
  6327. for tool in obj.tools:
  6328. apertures[str(apid)] = {}
  6329. apertures[str(apid)]['geometry'] = []
  6330. for geo in obj.tools[tool]['solid_geometry']:
  6331. new_el = dict()
  6332. new_el['solid'] = geo
  6333. new_el['follow'] = geo.exterior
  6334. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6335. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6336. apertures[str(apid)]['type'] = 'C'
  6337. apid += 1
  6338. # create solid_geometry
  6339. solid_geometry = []
  6340. for apid in apertures:
  6341. for geo_el in apertures[apid]['geometry']:
  6342. solid_geometry.append(geo_el['solid'])
  6343. solid_geometry = MultiPolygon(solid_geometry)
  6344. solid_geometry = solid_geometry.buffer(0.0000001)
  6345. obj_init.solid_geometry = deepcopy(solid_geometry)
  6346. obj_init.apertures = deepcopy(apertures)
  6347. # clear the working objects (perhaps not necessary due of Python GC)
  6348. apertures.clear()
  6349. if not self.collection.get_selected():
  6350. log.warning("App.convert_any2gerber --> No object selected")
  6351. self.inform.emit('[WARNING_NOTCL] %s' %
  6352. _("No object is selected. Select an object and try again."))
  6353. return
  6354. for obj in self.collection.get_selected():
  6355. obj_name = obj.options["name"]
  6356. try:
  6357. if isinstance(obj, FlatCAMExcellon):
  6358. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6359. elif isinstance(obj, FlatCAMGeometry):
  6360. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6361. else:
  6362. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6363. except Exception as e:
  6364. return "Operation failed: %s" % str(e)
  6365. def abort_all_tasks(self):
  6366. if self.abort_flag is False:
  6367. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6368. self.abort_flag = True
  6369. def app_is_idle(self):
  6370. if self.abort_flag:
  6371. self.inform.emit('[WARNING_NOTCL] %s' %
  6372. _("The current task was gracefully closed on user request..."))
  6373. self.abort_flag = False
  6374. def on_selectall(self):
  6375. self.report_usage("on_selectall()")
  6376. # delete the possible selection box around a possible selected object
  6377. self.delete_selection_shape()
  6378. for name in self.collection.get_names():
  6379. self.collection.set_active(name)
  6380. curr_sel_obj = self.collection.get_by_name(name)
  6381. # create the selection box around the selected object
  6382. if self.defaults['global_selection_shape'] is True:
  6383. self.draw_selection_shape(curr_sel_obj)
  6384. def on_preferences(self):
  6385. """
  6386. Adds the Preferences in a Tab in Plot Area
  6387. :return:
  6388. """
  6389. # add the tab if it was closed
  6390. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6391. # delete the absolute and relative position and messages in the infobar
  6392. self.ui.position_label.setText("")
  6393. self.ui.rel_position_label.setText("")
  6394. # Switch plot_area to preferences page
  6395. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6396. # self.ui.show()
  6397. # detect changes in the preferences
  6398. for idx in range(self.ui.pref_tab_area.count()):
  6399. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6400. try:
  6401. try:
  6402. tb.textEdited.disconnect(self.on_preferences_edited)
  6403. except (TypeError, AttributeError):
  6404. pass
  6405. tb.textEdited.connect(self.on_preferences_edited)
  6406. except AttributeError:
  6407. pass
  6408. try:
  6409. try:
  6410. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6411. except (TypeError, AttributeError):
  6412. pass
  6413. tb.modificationChanged.connect(self.on_preferences_edited)
  6414. except AttributeError:
  6415. pass
  6416. try:
  6417. try:
  6418. tb.toggled.disconnect(self.on_preferences_edited)
  6419. except (TypeError, AttributeError):
  6420. pass
  6421. tb.toggled.connect(self.on_preferences_edited)
  6422. except AttributeError:
  6423. pass
  6424. try:
  6425. try:
  6426. tb.valueChanged.disconnect(self.on_preferences_edited)
  6427. except (TypeError, AttributeError):
  6428. pass
  6429. tb.valueChanged.connect(self.on_preferences_edited)
  6430. except AttributeError:
  6431. pass
  6432. try:
  6433. try:
  6434. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6435. except (TypeError, AttributeError):
  6436. pass
  6437. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6438. except AttributeError:
  6439. pass
  6440. def on_preferences_edited(self):
  6441. self.inform.emit('[WARNING_NOTCL] %s' %
  6442. _("Preferences edited but not saved."))
  6443. for idx in range(self.ui.plot_tab_area.count()):
  6444. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  6445. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6446. self.preferences_changed_flag = True
  6447. def on_tools_database(self):
  6448. """
  6449. Adds the Tools Database in a Tab in Plot Area
  6450. :return:
  6451. """
  6452. for idx in range(self.ui.plot_tab_area.count()):
  6453. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6454. # there can be only one instance of Tools Database at one time
  6455. return
  6456. self.tools_db_tab = ToolsDB(
  6457. app=self,
  6458. parent=self.ui,
  6459. callback_on_edited=self.on_tools_db_edited,
  6460. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  6461. )
  6462. # add the tab if it was closed
  6463. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  6464. self.tools_db_tab.setObjectName("database_tab")
  6465. # delete the absolute and relative position and messages in the infobar
  6466. self.ui.position_label.setText("")
  6467. self.ui.rel_position_label.setText("")
  6468. # Switch plot_area to preferences page
  6469. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  6470. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  6471. self.tools_db_tab.ui_connect()
  6472. def on_tools_db_edited(self):
  6473. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  6474. for idx in range(self.ui.plot_tab_area.count()):
  6475. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6476. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6477. self.tools_db_changed_flag = True
  6478. def on_geometry_tool_add_from_db_executed(self, tool):
  6479. """
  6480. Here add the tool from DB in the selected geometry object
  6481. :return:
  6482. """
  6483. tool_from_db = deepcopy(tool)
  6484. obj = self.collection.get_active()
  6485. if isinstance(obj, FlatCAMGeometry):
  6486. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6487. for idx in range(self.ui.plot_tab_area.count()):
  6488. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6489. wdg = self.ui.plot_tab_area.widget(idx)
  6490. wdg.deleteLater()
  6491. self.ui.plot_tab_area.removeTab(idx)
  6492. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6493. else:
  6494. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6495. def on_plot_area_tab_closed(self, title):
  6496. if title == _("Preferences"):
  6497. # disconnect
  6498. for idx in range(self.ui.pref_tab_area.count()):
  6499. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6500. try:
  6501. tb.textEdited.disconnect(self.on_preferences_edited)
  6502. except (TypeError, AttributeError):
  6503. pass
  6504. try:
  6505. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6506. except (TypeError, AttributeError):
  6507. pass
  6508. try:
  6509. tb.toggled.disconnect(self.on_preferences_edited)
  6510. except (TypeError, AttributeError):
  6511. pass
  6512. try:
  6513. tb.valueChanged.disconnect(self.on_preferences_edited)
  6514. except (TypeError, AttributeError):
  6515. pass
  6516. try:
  6517. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6518. except (TypeError, AttributeError):
  6519. pass
  6520. if self.preferences_changed_flag is True:
  6521. msgbox = QtWidgets.QMessageBox()
  6522. msgbox.setText(_("One or more values are changed.\n"
  6523. "Do you want to save the Preferences?"))
  6524. msgbox.setWindowTitle(_("Save Preferences"))
  6525. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6526. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6527. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6528. msgbox.setDefaultButton(bt_yes)
  6529. msgbox.exec_()
  6530. response = msgbox.clickedButton()
  6531. if response == bt_yes:
  6532. self.on_save_button(save_to_file=True)
  6533. self.inform.emit('[success] %s' % _("Preferences saved."))
  6534. else:
  6535. self.preferences_changed_flag = False
  6536. self.inform.emit('')
  6537. return
  6538. if title == _("Tools Database"):
  6539. # disconnect the signals from the table widget in tab
  6540. self.tools_db_tab.ui_disconnect()
  6541. if self.tools_db_changed_flag is True:
  6542. msgbox = QtWidgets.QMessageBox()
  6543. msgbox.setText(_("One or more Tools are edited.\n"
  6544. "Do you want to update the Tools Database?"))
  6545. msgbox.setWindowTitle(_("Save Tools Database"))
  6546. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6547. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6548. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6549. msgbox.setDefaultButton(bt_yes)
  6550. msgbox.exec_()
  6551. response = msgbox.clickedButton()
  6552. if response == bt_yes:
  6553. self.tools_db_tab.on_save_tools_db()
  6554. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6555. else:
  6556. self.tools_db_changed_flag = False
  6557. self.inform.emit('')
  6558. return
  6559. self.tools_db_tab.deleteLater()
  6560. if title == _("Code Editor"):
  6561. self.toggle_codeeditor = False
  6562. if title == _("Bookmarks Manager"):
  6563. self.book_dialog_tab.rebuild_actions()
  6564. self.book_dialog_tab.deleteLater()
  6565. def on_flipy(self):
  6566. self.report_usage("on_flipy()")
  6567. obj_list = self.collection.get_selected()
  6568. xminlist = []
  6569. yminlist = []
  6570. xmaxlist = []
  6571. ymaxlist = []
  6572. if not obj_list:
  6573. self.inform.emit('[WARNING_NOTCL] %s' %
  6574. _("No object selected to Flip on Y axis."))
  6575. else:
  6576. try:
  6577. # first get a bounding box to fit all
  6578. for obj in obj_list:
  6579. xmin, ymin, xmax, ymax = obj.bounds()
  6580. xminlist.append(xmin)
  6581. yminlist.append(ymin)
  6582. xmaxlist.append(xmax)
  6583. ymaxlist.append(ymax)
  6584. # get the minimum x,y and maximum x,y for all objects selected
  6585. xminimal = min(xminlist)
  6586. yminimal = min(yminlist)
  6587. xmaximal = max(xmaxlist)
  6588. ymaximal = max(ymaxlist)
  6589. px = 0.5 * (xminimal + xmaximal)
  6590. py = 0.5 * (yminimal + ymaximal)
  6591. # execute mirroring
  6592. for obj in obj_list:
  6593. obj.mirror('X', [px, py])
  6594. obj.plot()
  6595. self.object_changed.emit(obj)
  6596. self.inform.emit('[success] %s' %
  6597. _("Flip on Y axis done."))
  6598. except Exception as e:
  6599. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6600. return
  6601. def on_flipx(self):
  6602. self.report_usage("on_flipx()")
  6603. obj_list = self.collection.get_selected()
  6604. xminlist = []
  6605. yminlist = []
  6606. xmaxlist = []
  6607. ymaxlist = []
  6608. if not obj_list:
  6609. self.inform.emit('[WARNING_NOTCL] %s' %
  6610. _("No object selected to Flip on X axis."))
  6611. else:
  6612. try:
  6613. # first get a bounding box to fit all
  6614. for obj in obj_list:
  6615. xmin, ymin, xmax, ymax = obj.bounds()
  6616. xminlist.append(xmin)
  6617. yminlist.append(ymin)
  6618. xmaxlist.append(xmax)
  6619. ymaxlist.append(ymax)
  6620. # get the minimum x,y and maximum x,y for all objects selected
  6621. xminimal = min(xminlist)
  6622. yminimal = min(yminlist)
  6623. xmaximal = max(xmaxlist)
  6624. ymaximal = max(ymaxlist)
  6625. px = 0.5 * (xminimal + xmaximal)
  6626. py = 0.5 * (yminimal + ymaximal)
  6627. # execute mirroring
  6628. for obj in obj_list:
  6629. obj.mirror('Y', [px, py])
  6630. obj.plot()
  6631. self.object_changed.emit(obj)
  6632. self.inform.emit('[success] %s' %
  6633. _("Flip on X axis done."))
  6634. except Exception as e:
  6635. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6636. return
  6637. def on_rotate(self, silent=False, preset=None):
  6638. self.report_usage("on_rotate()")
  6639. obj_list = self.collection.get_selected()
  6640. xminlist = []
  6641. yminlist = []
  6642. xmaxlist = []
  6643. ymaxlist = []
  6644. if not obj_list:
  6645. self.inform.emit('[WARNING_NOTCL] %s' %
  6646. _("No object selected to Rotate."))
  6647. else:
  6648. if silent is False:
  6649. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6650. min=-360, max=360, decimals=4,
  6651. init_val=float(self.defaults['tools_transform_rotate']))
  6652. num, ok = rotatebox.get_value()
  6653. else:
  6654. num = preset
  6655. ok = True
  6656. if ok:
  6657. try:
  6658. # first get a bounding box to fit all
  6659. for obj in obj_list:
  6660. xmin, ymin, xmax, ymax = obj.bounds()
  6661. xminlist.append(xmin)
  6662. yminlist.append(ymin)
  6663. xmaxlist.append(xmax)
  6664. ymaxlist.append(ymax)
  6665. # get the minimum x,y and maximum x,y for all objects selected
  6666. xminimal = min(xminlist)
  6667. yminimal = min(yminlist)
  6668. xmaximal = max(xmaxlist)
  6669. ymaximal = max(ymaxlist)
  6670. px = 0.5 * (xminimal + xmaximal)
  6671. py = 0.5 * (yminimal + ymaximal)
  6672. for sel_obj in obj_list:
  6673. sel_obj.rotate(-float(num), point=(px, py))
  6674. sel_obj.plot()
  6675. self.object_changed.emit(sel_obj)
  6676. self.inform.emit('[success] %s' %
  6677. _("Rotation done."))
  6678. except Exception as e:
  6679. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6680. return
  6681. def on_skewx(self):
  6682. self.report_usage("on_skewx()")
  6683. obj_list = self.collection.get_selected()
  6684. xminlist = []
  6685. yminlist = []
  6686. if not obj_list:
  6687. self.inform.emit('[WARNING_NOTCL] %s' %
  6688. _("No object selected to Skew/Shear on X axis."))
  6689. else:
  6690. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6691. min=-360, max=360, decimals=4,
  6692. init_val=float(self.defaults['tools_transform_skew_x']))
  6693. num, ok = skewxbox.get_value()
  6694. if ok:
  6695. # first get a bounding box to fit all
  6696. for obj in obj_list:
  6697. xmin, ymin, xmax, ymax = obj.bounds()
  6698. xminlist.append(xmin)
  6699. yminlist.append(ymin)
  6700. # get the minimum x,y and maximum x,y for all objects selected
  6701. xminimal = min(xminlist)
  6702. yminimal = min(yminlist)
  6703. for obj in obj_list:
  6704. obj.skew(num, 0, point=(xminimal, yminimal))
  6705. obj.plot()
  6706. self.object_changed.emit(obj)
  6707. self.inform.emit('[success] %s' %
  6708. _("Skew on X axis done."))
  6709. def on_skewy(self):
  6710. self.report_usage("on_skewy()")
  6711. obj_list = self.collection.get_selected()
  6712. xminlist = []
  6713. yminlist = []
  6714. if not obj_list:
  6715. self.inform.emit('[WARNING_NOTCL] %s' %
  6716. _("No object selected to Skew/Shear on Y axis."))
  6717. else:
  6718. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6719. min=-360, max=360, decimals=4,
  6720. init_val=float(self.defaults['tools_transform_skew_y']))
  6721. num, ok = skewybox.get_value()
  6722. if ok:
  6723. # first get a bounding box to fit all
  6724. for obj in obj_list:
  6725. xmin, ymin, xmax, ymax = obj.bounds()
  6726. xminlist.append(xmin)
  6727. yminlist.append(ymin)
  6728. # get the minimum x,y and maximum x,y for all objects selected
  6729. xminimal = min(xminlist)
  6730. yminimal = min(yminlist)
  6731. for obj in obj_list:
  6732. obj.skew(0, num, point=(xminimal, yminimal))
  6733. obj.plot()
  6734. self.object_changed.emit(obj)
  6735. self.inform.emit('[success] %s' %
  6736. _("Skew on Y axis done."))
  6737. def on_plots_updated(self):
  6738. """
  6739. Callback used to report when the plots have changed.
  6740. Adjust axes and zooms to fit.
  6741. :return: None
  6742. """
  6743. if self.is_legacy is False:
  6744. self.plotcanvas.update() # TODO: Need update canvas?
  6745. else:
  6746. self.plotcanvas.auto_adjust_axes()
  6747. self.on_zoom_fit(None)
  6748. self.collection.update_view()
  6749. # self.inform.emit(_("Plots updated ..."))
  6750. # TODO: Rework toolbar 'clear', 'replot' functions
  6751. def on_toolbar_replot(self):
  6752. """
  6753. Callback for toolbar button. Re-plots all objects.
  6754. :return: None
  6755. """
  6756. self.report_usage("on_toolbar_replot")
  6757. self.log.debug("on_toolbar_replot()")
  6758. try:
  6759. self.collection.get_active().read_form()
  6760. except AttributeError:
  6761. self.log.debug("on_toolbar_replot(): AttributeError")
  6762. pass
  6763. self.plot_all()
  6764. def on_row_activated(self, index):
  6765. if index.isValid():
  6766. if index.internalPointer().parent_item != self.collection.root_item:
  6767. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6768. self.collection.on_item_activated(index)
  6769. def on_row_selected(self, obj_name):
  6770. # this is a special string; when received it will make all entries unchecked
  6771. # it mean we clicked outside of the items and deselected all
  6772. if obj_name == 'none':
  6773. for act in self.ui.menuobjects.actions():
  6774. act.setChecked(False)
  6775. return
  6776. # get the name of the selected objects and add them to a list
  6777. name_list = list()
  6778. for obj in self.collection.get_selected():
  6779. name_list.append(obj.options['name'])
  6780. # set all actions as unchecked but the ones selected make them checked
  6781. for act in self.ui.menuobjects.actions():
  6782. act.setChecked(False)
  6783. if act.text() in name_list:
  6784. act.setChecked(True)
  6785. def on_collection_updated(self, obj, state, old_name):
  6786. """
  6787. Create a menu from the object loaded in the collection.
  6788. TODO: should use the collection model to do this
  6789. :param obj: object that was changd (added, deleted, renamed)
  6790. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6791. :param old_name: the old name of the object before the action that triggered this slot happened
  6792. :return: None
  6793. """
  6794. icon_files = {
  6795. "gerber": "share/flatcam_icon16.png",
  6796. "excellon": "share/drill16.png",
  6797. "cncjob": "share/cnc16.png",
  6798. "geometry": "share/geometry16.png",
  6799. "script": "share/script_new16.png",
  6800. "document": "share/notes16_1.png"
  6801. }
  6802. if state == 'append':
  6803. for act in self.ui.menuobjects.actions():
  6804. try:
  6805. act.triggered.disconnect()
  6806. except TypeError:
  6807. pass
  6808. self.ui.menuobjects.clear()
  6809. gerber_list = list()
  6810. exc_list = list()
  6811. cncjob_list = list()
  6812. geo_list = list()
  6813. script_list = list()
  6814. doc_list = list()
  6815. for name in self.collection.get_names():
  6816. obj_named = self.collection.get_by_name(name)
  6817. if obj_named.kind == 'gerber':
  6818. gerber_list.append(name)
  6819. elif obj_named.kind == 'excellon':
  6820. exc_list.append(name)
  6821. elif obj_named.kind == 'cncjob':
  6822. cncjob_list.append(name)
  6823. elif obj_named.kind == 'geometry':
  6824. geo_list.append(name)
  6825. elif obj_named.kind == 'script':
  6826. script_list.append(name)
  6827. elif obj_named.kind == 'document':
  6828. doc_list.append(name)
  6829. def add_act(o_name):
  6830. obj_for_icon = self.collection.get_by_name(o_name)
  6831. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6832. add_action.setCheckable(True)
  6833. add_action.setText(o_name)
  6834. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6835. add_action.triggered.connect(
  6836. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  6837. self.collection.set_inactive(o_name))
  6838. self.ui.menuobjects.addAction(add_action)
  6839. for name in gerber_list:
  6840. add_act(name)
  6841. self.ui.menuobjects.addSeparator()
  6842. for name in exc_list:
  6843. add_act(name)
  6844. self.ui.menuobjects.addSeparator()
  6845. for name in cncjob_list:
  6846. add_act(name)
  6847. self.ui.menuobjects.addSeparator()
  6848. for name in geo_list:
  6849. add_act(name)
  6850. self.ui.menuobjects.addSeparator()
  6851. for name in script_list:
  6852. add_act(name)
  6853. self.ui.menuobjects.addSeparator()
  6854. for name in doc_list:
  6855. add_act(name)
  6856. self.ui.menuobjects.addSeparator()
  6857. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6858. QtGui.QIcon('share/select_all.png'),
  6859. _('Select All')
  6860. )
  6861. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6862. QtGui.QIcon('share/deselect_all32.png'),
  6863. _('Deselect All')
  6864. )
  6865. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6866. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6867. elif state == 'delete':
  6868. for act in self.ui.menuobjects.actions():
  6869. if act.text() == obj.options['name']:
  6870. try:
  6871. act.triggered.disconnect()
  6872. except TypeError:
  6873. pass
  6874. self.ui.menuobjects.removeAction(act)
  6875. break
  6876. elif state == 'rename':
  6877. for act in self.ui.menuobjects.actions():
  6878. if act.text() == old_name:
  6879. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6880. add_action.setText(obj.options['name'])
  6881. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6882. add_action.triggered.connect(
  6883. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  6884. self.collection.set_inactive(obj.options['name']))
  6885. self.ui.menuobjects.insertAction(act, add_action)
  6886. try:
  6887. act.triggered.disconnect()
  6888. except TypeError:
  6889. pass
  6890. self.ui.menuobjects.removeAction(act)
  6891. break
  6892. elif state == 'delete_all':
  6893. for act in self.ui.menuobjects.actions():
  6894. try:
  6895. act.triggered.disconnect()
  6896. except TypeError:
  6897. pass
  6898. self.ui.menuobjects.clear()
  6899. self.ui.menuobjects.addSeparator()
  6900. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6901. QtGui.QIcon('share/select_all.png'),
  6902. _('Select All')
  6903. )
  6904. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6905. QtGui.QIcon('share/deselect_all32.png'),
  6906. _('Deselect All')
  6907. )
  6908. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6909. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6910. def on_objects_selection(self, on_off):
  6911. obj_list = self.collection.get_names()
  6912. if on_off is True:
  6913. self.collection.set_all_active()
  6914. for act in self.ui.menuobjects.actions():
  6915. try:
  6916. act.setChecked(True)
  6917. except Exception:
  6918. pass
  6919. if obj_list:
  6920. self.inform.emit('[selected] %s' % _("All objects are selected."))
  6921. else:
  6922. self.collection.set_all_inactive()
  6923. for act in self.ui.menuobjects.actions():
  6924. try:
  6925. act.setChecked(False)
  6926. except Exception:
  6927. pass
  6928. if obj_list:
  6929. self.inform.emit('%s' % _("Objects selection is cleared."))
  6930. else:
  6931. self.inform.emit('')
  6932. def grid_status(self):
  6933. if self.ui.grid_snap_btn.isChecked():
  6934. return True
  6935. else:
  6936. return False
  6937. def populate_cmenu_grids(self):
  6938. units = self.defaults['units'].lower()
  6939. self.ui.cmenu_gridmenu.clear()
  6940. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6941. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6942. grid_toggle.setCheckable(True)
  6943. if self.grid_status() == True:
  6944. grid_toggle.setChecked(True)
  6945. else:
  6946. grid_toggle.setChecked(False)
  6947. self.ui.cmenu_gridmenu.addSeparator()
  6948. for grid in sorted_list:
  6949. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6950. action.triggered.connect(self.set_grid)
  6951. self.ui.cmenu_gridmenu.addSeparator()
  6952. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6953. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6954. grid_add.triggered.connect(self.on_grid_add)
  6955. grid_delete.triggered.connect(self.on_grid_delete)
  6956. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6957. def set_grid(self):
  6958. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6959. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6960. def on_grid_add(self):
  6961. # ## Current application units in lower Case
  6962. units = self.defaults['units'].lower()
  6963. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6964. text=_('Enter a Grid Value:'),
  6965. min=0.0000, max=99.9999, decimals=4)
  6966. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6967. val, ok = grid_add_popup.get_value()
  6968. if ok:
  6969. if float(val) == 0:
  6970. self.inform.emit('[WARNING_NOTCL] %s' %
  6971. _("Please enter a grid value with non-zero value, in Float format."))
  6972. return
  6973. else:
  6974. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6975. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6976. self.inform.emit('[success] %s...' %
  6977. _("New Grid added"))
  6978. else:
  6979. self.inform.emit('[WARNING_NOTCL] %s...' %
  6980. _("Grid already exists"))
  6981. else:
  6982. self.inform.emit('[WARNING_NOTCL] %s...' %
  6983. _("Adding New Grid cancelled"))
  6984. def on_grid_delete(self):
  6985. # ## Current application units in lower Case
  6986. units = self.defaults['units'].lower()
  6987. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6988. text='Enter a Grid Value:',
  6989. min=0.0000, max=99.9999, decimals=4)
  6990. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6991. val, ok = grid_del_popup.get_value()
  6992. if ok:
  6993. if float(val) == 0:
  6994. self.inform.emit('[WARNING_NOTCL] %s' %
  6995. _("Please enter a grid value with non-zero value, in Float format."))
  6996. return
  6997. else:
  6998. try:
  6999. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  7000. except ValueError:
  7001. self.inform.emit('[ERROR_NOTCL]%s...' %
  7002. _(" Grid Value does not exist"))
  7003. return
  7004. self.inform.emit('[success] %s...' %
  7005. _("Grid Value deleted"))
  7006. else:
  7007. self.inform.emit('[WARNING_NOTCL] %s...' %
  7008. _("Delete Grid value cancelled"))
  7009. def on_shortcut_list(self):
  7010. self.report_usage("on_shortcut_list()")
  7011. # add the tab if it was closed
  7012. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  7013. # delete the absolute and relative position and messages in the infobar
  7014. self.ui.position_label.setText("")
  7015. self.ui.rel_position_label.setText("")
  7016. # Switch plot_area to preferences page
  7017. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  7018. # self.ui.show()
  7019. def on_select_tab(self, name):
  7020. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  7021. if self.ui.splitter.sizes()[0] == 0:
  7022. self.ui.splitter.setSizes([1, 1])
  7023. else:
  7024. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  7025. self.ui.splitter.setSizes([0, 1])
  7026. if name == 'project':
  7027. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7028. elif name == 'selected':
  7029. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7030. elif name == 'tool':
  7031. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  7032. def on_copy_name(self):
  7033. self.report_usage("on_copy_name()")
  7034. obj = self.collection.get_active()
  7035. try:
  7036. name = obj.options["name"]
  7037. except AttributeError:
  7038. log.debug("on_copy_name() --> No object selected to copy it's name")
  7039. self.inform.emit('[WARNING_NOTCL]%s' %
  7040. _(" No object selected to copy it's name"))
  7041. return
  7042. self.clipboard.setText(name)
  7043. self.inform.emit(_("Name copied on clipboard ..."))
  7044. def on_mouse_click_over_plot(self, event):
  7045. """
  7046. Default actions are:
  7047. :param event: Contains information about the event, like which button
  7048. was clicked, the pixel coordinates and the axes coordinates.
  7049. :return: None
  7050. """
  7051. self.pos = []
  7052. if self.is_legacy is False:
  7053. event_pos = event.pos
  7054. if self.defaults["global_pan_button"] == '2':
  7055. pan_button = 2
  7056. else:
  7057. pan_button = 3
  7058. # Set the mouse button for panning
  7059. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7060. else:
  7061. event_pos = (event.xdata, event.ydata)
  7062. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7063. if self.defaults["global_pan_button"] == '2':
  7064. pan_button = 3
  7065. else:
  7066. pan_button = 2
  7067. # So it can receive key presses
  7068. self.plotcanvas.native.setFocus()
  7069. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7070. if self.grid_status() == True:
  7071. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  7072. else:
  7073. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  7074. try:
  7075. if event.button == 1:
  7076. # Reset here the relative coordinates so there is a new reference on the click position
  7077. if self.rel_point1 is None:
  7078. self.rel_point1 = self.pos
  7079. else:
  7080. self.rel_point2 = copy(self.rel_point1)
  7081. self.rel_point1 = self.pos
  7082. self.on_mouse_move_over_plot(event, origin_click=True)
  7083. except Exception as e:
  7084. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  7085. def on_mouse_double_click_over_plot(self, event):
  7086. if event.button == 1:
  7087. self.doubleclick = True
  7088. def on_mouse_move_over_plot(self, event, origin_click=None):
  7089. """
  7090. Callback for the mouse motion event over the plot.
  7091. :param event: Contains information about the event.
  7092. :param origin_click
  7093. :return: None
  7094. """
  7095. if self.is_legacy is False:
  7096. event_pos = event.pos
  7097. if self.defaults["global_pan_button"] == '2':
  7098. pan_button = 2
  7099. else:
  7100. pan_button = 3
  7101. self.event_is_dragging = event.is_dragging
  7102. else:
  7103. event_pos = (event.xdata, event.ydata)
  7104. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7105. if self.defaults["global_pan_button"] == '2':
  7106. pan_button = 3
  7107. else:
  7108. pan_button = 2
  7109. self.event_is_dragging = self.plotcanvas.is_dragging
  7110. # So it can receive key presses
  7111. self.plotcanvas.native.setFocus()
  7112. self.pos_jump = event_pos
  7113. self.ui.popMenu.mouse_is_panning = False
  7114. if not origin_click:
  7115. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7116. if event.button == pan_button and self.event_is_dragging == 1:
  7117. self.ui.popMenu.mouse_is_panning = True
  7118. return
  7119. if self.rel_point1 is not None:
  7120. try: # May fail in case mouse not within axes
  7121. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7122. if self.grid_status() == True:
  7123. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7124. # Update cursor
  7125. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7126. symbol='++', edge_color=self.cursor_color_3D,
  7127. size=self.defaults["global_cursor_size"])
  7128. else:
  7129. pos = (pos_canvas[0], pos_canvas[1])
  7130. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7131. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7132. dx = pos[0] - float(self.rel_point1[0])
  7133. dy = pos[1] - float(self.rel_point1[1])
  7134. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7135. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  7136. self.mouse = [pos[0], pos[1]]
  7137. # if the mouse is moved and the LMB is clicked then the action is a selection
  7138. if self.event_is_dragging == 1 and event.button == 1:
  7139. self.delete_selection_shape()
  7140. if dx < 0:
  7141. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7142. face_color=self.defaults['global_alt_sel_fill'])
  7143. self.selection_type = False
  7144. elif dx > 0:
  7145. self.draw_moving_selection_shape(self.pos, pos)
  7146. self.selection_type = True
  7147. else:
  7148. self.selection_type = None
  7149. # hover effect - enabled in Preferences -> General -> GUI Settings
  7150. if self.defaults['global_hover']:
  7151. for obj in self.collection.get_list():
  7152. try:
  7153. # select the object(s) only if it is enabled (plotted)
  7154. if obj.options['plot']:
  7155. if obj not in self.collection.get_selected():
  7156. poly_obj = Polygon(
  7157. [(obj.options['xmin'], obj.options['ymin']),
  7158. (obj.options['xmax'], obj.options['ymin']),
  7159. (obj.options['xmax'], obj.options['ymax']),
  7160. (obj.options['xmin'], obj.options['ymax'])]
  7161. )
  7162. if Point(pos).within(poly_obj):
  7163. if obj.isHovering is False:
  7164. obj.isHovering = True
  7165. obj.notHovering = True
  7166. # create the selection box around the selected object
  7167. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7168. else:
  7169. if obj.notHovering is True:
  7170. obj.notHovering = False
  7171. obj.isHovering = False
  7172. self.delete_hover_shape()
  7173. except Exception:
  7174. # the Exception here will happen if we try to select on screen and we have an
  7175. # newly (and empty) just created Geometry or Excellon object that do not have the
  7176. # xmin, xmax, ymin, ymax options.
  7177. # In this case poly_obj creation (see above) will fail
  7178. pass
  7179. except Exception:
  7180. self.ui.position_label.setText("")
  7181. self.ui.rel_position_label.setText("")
  7182. self.mouse = None
  7183. def on_mouse_click_release_over_plot(self, event):
  7184. """
  7185. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7186. and has been registered in ''self.__init__()''.
  7187. :param event: contains information about the event.
  7188. :return:
  7189. """
  7190. if self.is_legacy is False:
  7191. event_pos = event.pos
  7192. right_button = 2
  7193. else:
  7194. event_pos = (event.xdata, event.ydata)
  7195. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7196. right_button = 3
  7197. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7198. if self.grid_status() == True:
  7199. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7200. else:
  7201. pos = (pos_canvas[0], pos_canvas[1])
  7202. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7203. # canvas menu
  7204. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  7205. self.cursor = QtGui.QCursor()
  7206. self.populate_cmenu_grids()
  7207. self.ui.popMenu.popup(self.cursor.pos())
  7208. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7209. # selection and then select a type of selection ("enclosing" or "touching")
  7210. if event.button == 1: # left click
  7211. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7212. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7213. if modifiers == QtCore.Qt.ShiftModifier:
  7214. # do not auto open the Project Tab
  7215. self.click_noproject = True
  7216. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  7217. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  7218. return
  7219. if self.doubleclick is True:
  7220. self.doubleclick = False
  7221. if self.collection.get_selected():
  7222. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7223. if self.ui.splitter.sizes()[0] == 0:
  7224. self.ui.splitter.setSizes([1, 1])
  7225. try:
  7226. # delete the selection shape(S) as it may be in the way
  7227. self.delete_selection_shape()
  7228. self.delete_hover_shape()
  7229. except Exception as e:
  7230. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  7231. return
  7232. else:
  7233. if self.selection_type is not None:
  7234. try:
  7235. self.selection_area_handler(self.pos, pos, self.selection_type)
  7236. self.selection_type = None
  7237. except Exception as e:
  7238. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  7239. return
  7240. else:
  7241. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7242. if key_modifier == QtCore.Qt.ShiftModifier:
  7243. mod_key = 'Shift'
  7244. elif key_modifier == QtCore.Qt.ControlModifier:
  7245. mod_key = 'Control'
  7246. else:
  7247. mod_key = None
  7248. try:
  7249. if mod_key == self.defaults["global_mselect_key"]:
  7250. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7251. # deselect, and if it's not selected then it will be selected
  7252. # If there is no active command (self.command_active is None) then we check if we clicked
  7253. # on a object by checking the bounding limits against mouse click position
  7254. if self.command_active is None:
  7255. self.select_objects(key='CTRL')
  7256. self.delete_hover_shape()
  7257. else:
  7258. # If there is no active command (self.command_active is None) then we check if we clicked
  7259. # on a object by checking the bounding limits against mouse click position
  7260. if self.command_active is None:
  7261. self.select_objects()
  7262. self.delete_hover_shape()
  7263. except Exception as e:
  7264. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  7265. return
  7266. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7267. """
  7268. :param start_pos: mouse position when the selection LMB click was done
  7269. :param end_pos: mouse position when the left mouse button is released
  7270. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7271. :return:
  7272. """
  7273. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7274. # delete previous selection shape
  7275. self.delete_selection_shape()
  7276. # make all objects inactive
  7277. self.collection.set_all_inactive()
  7278. for obj in self.collection.get_list():
  7279. try:
  7280. # select the object(s) only if it is enabled (plotted)
  7281. if obj.options['plot']:
  7282. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7283. (obj.options['xmax'], obj.options['ymin']),
  7284. (obj.options['xmax'], obj.options['ymax']),
  7285. (obj.options['xmin'], obj.options['ymax'])])
  7286. if sel_type is True:
  7287. if poly_obj.within(poly_selection):
  7288. # create the selection box around the selected object
  7289. if self.defaults['global_selection_shape'] is True:
  7290. self.draw_selection_shape(obj)
  7291. self.collection.set_active(obj.options['name'])
  7292. else:
  7293. if poly_selection.intersects(poly_obj):
  7294. # create the selection box around the selected object
  7295. if self.defaults['global_selection_shape'] is True:
  7296. self.draw_selection_shape(obj)
  7297. self.collection.set_active(obj.options['name'])
  7298. except Exception as e:
  7299. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7300. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7301. # In this case poly_obj creation (see above) will fail
  7302. log.debug("App.selection_area_handler() --> %s" % str(e))
  7303. def select_objects(self, key=None):
  7304. """
  7305. Will select objects clicked on canvas
  7306. :param key: for future use in cumulative selection
  7307. :return:
  7308. """
  7309. # list where we store the overlapped objects under our mouse left click position
  7310. objects_under_the_click_list = []
  7311. # Populate the list with the overlapped objects on the click position
  7312. curr_x, curr_y = self.pos
  7313. for obj in self.all_objects_list:
  7314. # FlatCAMScript and FlatCAMDocument objects can't be selected
  7315. if isinstance(obj, FlatCAMScript) or isinstance(obj, FlatCAMDocument):
  7316. continue
  7317. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7318. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7319. if obj.options['name'] not in objects_under_the_click_list:
  7320. if obj.options['plot']:
  7321. # add objects to the objects_under_the_click list only if the object is plotted
  7322. # (active and not disabled)
  7323. objects_under_the_click_list.append(obj.options['name'])
  7324. try:
  7325. if objects_under_the_click_list:
  7326. curr_sel_obj = self.collection.get_active()
  7327. # case when there is only an object under the click and we toggle it
  7328. if len(objects_under_the_click_list) == 1:
  7329. if curr_sel_obj is None:
  7330. self.collection.set_active(objects_under_the_click_list[0])
  7331. curr_sel_obj = self.collection.get_active()
  7332. # create the selection box around the selected object
  7333. if self.defaults['global_selection_shape'] is True:
  7334. self.draw_selection_shape(curr_sel_obj)
  7335. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  7336. self.on_objects_selection(False)
  7337. self.delete_selection_shape()
  7338. self.collection.set_active(objects_under_the_click_list[0])
  7339. curr_sel_obj = self.collection.get_active()
  7340. # create the selection box around the selected object
  7341. if self.defaults['global_selection_shape'] is True:
  7342. self.draw_selection_shape(curr_sel_obj)
  7343. self.selected_message(curr_sel_obj=curr_sel_obj)
  7344. else:
  7345. self.on_objects_selection(False)
  7346. self.delete_selection_shape()
  7347. if self.call_source != 'app':
  7348. self.call_source = 'app'
  7349. self.selected_message(curr_sel_obj=curr_sel_obj)
  7350. else:
  7351. # If there is no selected object
  7352. # make active the first element of the overlapped objects list
  7353. if self.collection.get_active() is None:
  7354. self.collection.set_active(objects_under_the_click_list[0])
  7355. name_sel_obj = self.collection.get_active().options['name']
  7356. # In case that there is a selected object but it is not in the overlapped object list
  7357. # make that object inactive and activate the first element in the overlapped object list
  7358. if name_sel_obj not in objects_under_the_click_list:
  7359. self.collection.set_inactive(name_sel_obj)
  7360. name_sel_obj = objects_under_the_click_list[0]
  7361. self.collection.set_active(name_sel_obj)
  7362. else:
  7363. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7364. self.collection.set_all_inactive()
  7365. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7366. len(objects_under_the_click_list)])
  7367. curr_sel_obj = self.collection.get_active()
  7368. # delete the possible selection box around a possible selected object
  7369. self.delete_selection_shape()
  7370. # create the selection box around the selected object
  7371. if self.defaults['global_selection_shape'] is True:
  7372. self.draw_selection_shape(curr_sel_obj)
  7373. self.selected_message(curr_sel_obj=curr_sel_obj)
  7374. else:
  7375. # deselect everything
  7376. self.on_objects_selection(False)
  7377. # delete the possible selection box around a possible selected object
  7378. self.delete_selection_shape()
  7379. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7380. # only when working on App
  7381. if self.call_source == 'app':
  7382. if self.click_noproject is False:
  7383. # if the Tool Tab is in focus don't change focus to Project Tab
  7384. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  7385. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7386. else:
  7387. # restore auto open the Project Tab
  7388. self.click_noproject = False
  7389. # delete any text in the status bar, implicitly the last object name that was selected
  7390. # self.inform.emit("")
  7391. else:
  7392. self.call_source = 'app'
  7393. except Exception as e:
  7394. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7395. def selected_message(self, curr_sel_obj):
  7396. if curr_sel_obj:
  7397. if curr_sel_obj.kind == 'gerber':
  7398. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7399. color='green', name=str(curr_sel_obj.options['name'])))
  7400. elif curr_sel_obj.kind == 'excellon':
  7401. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7402. color='brown', name=str(curr_sel_obj.options['name'])))
  7403. elif curr_sel_obj.kind == 'cncjob':
  7404. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7405. color='blue', name=str(curr_sel_obj.options['name'])))
  7406. elif curr_sel_obj.kind == 'geometry':
  7407. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7408. color='red', name=str(curr_sel_obj.options['name'])))
  7409. def delete_hover_shape(self):
  7410. self.hover_shapes.clear()
  7411. self.hover_shapes.redraw()
  7412. def draw_hover_shape(self, sel_obj, color=None):
  7413. """
  7414. :param sel_obj: the object for which the hover shape must be drawn
  7415. :return:
  7416. """
  7417. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7418. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7419. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7420. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7421. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7422. if self.defaults['units'].upper() == 'MM':
  7423. hover_rect = hover_rect.buffer(-0.1)
  7424. hover_rect = hover_rect.buffer(0.2)
  7425. else:
  7426. hover_rect = hover_rect.buffer(-0.00393)
  7427. hover_rect = hover_rect.buffer(0.00787)
  7428. # if color:
  7429. # face = Color(color)
  7430. # face.alpha = 0.2
  7431. # outline = Color(color, alpha=0.8)
  7432. # else:
  7433. # face = Color(self.defaults['global_sel_fill'])
  7434. # face.alpha = 0.2
  7435. # outline = self.defaults['global_sel_line']
  7436. if color:
  7437. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7438. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7439. else:
  7440. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7441. outline = self.defaults['global_sel_line']
  7442. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7443. if self.is_legacy is True:
  7444. self.hover_shapes.redraw()
  7445. def delete_selection_shape(self):
  7446. self.move_tool.sel_shapes.clear()
  7447. self.move_tool.sel_shapes.redraw()
  7448. def draw_selection_shape(self, sel_obj, color=None):
  7449. """
  7450. :param sel_obj: the object for which the selection shape must be drawn
  7451. :return:
  7452. """
  7453. if sel_obj is None:
  7454. return
  7455. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7456. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7457. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7458. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7459. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7460. if self.defaults['units'].upper() == 'MM':
  7461. sel_rect = sel_rect.buffer(-0.1)
  7462. sel_rect = sel_rect.buffer(0.2)
  7463. else:
  7464. sel_rect = sel_rect.buffer(-0.00393)
  7465. sel_rect = sel_rect.buffer(0.00787)
  7466. if color:
  7467. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7468. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7469. else:
  7470. if self.is_legacy is False:
  7471. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7472. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7473. else:
  7474. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7475. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7476. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7477. color=outline,
  7478. face_color=face,
  7479. update=True,
  7480. layer=0,
  7481. tolerance=None))
  7482. if self.is_legacy is True:
  7483. self.move_tool.sel_shapes.redraw()
  7484. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7485. """
  7486. :param old_coords: old coordinates
  7487. :param coords: new coordinates
  7488. :return:
  7489. """
  7490. if 'color' in kwargs:
  7491. color = kwargs['color']
  7492. else:
  7493. color = self.defaults['global_sel_line']
  7494. if 'face_color' in kwargs:
  7495. face_color = kwargs['face_color']
  7496. else:
  7497. face_color = self.defaults['global_sel_fill']
  7498. if 'face_alpha' in kwargs:
  7499. face_alpha = kwargs['face_alpha']
  7500. else:
  7501. face_alpha = 0.3
  7502. x0, y0 = old_coords
  7503. x1, y1 = coords
  7504. pt1 = (x0, y0)
  7505. pt2 = (x1, y0)
  7506. pt3 = (x1, y1)
  7507. pt4 = (x0, y1)
  7508. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7509. # color_t = Color(face_color)
  7510. # color_t.alpha = face_alpha
  7511. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7512. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7513. layer=0, tolerance=None)
  7514. if self.is_legacy is True:
  7515. self.move_tool.sel_shapes.redraw()
  7516. def on_file_new_click(self):
  7517. if self.collection.get_list() and self.should_we_save:
  7518. msgbox = QtWidgets.QMessageBox()
  7519. # msgbox.setText("<B>Save changes ...</B>")
  7520. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7521. "Creating a New project will delete them.\n"
  7522. "Do you want to Save the project?"))
  7523. msgbox.setWindowTitle(_("Save changes"))
  7524. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7525. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7526. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7527. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7528. msgbox.setDefaultButton(bt_yes)
  7529. msgbox.exec_()
  7530. response = msgbox.clickedButton()
  7531. if response == bt_yes:
  7532. self.on_file_saveprojectas()
  7533. elif response == bt_cancel:
  7534. return
  7535. elif response == bt_no:
  7536. self.on_file_new()
  7537. else:
  7538. self.on_file_new()
  7539. self.inform.emit('[success] %s...' %
  7540. _("New Project created"))
  7541. def on_file_new(self, cli=None):
  7542. """
  7543. Callback for menu item File -> New. Returns the application to its
  7544. startup state. This method is thread-safe.
  7545. :return: None
  7546. """
  7547. self.report_usage("on_file_new")
  7548. # Remove everything from memory
  7549. App.log.debug("on_file_new()")
  7550. if self.call_source != 'app':
  7551. self.editor2object(cleanup=True)
  7552. # ## EDITOR section
  7553. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7554. self.exc_editor = FlatCAMExcEditor(self)
  7555. self.grb_editor = FlatCAMGrbEditor(self)
  7556. # Clear pool
  7557. self.clear_pool()
  7558. for obj in self.collection.get_list():
  7559. # delete shapes left drawn from mark shape_collections, if any
  7560. if isinstance(obj, FlatCAMGerber):
  7561. try:
  7562. obj.mark_shapes.enabled = False
  7563. obj.mark_shapes.clear(update=True)
  7564. except AttributeError:
  7565. pass
  7566. # also delete annotation shapes, if any
  7567. elif isinstance(obj, FlatCAMCNCjob):
  7568. try:
  7569. obj.annotation.enabled = False
  7570. obj.annotation.clear(update=True)
  7571. except AttributeError:
  7572. pass
  7573. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7574. self.init_tcl()
  7575. self.delete_selection_shape()
  7576. self.collection.delete_all()
  7577. self.setup_component_editor()
  7578. # Clear project filename
  7579. self.project_filename = None
  7580. # Load the application defaults
  7581. self.load_defaults(filename='current_defaults')
  7582. # Re-fresh project options
  7583. self.on_options_app2project()
  7584. # Init Tools
  7585. self.init_tools()
  7586. if cli is None:
  7587. # Close any Tabs opened in the Plot Tab Area section
  7588. for index in range(self.ui.plot_tab_area.count()):
  7589. self.ui.plot_tab_area.closeTab(index)
  7590. # for whatever reason previous command does not close the last tab so I do it manually
  7591. self.ui.plot_tab_area.closeTab(0)
  7592. # # And then add again the Plot Area
  7593. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7594. self.ui.plot_tab_area.protectTab(0)
  7595. # take the focus of the Notebook on Project Tab.
  7596. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7597. self.set_ui_title(name=_("New Project - Not saved"))
  7598. def obj_properties(self):
  7599. """
  7600. Will launch the object Properties Tool
  7601. :return:
  7602. """
  7603. self.report_usage("obj_properties()")
  7604. self.properties_tool.run(toggle=False)
  7605. def on_project_context_save(self):
  7606. """
  7607. Wrapper, will save the object function of it's type
  7608. :return:
  7609. """
  7610. obj = self.collection.get_active()
  7611. if type(obj) == FlatCAMGeometry:
  7612. self.on_file_exportdxf()
  7613. elif type(obj) == FlatCAMExcellon:
  7614. self.on_file_saveexcellon()
  7615. elif type(obj) == FlatCAMCNCjob:
  7616. obj.on_exportgcode_button_click()
  7617. elif type(obj) == FlatCAMGerber:
  7618. self.on_file_savegerber()
  7619. elif type(obj) == FlatCAMScript:
  7620. self.on_file_savescript()
  7621. elif type(obj) == FlatCAMDocument:
  7622. self.on_file_savedocument()
  7623. def obj_move(self):
  7624. self.report_usage("obj_move()")
  7625. self.move_tool.run(toggle=False)
  7626. def on_fileopengerber(self, signal: bool = None, name=None):
  7627. """
  7628. File menu callback for opening a Gerber.
  7629. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7630. :return: None
  7631. """
  7632. self.report_usage("on_fileopengerber")
  7633. App.log.debug("on_fileopengerber()")
  7634. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7635. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7636. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7637. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7638. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7639. "*.mil);;" \
  7640. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7641. "Allegro Files (*.art);;" \
  7642. "Mentor Files (*.pho *.gdo);;" \
  7643. "All Files (*.*)"
  7644. if name is None:
  7645. try:
  7646. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7647. directory=self.get_last_folder(),
  7648. filter=_filter_)
  7649. except TypeError:
  7650. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7651. filenames = [str(filename) for filename in filenames]
  7652. else:
  7653. filenames = [name]
  7654. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7655. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7656. _("Opening Gerber file.")),
  7657. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7658. color=QtGui.QColor("gray"))
  7659. if len(filenames) == 0:
  7660. self.inform.emit('[WARNING_NOTCL] %s' %
  7661. _("Open Gerber cancelled."))
  7662. else:
  7663. for filename in filenames:
  7664. if filename != '':
  7665. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7666. def on_fileopenexcellon(self, signal: bool = None, name=None):
  7667. """
  7668. File menu callback for opening an Excellon file.
  7669. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7670. :return: None
  7671. """
  7672. self.report_usage("on_fileopenexcellon")
  7673. App.log.debug("on_fileopenexcellon()")
  7674. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7675. "All Files (*.*)"
  7676. if name is None:
  7677. try:
  7678. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7679. directory=self.get_last_folder(),
  7680. filter=_filter_)
  7681. except TypeError:
  7682. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7683. filenames = [str(filename) for filename in filenames]
  7684. else:
  7685. filenames = [str(name)]
  7686. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7687. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7688. _("Opening Excellon file.")),
  7689. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7690. color=QtGui.QColor("gray"))
  7691. if len(filenames) == 0:
  7692. self.inform.emit('[WARNING_NOTCL]%s' %
  7693. _(" Open Excellon cancelled."))
  7694. else:
  7695. for filename in filenames:
  7696. if filename != '':
  7697. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7698. def on_fileopengcode(self, signal: bool = None, name=None):
  7699. """
  7700. File menu call back for opening gcode.
  7701. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7702. :return: None
  7703. """
  7704. self.report_usage("on_fileopengcode")
  7705. App.log.debug("on_fileopengcode()")
  7706. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7707. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7708. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7709. "All Files (*.*)"
  7710. if name is None:
  7711. try:
  7712. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7713. directory=self.get_last_folder(),
  7714. filter=_filter_)
  7715. except TypeError:
  7716. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7717. filenames = [str(filename) for filename in filenames]
  7718. else:
  7719. filenames = [name]
  7720. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7721. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7722. _("Opening G-Code file.")),
  7723. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7724. color=QtGui.QColor("gray"))
  7725. if len(filenames) == 0:
  7726. self.inform.emit('[WARNING_NOTCL] %s' %
  7727. _("Open G-Code cancelled."))
  7728. else:
  7729. for filename in filenames:
  7730. if filename != '':
  7731. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7732. def on_file_openproject(self, signal: bool = None):
  7733. """
  7734. File menu callback for opening a project.
  7735. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7736. :return: None
  7737. """
  7738. self.report_usage("on_file_openproject")
  7739. App.log.debug("on_file_openproject()")
  7740. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7741. try:
  7742. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7743. directory=self.get_last_folder(), filter=_filter_)
  7744. except TypeError:
  7745. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7746. # The Qt methods above will return a QString which can cause problems later.
  7747. # So far json.dump() will fail to serialize it.
  7748. # TODO: Improve the serialization methods and remove this fix.
  7749. filename = str(filename)
  7750. if filename == "":
  7751. self.inform.emit('[WARNING_NOTCL] %s' %
  7752. _("Open Project cancelled."))
  7753. else:
  7754. # self.worker_task.emit({'fcn': self.open_project,
  7755. # 'params': [filename]})
  7756. # The above was failing because open_project() is not
  7757. # thread safe. The new_project()
  7758. self.open_project(filename)
  7759. def on_file_openconfig(self, signal: bool = None):
  7760. """
  7761. File menu callback for opening a config file.
  7762. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7763. :return: None
  7764. """
  7765. self.report_usage("on_file_openconfig")
  7766. App.log.debug("on_file_openconfig()")
  7767. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7768. try:
  7769. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7770. directory=self.data_path, filter=_filter_)
  7771. except TypeError:
  7772. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7773. filter=_filter_)
  7774. if filename == "":
  7775. self.inform.emit('[WARNING_NOTCL] %s' %
  7776. _("Open Config cancelled."))
  7777. else:
  7778. self.open_config_file(filename)
  7779. def on_file_exportsvg(self):
  7780. """
  7781. Callback for menu item File->Export SVG.
  7782. :return: None
  7783. """
  7784. self.report_usage("on_file_exportsvg")
  7785. App.log.debug("on_file_exportsvg()")
  7786. obj = self.collection.get_active()
  7787. if obj is None:
  7788. self.inform.emit('[WARNING_NOTCL] %s' %
  7789. _("No object selected."))
  7790. msg = _("Please Select a Geometry object to export")
  7791. msgbox = QtWidgets.QMessageBox()
  7792. msgbox.setInformativeText(msg)
  7793. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7794. msgbox.setDefaultButton(bt_ok)
  7795. msgbox.exec_()
  7796. return
  7797. # Check for more compatible types and add as required
  7798. if (not isinstance(obj, FlatCAMGeometry)
  7799. and not isinstance(obj, FlatCAMGerber)
  7800. and not isinstance(obj, FlatCAMCNCjob)
  7801. and not isinstance(obj, FlatCAMExcellon)):
  7802. msg = '[ERROR_NOTCL] %s' % \
  7803. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7804. msgbox = QtWidgets.QMessageBox()
  7805. msgbox.setInformativeText(msg)
  7806. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7807. msgbox.setDefaultButton(bt_ok)
  7808. msgbox.exec_()
  7809. return
  7810. name = obj.options["name"]
  7811. _filter = "SVG File (*.svg);;All Files (*.*)"
  7812. try:
  7813. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7814. caption=_("Export SVG"),
  7815. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7816. filter=_filter)
  7817. except TypeError:
  7818. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7819. filename = str(filename)
  7820. if filename == "":
  7821. self.inform.emit('[WARNING_NOTCL]%s' %
  7822. _(" Export SVG cancelled."))
  7823. return
  7824. else:
  7825. self.export_svg(name, filename)
  7826. if self.defaults["global_open_style"] is False:
  7827. self.file_opened.emit("SVG", filename)
  7828. self.file_saved.emit("SVG", filename)
  7829. def on_file_exportpng(self):
  7830. self.report_usage("on_file_exportpng")
  7831. App.log.debug("on_file_exportpng()")
  7832. self.date = str(datetime.today()).rpartition('.')[0]
  7833. self.date = ''.join(c for c in self.date if c not in ':-')
  7834. self.date = self.date.replace(' ', '_')
  7835. if self.is_legacy is False:
  7836. image = _screenshot()
  7837. data = np.asarray(image)
  7838. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7839. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7840. _('Data must be a 3D array with last dimension 3 or 4'))
  7841. return
  7842. filter_ = "PNG File (*.png);;All Files (*.*)"
  7843. try:
  7844. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7845. caption=_("Export PNG Image"),
  7846. directory=self.get_last_save_folder() + '/png_' + self.date,
  7847. filter=filter_)
  7848. except TypeError:
  7849. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7850. filename = str(filename)
  7851. if filename == "":
  7852. self.inform.emit(_("Export PNG cancelled."))
  7853. return
  7854. else:
  7855. if self.is_legacy is False:
  7856. write_png(filename, data)
  7857. else:
  7858. self.plotcanvas.figure.savefig(filename)
  7859. if self.defaults["global_open_style"] is False:
  7860. self.file_opened.emit("png", filename)
  7861. self.file_saved.emit("png", filename)
  7862. def on_file_savegerber(self):
  7863. """
  7864. Callback for menu item in Project context menu.
  7865. :return: None
  7866. """
  7867. self.report_usage("on_file_savegerber")
  7868. App.log.debug("on_file_savegerber()")
  7869. obj = self.collection.get_active()
  7870. if obj is None:
  7871. self.inform.emit('[WARNING_NOTCL] %s' %
  7872. _("No object selected. Please select an Gerber object to export."))
  7873. return
  7874. # Check for more compatible types and add as required
  7875. if not isinstance(obj, FlatCAMGerber):
  7876. self.inform.emit('[ERROR_NOTCL] %s' %
  7877. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7878. return
  7879. name = self.collection.get_active().options["name"]
  7880. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7881. try:
  7882. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7883. caption="Save Gerber source file",
  7884. directory=self.get_last_save_folder() + '/' + name,
  7885. filter=_filter)
  7886. except TypeError:
  7887. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7888. filename = str(filename)
  7889. if filename == "":
  7890. self.inform.emit('[WARNING_NOTCL] %s' %
  7891. _("Save Gerber source file cancelled."))
  7892. return
  7893. else:
  7894. self.save_source_file(name, filename)
  7895. if self.defaults["global_open_style"] is False:
  7896. self.file_opened.emit("Gerber", filename)
  7897. self.file_saved.emit("Gerber", filename)
  7898. def on_file_savescript(self):
  7899. """
  7900. Callback for menu item in Project context menu.
  7901. :return: None
  7902. """
  7903. self.report_usage("on_file_savescript")
  7904. App.log.debug("on_file_savescript()")
  7905. obj = self.collection.get_active()
  7906. if obj is None:
  7907. self.inform.emit('[WARNING_NOTCL] %s' %
  7908. _("No object selected. Please select an Script object to export."))
  7909. return
  7910. # Check for more compatible types and add as required
  7911. if not isinstance(obj, FlatCAMScript):
  7912. self.inform.emit('[ERROR_NOTCL] %s' %
  7913. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7914. return
  7915. name = self.collection.get_active().options["name"]
  7916. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7917. try:
  7918. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7919. caption="Save Script source file",
  7920. directory=self.get_last_save_folder() + '/' + name,
  7921. filter=_filter)
  7922. except TypeError:
  7923. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7924. filename = str(filename)
  7925. if filename == "":
  7926. self.inform.emit('[WARNING_NOTCL] %s' %
  7927. _("Save Script source file cancelled."))
  7928. return
  7929. else:
  7930. self.save_source_file(name, filename)
  7931. if self.defaults["global_open_style"] is False:
  7932. self.file_opened.emit("Script", filename)
  7933. self.file_saved.emit("Script", filename)
  7934. def on_file_savedocument(self):
  7935. """
  7936. Callback for menu item in Project context menu.
  7937. :return: None
  7938. """
  7939. self.report_usage("on_file_savedocument")
  7940. App.log.debug("on_file_savedocument()")
  7941. obj = self.collection.get_active()
  7942. if obj is None:
  7943. self.inform.emit('[WARNING_NOTCL] %s' %
  7944. _("No object selected. Please select an Document object to export."))
  7945. return
  7946. # Check for more compatible types and add as required
  7947. if not isinstance(obj, FlatCAMScript):
  7948. self.inform.emit('[ERROR_NOTCL] %s' %
  7949. _("Failed. Only Document objects can be saved as Document files..."))
  7950. return
  7951. name = self.collection.get_active().options["name"]
  7952. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7953. try:
  7954. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7955. caption="Save Document source file",
  7956. directory=self.get_last_save_folder() + '/' + name,
  7957. filter=_filter)
  7958. except TypeError:
  7959. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7960. filename = str(filename)
  7961. if filename == "":
  7962. self.inform.emit('[WARNING_NOTCL] %s' %
  7963. _("Save Document source file cancelled."))
  7964. return
  7965. else:
  7966. self.save_source_file(name, filename)
  7967. if self.defaults["global_open_style"] is False:
  7968. self.file_opened.emit("Document", filename)
  7969. self.file_saved.emit("Document", filename)
  7970. def on_file_saveexcellon(self):
  7971. """
  7972. Callback for menu item in project context menu.
  7973. :return: None
  7974. """
  7975. self.report_usage("on_file_saveexcellon")
  7976. App.log.debug("on_file_saveexcellon()")
  7977. obj = self.collection.get_active()
  7978. if obj is None:
  7979. self.inform.emit('[WARNING_NOTCL] %s' %
  7980. _("No object selected. Please select an Excellon object to export."))
  7981. return
  7982. # Check for more compatible types and add as required
  7983. if not isinstance(obj, FlatCAMExcellon):
  7984. self.inform.emit('[ERROR_NOTCL] %s' %
  7985. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7986. return
  7987. name = self.collection.get_active().options["name"]
  7988. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7989. try:
  7990. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7991. caption=_("Save Excellon source file"),
  7992. directory=self.get_last_save_folder() + '/' + name,
  7993. filter=_filter)
  7994. except TypeError:
  7995. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7996. filename = str(filename)
  7997. if filename == "":
  7998. self.inform.emit('[WARNING_NOTCL] %s' %
  7999. _("Saving Excellon source file cancelled."))
  8000. return
  8001. else:
  8002. self.save_source_file(name, filename)
  8003. if self.defaults["global_open_style"] is False:
  8004. self.file_opened.emit("Excellon", filename)
  8005. self.file_saved.emit("Excellon", filename)
  8006. def on_file_exportexcellon(self):
  8007. """
  8008. Callback for menu item File->Export->Excellon.
  8009. :return: None
  8010. """
  8011. self.report_usage("on_file_exportexcellon")
  8012. App.log.debug("on_file_exportexcellon()")
  8013. obj = self.collection.get_active()
  8014. if obj is None:
  8015. self.inform.emit('[WARNING_NOTCL] %s' %
  8016. _("No object selected. Please Select an Excellon object to export."))
  8017. return
  8018. # Check for more compatible types and add as required
  8019. if not isinstance(obj, FlatCAMExcellon):
  8020. self.inform.emit('[ERROR_NOTCL] %s' %
  8021. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8022. return
  8023. name = self.collection.get_active().options["name"]
  8024. _filter = self.defaults["excellon_save_filters"]
  8025. try:
  8026. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8027. caption=_("Export Excellon"),
  8028. directory=self.get_last_save_folder() + '/' + name,
  8029. filter=_filter)
  8030. except TypeError:
  8031. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  8032. filename = str(filename)
  8033. if filename == "":
  8034. self.inform.emit('[WARNING_NOTCL] %s' %
  8035. _("Export Excellon cancelled."))
  8036. return
  8037. else:
  8038. used_extension = filename.rpartition('.')[2]
  8039. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  8040. self.export_excellon(name, filename)
  8041. if self.defaults["global_open_style"] is False:
  8042. self.file_opened.emit("Excellon", filename)
  8043. self.file_saved.emit("Excellon", filename)
  8044. def on_file_exportgerber(self):
  8045. """
  8046. Callback for menu item File->Export->Gerber.
  8047. :return: None
  8048. """
  8049. self.report_usage("on_file_exportgerber")
  8050. App.log.debug("on_file_exportgerber()")
  8051. obj = self.collection.get_active()
  8052. if obj is None:
  8053. self.inform.emit('[WARNING_NOTCL] %s' %
  8054. _("No object selected. Please Select an Gerber object to export."))
  8055. return
  8056. # Check for more compatible types and add as required
  8057. if not isinstance(obj, FlatCAMGerber):
  8058. self.inform.emit('[ERROR_NOTCL] %s' %
  8059. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8060. return
  8061. name = self.collection.get_active().options["name"]
  8062. _filter_ = self.defaults['gerber_save_filters']
  8063. try:
  8064. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8065. caption=_("Export Gerber"),
  8066. directory=self.get_last_save_folder() + '/' + name,
  8067. filter=_filter_)
  8068. except TypeError:
  8069. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  8070. filename = str(filename)
  8071. if filename == "":
  8072. self.inform.emit('[WARNING_NOTCL] %s' %
  8073. _("Export Gerber cancelled."))
  8074. return
  8075. else:
  8076. used_extension = filename.rpartition('.')[2]
  8077. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  8078. self.export_gerber(name, filename)
  8079. if self.defaults["global_open_style"] is False:
  8080. self.file_opened.emit("Gerber", filename)
  8081. self.file_saved.emit("Gerber", filename)
  8082. def on_file_exportdxf(self):
  8083. """
  8084. Callback for menu item File->Export DXF.
  8085. :return: None
  8086. """
  8087. self.report_usage("on_file_exportdxf")
  8088. App.log.debug("on_file_exportdxf()")
  8089. obj = self.collection.get_active()
  8090. if obj is None:
  8091. self.inform.emit('[WARNING_NOTCL] %s' %
  8092. _("No object selected."))
  8093. msg = _("Please Select a Geometry object to export")
  8094. msgbox = QtWidgets.QMessageBox()
  8095. msgbox.setInformativeText(msg)
  8096. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8097. msgbox.setDefaultButton(bt_ok)
  8098. msgbox.exec_()
  8099. return
  8100. # Check for more compatible types and add as required
  8101. if not isinstance(obj, FlatCAMGeometry):
  8102. msg = '[ERROR_NOTCL] %s' % \
  8103. _("Only Geometry objects can be used.")
  8104. msgbox = QtWidgets.QMessageBox()
  8105. msgbox.setInformativeText(msg)
  8106. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8107. msgbox.setDefaultButton(bt_ok)
  8108. msgbox.exec_()
  8109. return
  8110. name = self.collection.get_active().options["name"]
  8111. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8112. try:
  8113. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8114. caption=_("Export DXF"),
  8115. directory=self.get_last_save_folder() + '/' + name,
  8116. filter=_filter_)
  8117. except TypeError:
  8118. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  8119. filter=_filter_)
  8120. filename = str(filename)
  8121. if filename == "":
  8122. self.inform.emit('[WARNING_NOTCL] %s' %
  8123. _("Export DXF cancelled."))
  8124. return
  8125. else:
  8126. self.export_dxf(name, filename)
  8127. if self.defaults["global_open_style"] is False:
  8128. self.file_opened.emit("DXF", filename)
  8129. self.file_saved.emit("DXF", filename)
  8130. def on_file_importsvg(self, type_of_obj):
  8131. """
  8132. Callback for menu item File->Import SVG.
  8133. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8134. :type type_of_obj: str
  8135. :return: None
  8136. """
  8137. self.report_usage("on_file_importsvg")
  8138. App.log.debug("on_file_importsvg()")
  8139. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  8140. try:
  8141. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8142. directory=self.get_last_folder(), filter=_filter_)
  8143. except TypeError:
  8144. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8145. filter=_filter_)
  8146. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8147. type_of_obj = "geometry"
  8148. filenames = [str(filename) for filename in filenames]
  8149. if len(filenames) == 0:
  8150. self.inform.emit('[WARNING_NOTCL] %s' %
  8151. _("Open SVG cancelled."))
  8152. else:
  8153. for filename in filenames:
  8154. if filename != '':
  8155. self.worker_task.emit({'fcn': self.import_svg,
  8156. 'params': [filename, type_of_obj]})
  8157. def on_file_importdxf(self, type_of_obj):
  8158. """
  8159. Callback for menu item File->Import DXF.
  8160. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8161. :type type_of_obj: str
  8162. :return: None
  8163. """
  8164. self.report_usage("on_file_importdxf")
  8165. App.log.debug("on_file_importdxf()")
  8166. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8167. try:
  8168. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8169. directory=self.get_last_folder(),
  8170. filter=_filter_)
  8171. except TypeError:
  8172. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8173. filter=_filter_)
  8174. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8175. type_of_obj = "geometry"
  8176. filenames = [str(filename) for filename in filenames]
  8177. if len(filenames) == 0:
  8178. self.inform.emit('[WARNING_NOTCL] %s' %
  8179. _("Open DXF cancelled."))
  8180. else:
  8181. for filename in filenames:
  8182. if filename != '':
  8183. self.worker_task.emit({'fcn': self.import_dxf,
  8184. 'params': [filename, type_of_obj]})
  8185. # ###############################################################################################################
  8186. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8187. # ###############################################################################################################
  8188. def init_code_editor(self, name):
  8189. self.text_editor_tab = TextEditor(app=self)
  8190. # add the tab if it was closed
  8191. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8192. self.text_editor_tab.setObjectName('text_editor_tab')
  8193. # delete the absolute and relative position and messages in the infobar
  8194. self.ui.position_label.setText("")
  8195. self.ui.rel_position_label.setText("")
  8196. # first clear previous text in text editor (if any)
  8197. self.text_editor_tab.code_editor.clear()
  8198. self.text_editor_tab.code_editor.setReadOnly(False)
  8199. self.toggle_codeeditor = True
  8200. self.text_editor_tab.code_editor.completer_enable = False
  8201. self.text_editor_tab.buttonRun.hide()
  8202. # make sure to keep a reference to the code editor
  8203. self.reference_code_editor = self.text_editor_tab.code_editor
  8204. # Switch plot_area to CNCJob tab
  8205. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8206. def on_view_source(self):
  8207. """
  8208. Called when the user wants to see the source file of the selected object
  8209. :return:
  8210. """
  8211. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8212. self.proc_container.view.set_busy(_("Loading..."))
  8213. try:
  8214. obj = self.collection.get_active()
  8215. except Exception as e:
  8216. log.debug("App.on_view_source() --> %s" % str(e))
  8217. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8218. return 'fail'
  8219. if obj is None:
  8220. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8221. return 'fail'
  8222. flt = "All Files (*.*)"
  8223. if obj.kind == 'gerber':
  8224. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  8225. elif obj.kind == 'excellon':
  8226. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  8227. elif obj.kind == 'cncjob':
  8228. "GCode Files (*.NC);;All Files (*.*)"
  8229. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  8230. # add the tab if it was closed
  8231. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8232. self.source_editor_tab.setObjectName('source_editor_tab')
  8233. # delete the absolute and relative position and messages in the infobar
  8234. self.ui.position_label.setText("")
  8235. self.ui.rel_position_label.setText("")
  8236. # first clear previous text in text editor (if any)
  8237. self.source_editor_tab.code_editor.clear()
  8238. self.source_editor_tab.code_editor.setReadOnly(False)
  8239. self.source_editor_tab.code_editor.completer_enable = False
  8240. self.source_editor_tab.buttonRun.hide()
  8241. # Switch plot_area to CNCJob tab
  8242. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8243. try:
  8244. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8245. except TypeError:
  8246. pass
  8247. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8248. try:
  8249. self.source_editor_tab.buttonSave.clicked.disconnect()
  8250. except TypeError:
  8251. pass
  8252. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8253. # then append the text from GCode to the text editor
  8254. if obj.kind == 'cncjob':
  8255. try:
  8256. file = obj.export_gcode(
  8257. preamble=self.defaults["cncjob_prepend"],
  8258. postamble=self.defaults["cncjob_append"],
  8259. to_file=True)
  8260. if file == 'fail':
  8261. return 'fail'
  8262. except AttributeError:
  8263. self.inform.emit('[WARNING_NOTCL] %s' %
  8264. _("There is no selected object for which to see it's source file code."))
  8265. return 'fail'
  8266. else:
  8267. try:
  8268. file = StringIO(obj.source_file)
  8269. except (AttributeError, TypeError):
  8270. self.inform.emit('[WARNING_NOTCL] %s' %
  8271. _("There is no selected object for which to see it's source file code."))
  8272. return 'fail'
  8273. self.source_editor_tab.t_frame.hide()
  8274. try:
  8275. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  8276. # for line in file:
  8277. # QtWidgets.QApplication.processEvents()
  8278. # proc_line = str(line).strip('\n')
  8279. # self.source_editor_tab.code_editor.append(proc_line)
  8280. except Exception as e:
  8281. log.debug('App.on_view_source() -->%s' % str(e))
  8282. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  8283. return
  8284. self.source_editor_tab.handleTextChanged()
  8285. self.source_editor_tab.t_frame.show()
  8286. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8287. self.proc_container.view.set_idle()
  8288. # self.ui.show()
  8289. def on_toggle_code_editor(self):
  8290. self.report_usage("on_toggle_code_editor()")
  8291. if self.toggle_codeeditor is False:
  8292. self.init_code_editor(name=_("Code Editor"))
  8293. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8294. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8295. self.text_editor_tab.buttonSave.clicked.disconnect()
  8296. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8297. else:
  8298. for idx in range(self.ui.plot_tab_area.count()):
  8299. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8300. self.ui.plot_tab_area.closeTab(idx)
  8301. break
  8302. self.toggle_codeeditor = False
  8303. def on_code_editor_close(self):
  8304. print("closed")
  8305. self.toggle_codeeditor = False
  8306. def on_filenewscript(self, silent=False, name=None, text=None):
  8307. """
  8308. Will create a new script file and open it in the Code Editor
  8309. :param silent: if True will not display status messages
  8310. :param name: if specified will be the name of the new script
  8311. :param text: pass a source file to the newly created script to be loaded in it
  8312. :return: None
  8313. """
  8314. if silent is False:
  8315. self.inform.emit('[success] %s' %
  8316. _("New TCL script file created in Code Editor."))
  8317. # delete the absolute and relative position and messages in the infobar
  8318. self.ui.position_label.setText("")
  8319. self.ui.rel_position_label.setText("")
  8320. if name is not None:
  8321. self.new_script_object(name=name, text=text)
  8322. else:
  8323. self.new_script_object(text=text)
  8324. # script_text = script_obj.source_file
  8325. #
  8326. # self.proc_container.view.set_busy(_("Loading..."))
  8327. # script_obj.script_editor_tab.t_frame.hide()
  8328. #
  8329. # script_obj.script_editor_tab.t_frame.show()
  8330. # self.proc_container.view.set_idle()
  8331. def on_fileopenscript(self, name=None, silent=False):
  8332. """
  8333. Will open a Tcl script file into the Code Editor
  8334. :param silent: if True will not display status messages
  8335. :param name: name of a Tcl script file to open
  8336. :return:
  8337. """
  8338. self.report_usage("on_fileopenscript")
  8339. App.log.debug("on_fileopenscript()")
  8340. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8341. if name:
  8342. filenames = [name]
  8343. else:
  8344. try:
  8345. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8346. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8347. except TypeError:
  8348. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8349. if len(filenames) == 0:
  8350. if silent is False:
  8351. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8352. else:
  8353. for filename in filenames:
  8354. if filename != '':
  8355. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8356. def on_filerunscript(self, name=None, silent=False):
  8357. """
  8358. File menu callback for loading and running a TCL script.
  8359. :param silent: if True will not display status messages
  8360. :param name: name of a Tcl script file to be run by FlatCAM
  8361. :return: None
  8362. """
  8363. self.report_usage("on_filerunscript")
  8364. App.log.debug("on_file_runscript()")
  8365. if name:
  8366. filename = name
  8367. if self.cmd_line_headless != 1:
  8368. self.splash.showMessage('%s: %ssec\n%s' %
  8369. (_("Canvas initialization started.\n"
  8370. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8371. _("Executing FlatCAMScript file.")
  8372. ),
  8373. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8374. color=QtGui.QColor("gray"))
  8375. else:
  8376. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8377. try:
  8378. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8379. directory=self.get_last_folder(), filter=_filter_)
  8380. except TypeError:
  8381. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8382. # The Qt methods above will return a QString which can cause problems later.
  8383. # So far json.dump() will fail to serialize it.
  8384. # TODO: Improve the serialization methods and remove this fix.
  8385. filename = str(filename)
  8386. if filename == "":
  8387. if silent is False:
  8388. self.inform.emit('[WARNING_NOTCL] %s' %
  8389. _("Run TCL script cancelled."))
  8390. else:
  8391. if self.cmd_line_headless != 1:
  8392. if self.ui.shell_dock.isHidden():
  8393. self.ui.shell_dock.show()
  8394. try:
  8395. with open(filename, "r") as tcl_script:
  8396. cmd_line_shellfile_content = tcl_script.read()
  8397. if self.cmd_line_headless != 1:
  8398. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8399. else:
  8400. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8401. if silent is False:
  8402. self.inform.emit('[success] %s' %
  8403. _("TCL script file opened in Code Editor and executed."))
  8404. except Exception as e:
  8405. log.debug("App.on_filerunscript() -> %s" % str(e))
  8406. sys.exit(2)
  8407. def on_file_saveproject(self, silent=False):
  8408. """
  8409. Callback for menu item File->Save Project. Saves the project to
  8410. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8411. if set to None. The project is saved by calling ``self.save_project()``.
  8412. :param silent: if True will not display status messages
  8413. :return: None
  8414. """
  8415. self.report_usage("on_file_saveproject")
  8416. if self.project_filename is None:
  8417. self.on_file_saveprojectas()
  8418. else:
  8419. self.worker_task.emit({'fcn': self.save_project,
  8420. 'params': [self.project_filename, silent]})
  8421. if self.defaults["global_open_style"] is False:
  8422. self.file_opened.emit("project", self.project_filename)
  8423. self.file_saved.emit("project", self.project_filename)
  8424. self.set_ui_title(name=self.project_filename)
  8425. self.should_we_save = False
  8426. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8427. """
  8428. Callback for menu item File->Save Project As... Opens a file
  8429. chooser and saves the project to the given file via
  8430. ``self.save_project()``.
  8431. :param make_copy if to be create a copy of the project; boolean
  8432. :param use_thread: if to be run in a separate thread; boolean
  8433. :param quit_action: if to be followed by quiting the application; boolean
  8434. :return: None
  8435. """
  8436. self.report_usage("on_file_saveprojectas")
  8437. self.date = str(datetime.today()).rpartition('.')[0]
  8438. self.date = ''.join(c for c in self.date if c not in ':-')
  8439. self.date = self.date.replace(' ', '_')
  8440. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8441. try:
  8442. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8443. caption=_("Save Project As ..."),
  8444. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  8445. filter=filter_)
  8446. except TypeError:
  8447. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8448. filename = str(filename)
  8449. if filename == '':
  8450. self.inform.emit('[WARNING_NOTCL] %s' %
  8451. _("Save Project cancelled."))
  8452. return
  8453. try:
  8454. f = open(filename, 'r')
  8455. f.close()
  8456. except IOError:
  8457. pass
  8458. if use_thread is True:
  8459. self.worker_task.emit({'fcn': self.save_project,
  8460. 'params': [filename, quit_action]})
  8461. else:
  8462. self.save_project(filename, quit_action)
  8463. # self.save_project(filename)
  8464. if self.defaults["global_open_style"] is False:
  8465. self.file_opened.emit("project", filename)
  8466. self.file_saved.emit("project", filename)
  8467. if not make_copy:
  8468. self.project_filename = filename
  8469. self.set_ui_title(name=self.project_filename)
  8470. self.should_we_save = False
  8471. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8472. """
  8473. Exports a Geometry Object to an SVG file.
  8474. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8475. :param filename: Path to the SVG file to save to.
  8476. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8477. :return:
  8478. """
  8479. self.report_usage("export_svg()")
  8480. if filename is None:
  8481. filename = self.defaults["global_last_save_folder"]
  8482. self.log.debug("export_svg()")
  8483. try:
  8484. obj = self.collection.get_by_name(str(obj_name))
  8485. except Exception:
  8486. # TODO: The return behavior has not been established... should raise exception?
  8487. return "Could not retrieve object: %s" % obj_name
  8488. with self.proc_container.new(_("Exporting SVG")) as proc:
  8489. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8490. # Determine bounding area for svg export
  8491. bounds = obj.bounds()
  8492. size = obj.size()
  8493. # Convert everything to strings for use in the xml doc
  8494. svgwidth = str(size[0])
  8495. svgheight = str(size[1])
  8496. minx = str(bounds[0])
  8497. miny = str(bounds[1] - size[1])
  8498. uom = obj.units.lower()
  8499. # Add a SVG Header and footer to the svg output from shapely
  8500. # The transform flips the Y Axis so that everything renders
  8501. # properly within svg apps such as inkscape
  8502. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8503. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8504. svg_header += 'width="' + svgwidth + uom + '" '
  8505. svg_header += 'height="' + svgheight + uom + '" '
  8506. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8507. svg_header += '<g transform="scale(1,-1)">'
  8508. svg_footer = '</g> </svg>'
  8509. svg_elem = svg_header + exported_svg + svg_footer
  8510. # Parse the xml through a xml parser just to add line feeds
  8511. # and to make it look more pretty for the output
  8512. svgcode = parse_xml_string(svg_elem)
  8513. svgcode = svgcode.toprettyxml()
  8514. try:
  8515. with open(filename, 'w') as fp:
  8516. fp.write(svgcode)
  8517. except PermissionError:
  8518. self.inform.emit('[WARNING] %s' %
  8519. _("Permission denied, saving not possible.\n"
  8520. "Most likely another app is holding the file open and not accessible."))
  8521. return 'fail'
  8522. if self.defaults["global_open_style"] is False:
  8523. self.file_opened.emit("SVG", filename)
  8524. self.file_saved.emit("SVG", filename)
  8525. self.inform.emit('[success] %s: %s' %
  8526. (_("SVG file exported to"), filename))
  8527. def save_source_file(self, obj_name, filename, use_thread=True):
  8528. """
  8529. Exports a FlatCAM Object to an Gerber/Excellon file.
  8530. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8531. :param filename: Path to the Gerber file to save to.
  8532. :param use_thread: if to be run in a separate thread
  8533. :return:
  8534. """
  8535. self.report_usage("save source file()")
  8536. if filename is None:
  8537. filename = self.defaults["global_last_save_folder"]
  8538. self.log.debug("save source file()")
  8539. obj = self.collection.get_by_name(obj_name)
  8540. file_string = StringIO(obj.source_file)
  8541. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8542. if file_string.getvalue() == '':
  8543. self.inform.emit('[ERROR_NOTCL] %s' %
  8544. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  8545. return 'fail'
  8546. try:
  8547. with open(filename, 'w') as file:
  8548. file.writelines('G04*\n')
  8549. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8550. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8551. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8552. file.writelines('G04 Created on : %s*\n' % time_string)
  8553. for line in file_string:
  8554. file.writelines(line)
  8555. except PermissionError:
  8556. self.inform.emit('[WARNING] %s' %
  8557. _("Permission denied, saving not possible.\n"
  8558. "Most likely another app is holding the file open and not accessible."))
  8559. return 'fail'
  8560. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8561. """
  8562. Exports a Excellon Object to an Excellon file.
  8563. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8564. :param filename: Path to the Excellon file to save to.
  8565. :param local_use:
  8566. :param use_thread: if to be run in a separate thread
  8567. :return:
  8568. """
  8569. self.report_usage("export_excellon()")
  8570. if filename is None:
  8571. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  8572. self.log.debug("export_excellon()")
  8573. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8574. self.defaults["excellon_exp_decimals"]
  8575. )
  8576. if local_use is None:
  8577. try:
  8578. obj = self.collection.get_by_name(str(obj_name))
  8579. except Exception:
  8580. # TODO: The return behavior has not been established... should raise exception?
  8581. return "Could not retrieve object: %s" % obj_name
  8582. else:
  8583. obj = local_use
  8584. if not isinstance(obj, FlatCAMExcellon):
  8585. self.inform.emit('[ERROR_NOTCL] %s' %
  8586. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8587. return
  8588. # updated units
  8589. eunits = self.defaults["excellon_exp_units"]
  8590. ewhole = self.defaults["excellon_exp_integer"]
  8591. efract = self.defaults["excellon_exp_decimals"]
  8592. ezeros = self.defaults["excellon_exp_zeros"]
  8593. eformat = self.defaults["excellon_exp_format"]
  8594. slot_type = self.defaults["excellon_exp_slot_type"]
  8595. fc_units = self.defaults['units'].upper()
  8596. if fc_units == 'MM':
  8597. factor = 1 if eunits == 'METRIC' else 0.03937
  8598. else:
  8599. factor = 25.4 if eunits == 'METRIC' else 1
  8600. def make_excellon():
  8601. try:
  8602. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8603. header = 'M48\n'
  8604. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8605. (str(self.version), str(self.version_date))
  8606. header += ';Filename: %s' % str(obj_name) + '\n'
  8607. header += ';Created on : %s' % time_str + '\n'
  8608. if eformat == 'dec':
  8609. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8610. header += eunits + '\n'
  8611. for tool in obj.tools:
  8612. if eunits == 'METRIC':
  8613. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8614. tool=str(tool),
  8615. dec=2)
  8616. else:
  8617. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8618. tool=str(tool),
  8619. dec=4)
  8620. else:
  8621. if ezeros == 'LZ':
  8622. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8623. form='ndec', e_zeros='LZ', factor=factor,
  8624. slot_type=slot_type)
  8625. header += '%s,%s\n' % (eunits, 'LZ')
  8626. header += format_exc
  8627. for tool in obj.tools:
  8628. if eunits == 'METRIC':
  8629. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8630. tool=str(tool),
  8631. dec=2)
  8632. else:
  8633. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8634. tool=str(tool),
  8635. dec=4)
  8636. else:
  8637. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8638. form='ndec', e_zeros='TZ', factor=factor,
  8639. slot_type=slot_type)
  8640. header += '%s,%s\n' % (eunits, 'TZ')
  8641. header += format_exc
  8642. for tool in obj.tools:
  8643. if eunits == 'METRIC':
  8644. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8645. tool=str(tool),
  8646. dec=2)
  8647. else:
  8648. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8649. tool=str(tool),
  8650. dec=4)
  8651. header += '%\n'
  8652. footer = 'M30\n'
  8653. exported_excellon = header
  8654. exported_excellon += excellon_code
  8655. exported_excellon += footer
  8656. if local_use is None:
  8657. try:
  8658. with open(filename, 'w') as fp:
  8659. fp.write(exported_excellon)
  8660. except PermissionError:
  8661. self.inform.emit('[WARNING] %s' %
  8662. _("Permission denied, saving not possible.\n"
  8663. "Most likely another app is holding the file open and not accessible."))
  8664. return 'fail'
  8665. if self.defaults["global_open_style"] is False:
  8666. self.file_opened.emit("Excellon", filename)
  8667. self.file_saved.emit("Excellon", filename)
  8668. self.inform.emit('[success] %s: %s' %
  8669. (_("Excellon file exported to"), filename))
  8670. else:
  8671. return exported_excellon
  8672. except Exception as e:
  8673. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8674. return 'fail'
  8675. if use_thread is True:
  8676. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8677. def job_thread_exc(app_obj):
  8678. ret = make_excellon()
  8679. if ret == 'fail':
  8680. self.inform.emit('[ERROR_NOTCL] %s' %
  8681. _('Could not export Excellon file.'))
  8682. return
  8683. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8684. else:
  8685. ret = make_excellon()
  8686. if ret == 'fail':
  8687. self.inform.emit('[ERROR_NOTCL] %s' %
  8688. _('Could not export Excellon file.'))
  8689. return 'fail'
  8690. if local_use is not None:
  8691. return ret
  8692. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8693. """
  8694. Exports a Gerber Object to an Gerber file.
  8695. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8696. :param filename: Path to the Gerber file to save to.
  8697. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8698. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8699. :param use_thread: if to be run in a separate thread
  8700. :return:
  8701. """
  8702. self.report_usage("export_gerber()")
  8703. if filename is None:
  8704. filename = self.defaults["global_last_save_folder"]
  8705. self.log.debug("export_gerber()")
  8706. if local_use is None:
  8707. try:
  8708. obj = self.collection.get_by_name(str(obj_name))
  8709. except Exception:
  8710. # TODO: The return behavior has not been established... should raise exception?
  8711. return "Could not retrieve object: %s" % obj_name
  8712. else:
  8713. obj = local_use
  8714. # updated units
  8715. gunits = self.defaults["gerber_exp_units"]
  8716. gwhole = self.defaults["gerber_exp_integer"]
  8717. gfract = self.defaults["gerber_exp_decimals"]
  8718. gzeros = self.defaults["gerber_exp_zeros"]
  8719. fc_units = self.defaults['units'].upper()
  8720. if fc_units == 'MM':
  8721. factor = 1 if gunits == 'MM' else 0.03937
  8722. else:
  8723. factor = 25.4 if gunits == 'MM' else 1
  8724. def make_gerber():
  8725. try:
  8726. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8727. header = 'G04*\n'
  8728. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8729. (str(self.version), str(self.version_date))
  8730. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8731. header += 'G04 Created on : %s*' % time_str + '\n'
  8732. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8733. header += "%MO{units}*%\n".format(units=gunits)
  8734. for apid in obj.apertures:
  8735. if obj.apertures[apid]['type'] == 'C':
  8736. header += "%ADD{apid}{type},{size}*%\n".format(
  8737. apid=str(apid),
  8738. type='C',
  8739. size=(factor * obj.apertures[apid]['size'])
  8740. )
  8741. elif obj.apertures[apid]['type'] == 'R':
  8742. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8743. apid=str(apid),
  8744. type='R',
  8745. width=(factor * obj.apertures[apid]['width']),
  8746. height=(factor * obj.apertures[apid]['height'])
  8747. )
  8748. elif obj.apertures[apid]['type'] == 'O':
  8749. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8750. apid=str(apid),
  8751. type='O',
  8752. width=(factor * obj.apertures[apid]['width']),
  8753. height=(factor * obj.apertures[apid]['height'])
  8754. )
  8755. header += '\n'
  8756. # obsolete units but some software may need it
  8757. if gunits == 'IN':
  8758. header += 'G70*\n'
  8759. else:
  8760. header += 'G71*\n'
  8761. # Absolute Mode
  8762. header += 'G90*\n'
  8763. header += 'G01*\n'
  8764. # positive polarity
  8765. header += '%LPD*%\n'
  8766. footer = 'M02*\n'
  8767. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8768. exported_gerber = header
  8769. exported_gerber += gerber_code
  8770. exported_gerber += footer
  8771. if local_use is None:
  8772. try:
  8773. with open(filename, 'w') as fp:
  8774. fp.write(exported_gerber)
  8775. except PermissionError:
  8776. self.inform.emit('[WARNING] %s' %
  8777. _("Permission denied, saving not possible.\n"
  8778. "Most likely another app is holding the file open and not accessible."))
  8779. return 'fail'
  8780. if self.defaults["global_open_style"] is False:
  8781. self.file_opened.emit("Gerber", filename)
  8782. self.file_saved.emit("Gerber", filename)
  8783. self.inform.emit('[success] %s: %s' %
  8784. (_("Gerber file exported to"), filename))
  8785. else:
  8786. return exported_gerber
  8787. except Exception as e:
  8788. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8789. return 'fail'
  8790. if use_thread is True:
  8791. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8792. def job_thread_grb(app_obj):
  8793. ret = make_gerber()
  8794. if ret == 'fail':
  8795. self.inform.emit('[ERROR_NOTCL] %s' %
  8796. _('Could not export Gerber file.'))
  8797. return
  8798. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8799. else:
  8800. ret = make_gerber()
  8801. if ret == 'fail':
  8802. self.inform.emit('[ERROR_NOTCL] %s' %
  8803. _('Could not export Gerber file.'))
  8804. return 'fail'
  8805. if local_use is not None:
  8806. return ret
  8807. def export_dxf(self, obj_name, filename, use_thread=True):
  8808. """
  8809. Exports a Geometry Object to an DXF file.
  8810. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8811. :param filename: Path to the DXF file to save to.
  8812. :param use_thread: if to be run in a separate thread
  8813. :return:
  8814. """
  8815. self.report_usage("export_dxf()")
  8816. if filename is None:
  8817. filename = self.defaults["global_last_save_folder"]
  8818. self.log.debug("export_dxf()")
  8819. try:
  8820. obj = self.collection.get_by_name(str(obj_name))
  8821. except Exception:
  8822. # TODO: The return behavior has not been established... should raise exception?
  8823. return "Could not retrieve object: %s" % obj_name
  8824. def make_dxf():
  8825. try:
  8826. dxf_code = obj.export_dxf()
  8827. dxf_code.saveas(filename)
  8828. if self.defaults["global_open_style"] is False:
  8829. self.file_opened.emit("DXF", filename)
  8830. self.file_saved.emit("DXF", filename)
  8831. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8832. except Exception:
  8833. return 'fail'
  8834. if use_thread is True:
  8835. with self.proc_container.new(_("Exporting DXF")) as proc:
  8836. def job_thread_exc(app_obj):
  8837. ret_dxf_val = make_dxf()
  8838. if ret_dxf_val == 'fail':
  8839. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8840. return
  8841. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8842. else:
  8843. ret = make_dxf()
  8844. if ret == 'fail':
  8845. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8846. return
  8847. def import_svg(self, filename, geo_type='geometry', outname=None):
  8848. """
  8849. Adds a new Geometry Object to the projects and populates
  8850. it with shapes extracted from the SVG file.
  8851. :param filename: Path to the SVG file.
  8852. :param geo_type: Type of FlatCAM object that will be created from SVG
  8853. :param outname:
  8854. :return:
  8855. """
  8856. self.report_usage("import_svg()")
  8857. log.debug("App.import_svg()")
  8858. obj_type = ""
  8859. if geo_type is None or geo_type == "geometry":
  8860. obj_type = "geometry"
  8861. elif geo_type == "gerber":
  8862. obj_type = "gerber"
  8863. else:
  8864. self.inform.emit('[ERROR_NOTCL] %s' %
  8865. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8866. return
  8867. units = self.defaults['units'].upper()
  8868. def obj_init(geo_obj, app_obj):
  8869. geo_obj.import_svg(filename, obj_type, units=units)
  8870. geo_obj.multigeo = False
  8871. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  8872. with self.proc_container.new(_("Importing SVG")) as proc:
  8873. # Object name
  8874. name = outname or filename.split('/')[-1].split('\\')[-1]
  8875. self.new_object(obj_type, name, obj_init, autoselected=False)
  8876. # Register recent file
  8877. self.file_opened.emit("svg", filename)
  8878. # GUI feedback
  8879. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8880. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8881. """
  8882. Adds a new Geometry Object to the projects and populates
  8883. it with shapes extracted from the DXF file.
  8884. :param filename: Path to the DXF file.
  8885. :param geo_type: Type of FlatCAM object that will be created from DXF
  8886. :param outname:
  8887. :type putname: str
  8888. :return:
  8889. """
  8890. self.report_usage("import_dxf()")
  8891. obj_type = ""
  8892. if geo_type is None or geo_type == "geometry":
  8893. obj_type = "geometry"
  8894. elif geo_type == "gerber":
  8895. obj_type = geo_type
  8896. else:
  8897. self.inform.emit('[ERROR_NOTCL] %s' %
  8898. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8899. return
  8900. units = self.defaults['units'].upper()
  8901. def obj_init(geo_obj, app_obj):
  8902. geo_obj.import_dxf(filename, obj_type, units=units)
  8903. geo_obj.multigeo = False
  8904. with self.proc_container.new(_("Importing DXF")) as proc:
  8905. # Object name
  8906. name = outname or filename.split('/')[-1].split('\\')[-1]
  8907. self.new_object(obj_type, name, obj_init, autoselected=False)
  8908. self.progress.emit(20)
  8909. # Register recent file
  8910. self.file_opened.emit("dxf", filename)
  8911. # GUI feedback
  8912. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8913. self.progress.emit(100)
  8914. def open_gerber(self, filename, outname=None):
  8915. """
  8916. Opens a Gerber file, parses it and creates a new object for
  8917. it in the program. Thread-safe.
  8918. :param outname: Name of the resulting object. None causes the
  8919. name to be that of the file.
  8920. :param filename: Gerber file filename
  8921. :type filename: str
  8922. :return: None
  8923. """
  8924. # How the object should be initialized
  8925. def obj_init(gerber_obj, app_obj):
  8926. assert isinstance(gerber_obj, FlatCAMGerber), \
  8927. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8928. # Opening the file happens here
  8929. try:
  8930. gerber_obj.parse_file(filename)
  8931. except IOError:
  8932. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8933. return "fail"
  8934. except ParseError as err:
  8935. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8936. app_obj.log.error(str(err))
  8937. return "fail"
  8938. except Exception as e:
  8939. log.debug("App.open_gerber() --> %s" % str(e))
  8940. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8941. msg += traceback.format_exc()
  8942. app_obj.inform.emit(msg)
  8943. return "fail"
  8944. if gerber_obj.is_empty():
  8945. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8946. _("Object is not Gerber file or empty. Aborting object creation."))
  8947. return "fail"
  8948. App.log.debug("open_gerber()")
  8949. with self.proc_container.new(_("Opening Gerber")) as proc:
  8950. # Object name
  8951. name = outname or filename.split('/')[-1].split('\\')[-1]
  8952. # # ## Object creation # ##
  8953. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8954. if ret == 'fail':
  8955. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  8956. return 'fail'
  8957. # Register recent file
  8958. self.file_opened.emit("gerber", filename)
  8959. # GUI feedback
  8960. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8961. def open_excellon(self, filename, outname=None, plot=True):
  8962. """
  8963. Opens an Excellon file, parses it and creates a new object for
  8964. it in the program. Thread-safe.
  8965. :param outname: Name of the resulting object. None causes the
  8966. name to be that of the file.
  8967. :param filename: Excellon file filename
  8968. :type filename: str
  8969. :return: None
  8970. """
  8971. App.log.debug("open_excellon()")
  8972. # How the object should be initialized
  8973. def obj_init(excellon_obj, app_obj):
  8974. # self.progress.emit(20)
  8975. try:
  8976. ret = excellon_obj.parse_file(filename=filename)
  8977. if ret == "fail":
  8978. log.debug("Excellon parsing failed.")
  8979. self.inform.emit('[ERROR_NOTCL] %s' %
  8980. _("This is not Excellon file."))
  8981. return "fail"
  8982. except IOError:
  8983. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8984. (_("Cannot open file"), filename))
  8985. log.debug("Could not open Excellon object.")
  8986. self.progress.emit(0) # TODO: self and app_bjj mixed
  8987. return "fail"
  8988. except Exception:
  8989. msg = '[ERROR_NOTCL] %s' % \
  8990. _("An internal error has occurred. See shell.\n")
  8991. msg += traceback.format_exc()
  8992. app_obj.inform.emit(msg)
  8993. return "fail"
  8994. ret = excellon_obj.create_geometry()
  8995. if ret == 'fail':
  8996. log.debug("Could not create geometry for Excellon object.")
  8997. return "fail"
  8998. for tool in excellon_obj.tools:
  8999. if excellon_obj.tools[tool]['solid_geometry']:
  9000. return
  9001. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9002. (_("No geometry found in file"), filename))
  9003. return "fail"
  9004. with self.proc_container.new(_("Opening Excellon.")):
  9005. # Object name
  9006. name = outname or filename.split('/')[-1].split('\\')[-1]
  9007. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  9008. if ret_val == 'fail':
  9009. self.inform.emit('[ERROR_NOTCL] %s' %
  9010. _('Open Excellon file failed. Probable not an Excellon file.'))
  9011. return
  9012. # Register recent file
  9013. self.file_opened.emit("excellon", filename)
  9014. # GUI feedback
  9015. self.inform.emit('[success] %s: %s' %
  9016. (_("Opened"), filename))
  9017. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  9018. """
  9019. Opens a G-gcode file, parses it and creates a new object for
  9020. it in the program. Thread-safe.
  9021. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9022. :param filename: G-code file filename
  9023. :type filename: str
  9024. :return: None
  9025. """
  9026. App.log.debug("open_gcode()")
  9027. # How the object should be initialized
  9028. def obj_init(job_obj, app_obj_):
  9029. """
  9030. :param job_obj: the resulting object
  9031. :type app_obj_: App
  9032. """
  9033. assert isinstance(app_obj_, App), \
  9034. "Initializer expected App, got %s" % type(app_obj_)
  9035. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  9036. try:
  9037. f = open(filename)
  9038. gcode = f.read()
  9039. f.close()
  9040. except IOError:
  9041. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  9042. (_("Failed to open"), filename))
  9043. return "fail"
  9044. job_obj.gcode = gcode
  9045. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9046. if gcode_ret == "fail":
  9047. self.inform.emit('[ERROR_NOTCL] %s' %
  9048. _("This is not GCODE"))
  9049. return "fail"
  9050. job_obj.create_geometry()
  9051. with self.proc_container.new(_("Opening G-Code.")):
  9052. # Object name
  9053. name = outname or filename.split('/')[-1].split('\\')[-1]
  9054. # New object creation and file processing
  9055. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9056. if obj_ret == 'fail':
  9057. self.inform.emit('[ERROR_NOTCL] %s' %
  9058. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9059. "Try to load it from File menu.\n "
  9060. "Attempting to create a FlatCAM CNCJob Object from "
  9061. "G-Code file failed during processing"))
  9062. return "fail"
  9063. # Register recent file
  9064. self.file_opened.emit("cncjob", filename)
  9065. # GUI feedback
  9066. self.inform.emit('[success] %s: %s' %
  9067. (_("Opened"), filename))
  9068. def open_script(self, filename, outname=None, silent=False):
  9069. """
  9070. Opens a Script file, parses it and creates a new object for
  9071. it in the program. Thread-safe.
  9072. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9073. :param filename: Script file filename
  9074. :type filename: str
  9075. :return: None
  9076. """
  9077. App.log.debug("open_script()")
  9078. with self.proc_container.new(_("Opening TCL Script...")):
  9079. try:
  9080. with open(filename, "r") as opened_script:
  9081. script_content = opened_script.readlines()
  9082. script_content = ''.join(script_content)
  9083. if silent is False:
  9084. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9085. except Exception as e:
  9086. log.debug("App.open_script() -> %s" % str(e))
  9087. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9088. return
  9089. # Object name
  9090. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9091. # New object creation and file processing
  9092. self.on_filenewscript(name=script_name, text=script_content)
  9093. # Register recent file
  9094. self.file_opened.emit("script", filename)
  9095. # GUI feedback
  9096. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9097. def open_config_file(self, filename, run_from_arg=None):
  9098. """
  9099. Loads a config file from the specified file.
  9100. :param filename: Name of the file from which to load.
  9101. :type filename: str
  9102. :return: None
  9103. """
  9104. App.log.debug("Opening config file: " + filename)
  9105. if run_from_arg:
  9106. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9107. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9108. _("Opening FlatCAM Config file.")),
  9109. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9110. color=QtGui.QColor("gray"))
  9111. # # add the tab if it was closed
  9112. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9113. # # first clear previous text in text editor (if any)
  9114. # self.ui.text_editor_tab.code_editor.clear()
  9115. #
  9116. # # Switch plot_area to CNCJob tab
  9117. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9118. # close the Code editor if already open
  9119. if self.toggle_codeeditor:
  9120. self.on_toggle_code_editor()
  9121. self.on_toggle_code_editor()
  9122. try:
  9123. if filename:
  9124. f = QtCore.QFile(filename)
  9125. if f.open(QtCore.QIODevice.ReadOnly):
  9126. stream = QtCore.QTextStream(f)
  9127. code_edited = stream.readAll()
  9128. self.text_editor_tab.code_editor.setPlainText(code_edited)
  9129. f.close()
  9130. except IOError:
  9131. App.log.error("Failed to open config file: %s" % filename)
  9132. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9133. (_("Failed to open config file"), filename))
  9134. return
  9135. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9136. """
  9137. Loads a project from the specified file.
  9138. 1) Loads and parses file
  9139. 2) Registers the file as recently opened.
  9140. 3) Calls on_file_new()
  9141. 4) Updates options
  9142. 5) Calls new_object() with the object's from_dict() as init method.
  9143. 6) Calls plot_all() if plot=True
  9144. :param filename: Name of the file from which to load.
  9145. :type filename: str
  9146. :param run_from_arg: True if run for arguments
  9147. :param plot: If True plot all objects in the project
  9148. :param cli: run from command line
  9149. :return: None
  9150. """
  9151. App.log.debug("Opening project: " + filename)
  9152. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9153. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9154. if cli is None:
  9155. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9156. if run_from_arg:
  9157. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9158. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9159. _("Opening FlatCAM Project file.")),
  9160. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9161. color=QtGui.QColor("gray"))
  9162. # Open and parse an uncompressed Project file
  9163. try:
  9164. f = open(filename, 'r')
  9165. except IOError:
  9166. App.log.error("Failed to open project file: %s" % filename)
  9167. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9168. (_("Failed to open project file"), filename))
  9169. return
  9170. try:
  9171. d = json.load(f, object_hook=dict2obj)
  9172. except Exception as e:
  9173. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9174. (filename, str(e)))
  9175. f.close()
  9176. # Open and parse a compressed Project file
  9177. try:
  9178. with lzma.open(filename) as f:
  9179. file_content = f.read().decode('utf-8')
  9180. d = json.loads(file_content, object_hook=dict2obj)
  9181. except Exception as e:
  9182. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9183. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9184. (_("Failed to open project file"), filename))
  9185. return
  9186. # Clear the current project
  9187. # # NOT THREAD SAFE # ##
  9188. if run_from_arg is True:
  9189. pass
  9190. elif cli is True:
  9191. self.delete_selection_shape()
  9192. else:
  9193. self.on_file_new()
  9194. # Project options
  9195. self.options.update(d['options'])
  9196. self.project_filename = filename
  9197. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9198. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9199. if cli is None:
  9200. self.set_screen_units(self.options["units"])
  9201. # Re create objects
  9202. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9203. for obj in d['objs']:
  9204. def obj_init(obj_inst, app_inst):
  9205. obj_inst.from_dict(obj)
  9206. App.log.debug("Recreating from opened project an %s object: %s" %
  9207. (obj['kind'].capitalize(), obj['options']['name']))
  9208. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9209. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9210. if cli is None:
  9211. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9212. obj['kind'].upper(),
  9213. obj['options']['name']
  9214. )
  9215. )
  9216. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9217. self.inform.emit('[success] %s: %s' %
  9218. (_("Project loaded from"), filename))
  9219. self.should_we_save = False
  9220. self.file_opened.emit("project", filename)
  9221. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9222. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9223. if cli is None:
  9224. self.set_ui_title(name=self.project_filename)
  9225. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9226. def propagate_defaults(self, silent=False):
  9227. """
  9228. This method is used to set default values in classes. It's
  9229. an alternative to project options but allows the use
  9230. of values invisible to the user.
  9231. :return: None
  9232. """
  9233. if silent is False:
  9234. self.log.debug("propagate_defaults()")
  9235. # Which objects to update the given parameters.
  9236. routes = {
  9237. "global_zdownrate": CNCjob,
  9238. "excellon_zeros": Excellon,
  9239. "excellon_format_upper_in": Excellon,
  9240. "excellon_format_lower_in": Excellon,
  9241. "excellon_format_upper_mm": Excellon,
  9242. "excellon_format_lower_mm": Excellon,
  9243. "excellon_units": Excellon,
  9244. "gerber_use_buffer_for_union": Gerber,
  9245. "geometry_multidepth": Geometry
  9246. }
  9247. for param in routes:
  9248. if param in routes[param].defaults:
  9249. try:
  9250. routes[param].defaults[param] = self.defaults[param]
  9251. if silent is False:
  9252. self.log.debug(" " + param + " OK")
  9253. except KeyError:
  9254. if silent is False:
  9255. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9256. else:
  9257. # Try extracting the name:
  9258. # classname_param here is param in the object
  9259. if param.find(routes[param].__name__.lower() + "_") == 0:
  9260. p = param[len(routes[param].__name__) + 1:]
  9261. if p in routes[param].defaults:
  9262. routes[param].defaults[p] = self.defaults[param]
  9263. if silent is False:
  9264. self.log.debug(" " + param + " OK!")
  9265. def plot_all(self, zoom=True):
  9266. """
  9267. Re-generates all plots from all objects.
  9268. :return: None
  9269. """
  9270. self.log.debug("Plot_all()")
  9271. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9272. for obj in self.collection.get_list():
  9273. def worker_task(obj):
  9274. with self.proc_container.new("Plotting"):
  9275. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9276. if zoom:
  9277. self.object_plotted.emit(obj)
  9278. # Send to worker
  9279. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9280. def register_folder(self, filename):
  9281. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9282. def register_save_folder(self, filename):
  9283. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9284. def set_progress_bar(self, percentage, text=""):
  9285. self.ui.progress_bar.setValue(int(percentage))
  9286. def setup_shell(self):
  9287. """
  9288. Creates shell functions. Runs once at startup.
  9289. :return: None
  9290. """
  9291. self.log.debug("setup_shell()")
  9292. def shelp(p=None):
  9293. if not p:
  9294. return _("Available commands:\n") + \
  9295. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9296. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9297. if p not in commands:
  9298. return "Unknown command: %s" % p
  9299. return commands[p]["help"]
  9300. # --- Migrated to new architecture ---
  9301. # def options(name):
  9302. # ops = self.collection.get_by_name(str(name)).options
  9303. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9304. def h(*args):
  9305. """
  9306. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9307. and standalone parameters into list.
  9308. """
  9309. kwa = {}
  9310. a = []
  9311. n = len(args)
  9312. name = None
  9313. for i in range(n):
  9314. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9315. if match:
  9316. assert name is None
  9317. name = match.group(1)
  9318. continue
  9319. if name is None:
  9320. a.append(args[i])
  9321. else:
  9322. kwa[name] = args[i]
  9323. name = None
  9324. return a, kwa
  9325. @contextmanager
  9326. def wait_signal(signal, timeout=10000):
  9327. """
  9328. Block loop until signal emitted, timeout (ms) elapses
  9329. or unhandled exception happens in a thread.
  9330. :param timeout: time after which the loop is exited
  9331. :param signal: Signal to wait for.
  9332. """
  9333. loop = QtCore.QEventLoop()
  9334. # Normal termination
  9335. signal.connect(loop.quit)
  9336. # Termination by exception in thread
  9337. self.thread_exception.connect(loop.quit)
  9338. status = {'timed_out': False}
  9339. def report_quit():
  9340. status['timed_out'] = True
  9341. loop.quit()
  9342. yield
  9343. # Temporarily change how exceptions are managed.
  9344. oeh = sys.excepthook
  9345. ex = []
  9346. def except_hook(type_, value, traceback_):
  9347. ex.append(value)
  9348. oeh(type_, value, traceback_)
  9349. sys.excepthook = except_hook
  9350. # Terminate on timeout
  9351. if timeout is not None:
  9352. QtCore.QTimer.singleShot(timeout, report_quit)
  9353. # # ## Block ## ##
  9354. loop.exec_()
  9355. # Restore exception management
  9356. sys.excepthook = oeh
  9357. if ex:
  9358. self.raiseTclError(str(ex[0]))
  9359. if status['timed_out']:
  9360. raise Exception('Timed out!')
  9361. def make_docs():
  9362. output = ''
  9363. import collections
  9364. od = collections.OrderedDict(sorted(commands.items()))
  9365. for cmd_, val in od.items():
  9366. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9367. t = val['help']
  9368. usage_i = t.find('>')
  9369. if usage_i < 0:
  9370. expl = t
  9371. output += expl + '\n\n'
  9372. continue
  9373. expl = t[:usage_i - 1]
  9374. output += expl + '\n\n'
  9375. end_usage_i = t[usage_i:].find('\n')
  9376. if end_usage_i < 0:
  9377. end_usage_i = len(t[usage_i:])
  9378. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9379. else:
  9380. extras = t[usage_i+end_usage_i+1:]
  9381. parts = [s.strip() for s in extras.split('\n')]
  9382. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9383. for p in parts:
  9384. output += ' ' + p + '\n\n'
  9385. return output
  9386. '''
  9387. Howto implement TCL shell commands:
  9388. All parameters passed to command should be possible to set as None and test it afterwards.
  9389. This is because we need to see error caused in tcl,
  9390. if None value as default parameter is not allowed TCL will return empty error.
  9391. Use:
  9392. def mycommand(name=None,...):
  9393. Test it like this:
  9394. if name is None:
  9395. self.raise_tcl_error('Argument name is missing.')
  9396. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9397. otherwise we will miss it and processing will silently continue.
  9398. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9399. which is catched in exec_command and displayed in TCL shell console with red background.
  9400. Error in console is displayed with TCL trace.
  9401. This behavior works only within main thread,
  9402. errors with promissed tasks can be catched and detected only with log.
  9403. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9404. TCL shell.
  9405. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9406. '''
  9407. commands = {
  9408. 'help': {
  9409. 'fcn': shelp,
  9410. 'help': _("Shows list of commands.")
  9411. },
  9412. }
  9413. # Import/overwrite tcl commands as objects of TclCommand descendants
  9414. # This modifies the variable 'commands'.
  9415. tclCommands.register_all_commands(self, commands)
  9416. # Add commands to the tcl interpreter
  9417. for cmd in commands:
  9418. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9419. # Make the tcl puts function return instead of print to stdout
  9420. self.tcl.eval('''
  9421. rename puts original_puts
  9422. proc puts {args} {
  9423. if {[llength $args] == 1} {
  9424. return "[lindex $args 0]"
  9425. } else {
  9426. eval original_puts $args
  9427. }
  9428. }
  9429. ''')
  9430. def setup_recent_items(self):
  9431. # TODO: Move this to constructor
  9432. icons = {
  9433. "gerber": "share/flatcam_icon16.png",
  9434. "excellon": "share/drill16.png",
  9435. 'geometry': "share/geometry16.png",
  9436. "cncjob": "share/cnc16.png",
  9437. "script": "share/script_new24.png",
  9438. "document": "share/notes16_1.png",
  9439. "project": "share/project16.png",
  9440. "svg": "share/geometry16.png",
  9441. "dxf": "share/dxf16.png",
  9442. "pdf": "share/pdf32.png",
  9443. "image": "share/image16.png"
  9444. }
  9445. openers = {
  9446. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9447. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9448. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9449. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9450. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9451. "document": None,
  9452. 'project': self.open_project,
  9453. 'svg': self.import_svg,
  9454. 'dxf': self.import_dxf,
  9455. 'image': self.image_tool.import_image,
  9456. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9457. }
  9458. # Open recent file for files
  9459. try:
  9460. f = open(self.data_path + '/recent.json')
  9461. except IOError:
  9462. App.log.error("Failed to load recent item list.")
  9463. self.inform.emit('[ERROR_NOTCL] %s' %
  9464. _("Failed to load recent item list."))
  9465. return
  9466. try:
  9467. self.recent = json.load(f)
  9468. except json.scanner.JSONDecodeError:
  9469. App.log.error("Failed to parse recent item list.")
  9470. self.inform.emit('[ERROR_NOTCL] %s' %
  9471. _("Failed to parse recent item list."))
  9472. f.close()
  9473. return
  9474. f.close()
  9475. # Open recent file for projects
  9476. try:
  9477. fp = open(self.data_path + '/recent_projects.json')
  9478. except IOError:
  9479. App.log.error("Failed to load recent project item list.")
  9480. self.inform.emit('[ERROR_NOTCL] %s' %
  9481. _("Failed to load recent projects item list."))
  9482. return
  9483. try:
  9484. self.recent_projects = json.load(fp)
  9485. except json.scanner.JSONDecodeError:
  9486. App.log.error("Failed to parse recent project item list.")
  9487. self.inform.emit('[ERROR_NOTCL] %s' %
  9488. _("Failed to parse recent project item list."))
  9489. fp.close()
  9490. return
  9491. fp.close()
  9492. # Closure needed to create callbacks in a loop.
  9493. # Otherwise late binding occurs.
  9494. def make_callback(func, fname):
  9495. def opener():
  9496. func(fname)
  9497. return opener
  9498. def reset_recent_files():
  9499. # Reset menu
  9500. self.ui.recent.clear()
  9501. self.recent = []
  9502. try:
  9503. ff = open(self.data_path + '/recent.json', 'w')
  9504. except IOError:
  9505. App.log.error("Failed to open recent items file for writing.")
  9506. return
  9507. json.dump(self.recent, ff)
  9508. def reset_recent_projects():
  9509. # Reset menu
  9510. self.ui.recent_projects.clear()
  9511. self.recent_projects = []
  9512. try:
  9513. fp = open(self.data_path + '/recent_projects.json', 'w')
  9514. except IOError:
  9515. App.log.error("Failed to open recent projects items file for writing.")
  9516. return
  9517. json.dump(self.recent, fp)
  9518. # Reset menu
  9519. self.ui.recent.clear()
  9520. self.ui.recent_projects.clear()
  9521. # Create menu items for projects
  9522. for recent in self.recent_projects:
  9523. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9524. if recent['kind'] == 'project':
  9525. try:
  9526. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9527. # Attach callback
  9528. o = make_callback(openers[recent["kind"]], recent['filename'])
  9529. action.triggered.connect(o)
  9530. self.ui.recent_projects.addAction(action)
  9531. except KeyError:
  9532. App.log.error("Unsupported file type: %s" % recent["kind"])
  9533. # Last action in Recent Files menu is one that Clear the content
  9534. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent projects")), self)
  9535. clear_action_proj.triggered.connect(reset_recent_projects)
  9536. self.ui.recent_projects.addSeparator()
  9537. self.ui.recent_projects.addAction(clear_action_proj)
  9538. # Create menu items for files
  9539. for recent in self.recent:
  9540. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9541. if recent['kind'] != 'project':
  9542. try:
  9543. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9544. # Attach callback
  9545. o = make_callback(openers[recent["kind"]], recent['filename'])
  9546. action.triggered.connect(o)
  9547. self.ui.recent.addAction(action)
  9548. except KeyError:
  9549. App.log.error("Unsupported file type: %s" % recent["kind"])
  9550. # Last action in Recent Files menu is one that Clear the content
  9551. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9552. clear_action.triggered.connect(reset_recent_files)
  9553. self.ui.recent.addSeparator()
  9554. self.ui.recent.addAction(clear_action)
  9555. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9556. # self.ui.menufilerecent.set_submenu(recent_menu)
  9557. # recent_menu.show_all()
  9558. # self.ui.recent.show()
  9559. self.log.debug("Recent items list has been populated.")
  9560. def setup_component_editor(self):
  9561. # label = QtWidgets.QLabel("Choose an item from Project")
  9562. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9563. sel_title = QtWidgets.QTextEdit(
  9564. _('<b>Shortcut Key List</b>'))
  9565. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9566. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9567. settings = QSettings("Open Source", "FlatCAM")
  9568. if settings.contains("notebook_font_size"):
  9569. fsize = settings.value('notebook_font_size', type=int)
  9570. else:
  9571. fsize = 12
  9572. tsize = fsize + int(fsize / 2)
  9573. # selected_text = (_('''
  9574. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9575. #
  9576. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9577. # The normal flow when working in FlatCAM is the following:</span></p>
  9578. #
  9579. # <ol>
  9580. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9581. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9582. # even dragging and dropping the files on the GUI.<br />
  9583. # <br />
  9584. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9585. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9586. # &nbsp;</li>
  9587. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9588. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9589. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9590. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9591. # <br />
  9592. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9593. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9594. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9595. # it even if it was out of focus.<br />
  9596. # <br />
  9597. # You can change the parameters in this screen and the flow direction is like this:<br />
  9598. # <br />
  9599. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9600. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9601. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9602. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9603. # </ol>
  9604. #
  9605. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9606. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9607. # <strong>F3</strong>.</span></p>
  9608. #
  9609. # ''').format(fsize=fsize, tsize=tsize))
  9610. selected_text = '''
  9611. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9612. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9613. {s1}</span></p>
  9614. <ol>
  9615. <li><span style="font-size:{fsize}px">{s2}<br />
  9616. <br />
  9617. {s3}</span><br />
  9618. &nbsp;</li>
  9619. <li><span style="font-size:{fsize}px">{s4}<br />
  9620. &nbsp;</li>
  9621. <br />
  9622. <li><span style="font-size:{fsize}px">{s5}<br />
  9623. &nbsp;</li>
  9624. <br />
  9625. <li><span style="font-size:{fsize}px">{s6}<br />
  9626. <br />
  9627. {s7}</span></li>
  9628. </ol>
  9629. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9630. '''.format(
  9631. title=_("Selected Tab - Choose an Item from Project Tab"),
  9632. subtitle=_("Details"),
  9633. s1=_("The normal flow when working in FlatCAM is the following:"),
  9634. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9635. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9636. "files on the GUI."),
  9637. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9638. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9639. "actions offered within the app."),
  9640. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9641. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9642. "SELECTED TAB will be updated with the object properties according to its kind: "
  9643. "Gerber, Excellon, Geometry or CNCJob object."),
  9644. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9645. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9646. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9647. "the SELECTED TAB and populate it even if it was out of focus."),
  9648. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9649. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9650. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9651. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9652. "(again, done in SELECTED TAB) --> Save GCode."),
  9653. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9654. "or through its own key shortcut: <b>F3</b>."),
  9655. tsize=tsize,
  9656. fsize=fsize
  9657. )
  9658. sel_title.setText(selected_text)
  9659. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9660. self.ui.selected_scroll_area.setWidget(sel_title)
  9661. def setup_obj_classes(self):
  9662. """
  9663. Sets up application specifics on the FlatCAMObj class.
  9664. :return: None
  9665. """
  9666. FlatCAMObj.app = self
  9667. ObjectCollection.app = self
  9668. Gerber.app = self
  9669. Excellon.app = self
  9670. Geometry.app = self
  9671. CNCjob.app = self
  9672. FCProcess.app = self
  9673. FCProcessContainer.app = self
  9674. def version_check(self):
  9675. """
  9676. Checks for the latest version of the program. Alerts the
  9677. user if theirs is outdated. This method is meant to be run
  9678. in a separate thread.
  9679. :return: None
  9680. """
  9681. self.log.debug("version_check()")
  9682. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9683. full_url = App.version_url + \
  9684. "?s=" + str(self.defaults['global_serial']) + \
  9685. "&v=" + str(self.version) + \
  9686. "&os=" + str(self.os) + \
  9687. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9688. else:
  9689. # no_stats dict; just so it won't break things on website
  9690. no_ststs_dict = {}
  9691. no_ststs_dict["global_ststs"] = {}
  9692. full_url = App.version_url + \
  9693. "?s=" + str(self.defaults['global_serial']) + \
  9694. "&v=" + str(self.version) + \
  9695. "&os=" + str(self.os) + \
  9696. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9697. App.log.debug("Checking for updates @ %s" % full_url)
  9698. # ## Get the data
  9699. try:
  9700. f = urllib.request.urlopen(full_url)
  9701. except Exception:
  9702. # App.log.warning("Failed checking for latest version. Could not connect.")
  9703. self.log.warning("Failed checking for latest version. Could not connect.")
  9704. self.inform.emit('[WARNING_NOTCL] %s' %
  9705. _("Failed checking for latest version. Could not connect."))
  9706. return
  9707. try:
  9708. data = json.load(f)
  9709. except Exception as e:
  9710. App.log.error("Could not parse information about latest version.")
  9711. self.inform.emit('[ERROR_NOTCL] %s' %
  9712. _("Could not parse information about latest version."))
  9713. App.log.debug("json.load(): %s" % str(e))
  9714. f.close()
  9715. return
  9716. f.close()
  9717. # ## Latest version?
  9718. if self.version >= data["version"]:
  9719. App.log.debug("FlatCAM is up to date!")
  9720. self.inform.emit('[success] %s' %
  9721. _("FlatCAM is up to date!"))
  9722. return
  9723. App.log.debug("Newer version available.")
  9724. self.message.emit(
  9725. _("Newer Version Available"),
  9726. _("There is a newer version of FlatCAM available for download:\n\n") +
  9727. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9728. _("info")
  9729. )
  9730. def on_plotcanvas_setup(self, container=None):
  9731. """
  9732. This is doing the setup for the plot area (VisPy canvas)
  9733. :param container: widget where to install the canvas
  9734. :return: None
  9735. """
  9736. if container:
  9737. plot_container = container
  9738. else:
  9739. plot_container = self.ui.right_layout
  9740. if self.is_legacy is False:
  9741. self.plotcanvas = PlotCanvas(plot_container, self)
  9742. else:
  9743. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9744. # So it can receive key presses
  9745. self.plotcanvas.native.setFocus()
  9746. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9747. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9748. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9749. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  9750. # Keys over plot enabled
  9751. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9752. if self.defaults['global_cursor_type'] == 'small':
  9753. self.app_cursor = self.plotcanvas.new_cursor()
  9754. else:
  9755. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9756. if self.ui.grid_snap_btn.isChecked():
  9757. self.app_cursor.enabled = True
  9758. else:
  9759. self.app_cursor.enabled = False
  9760. if self.is_legacy is False:
  9761. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9762. else:
  9763. # will use the default Matplotlib axes
  9764. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9765. def on_zoom_fit(self, event):
  9766. """
  9767. Callback for zoom-out request. This can be either from the corresponding
  9768. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9769. with axes limits from the geometry bounds of all objects.
  9770. :param event: Ignored.
  9771. :return: None
  9772. """
  9773. if self.is_legacy is False:
  9774. self.plotcanvas.fit_view()
  9775. else:
  9776. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9777. width = xmax - xmin
  9778. height = ymax - ymin
  9779. xmin -= 0.05 * width
  9780. xmax += 0.05 * width
  9781. ymin -= 0.05 * height
  9782. ymax += 0.05 * height
  9783. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9784. def on_zoom_in(self):
  9785. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9786. def on_zoom_out(self):
  9787. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9788. def disable_all_plots(self):
  9789. self.report_usage("disable_all_plots()")
  9790. self.disable_plots(self.collection.get_list())
  9791. self.inform.emit('[success] %s' %
  9792. _("All plots disabled."))
  9793. def disable_other_plots(self):
  9794. self.report_usage("disable_other_plots()")
  9795. self.disable_plots(self.collection.get_non_selected())
  9796. self.inform.emit('[success] %s' %
  9797. _("All non selected plots disabled."))
  9798. def enable_all_plots(self):
  9799. self.report_usage("enable_all_plots()")
  9800. self.enable_plots(self.collection.get_list())
  9801. self.inform.emit('[success] %s' %
  9802. _("All plots enabled."))
  9803. def on_enable_sel_plots(self):
  9804. log.debug("App.on_enable_sel_plot()")
  9805. object_list = self.collection.get_selected()
  9806. self.enable_plots(objects=object_list)
  9807. self.inform.emit('[success] %s' %
  9808. _("Selected plots enabled..."))
  9809. def on_disable_sel_plots(self):
  9810. log.debug("App.on_disable_sel_plot()")
  9811. # self.inform.emit(_("Disabling plots ..."))
  9812. object_list = self.collection.get_selected()
  9813. self.disable_plots(objects=object_list)
  9814. self.inform.emit('[success] %s' %
  9815. _("Selected plots disabled..."))
  9816. def enable_plots(self, objects):
  9817. """
  9818. Disables plots
  9819. :param objects: list of Objects to be enabled
  9820. :return:
  9821. """
  9822. log.debug("Enabling plots ...")
  9823. # self.inform.emit(_("Working ..."))
  9824. for obj in objects:
  9825. if obj.options['plot'] is False:
  9826. obj.options.set_change_callback(lambda x: None)
  9827. obj.options['plot'] = True
  9828. obj.options.set_change_callback(obj.on_options_change)
  9829. def worker_task(objs):
  9830. with self.proc_container.new(_("Enabling plots ...")):
  9831. for obj in objs:
  9832. # obj.options['plot'] = True
  9833. if isinstance(obj, FlatCAMCNCjob):
  9834. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9835. else:
  9836. obj.plot(visible=True)
  9837. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9838. # self.plots_updated.emit()
  9839. def disable_plots(self, objects):
  9840. """
  9841. Disables plots
  9842. :param objects: list of Objects to be disabled
  9843. :return:
  9844. """
  9845. # if no objects selected then do nothing
  9846. if not self.collection.get_selected():
  9847. return
  9848. log.debug("Disabling plots ...")
  9849. # self.inform.emit(_("Working ..."))
  9850. for obj in objects:
  9851. if obj.options['plot'] is True:
  9852. obj.options.set_change_callback(lambda x: None)
  9853. obj.options['plot'] = False
  9854. obj.options.set_change_callback(obj.on_options_change)
  9855. try:
  9856. self.delete_selection_shape()
  9857. except Exception as e:
  9858. log.debug("App.disable_plots() --> %s" % str(e))
  9859. # self.plots_updated.emit()
  9860. def worker_task(objs):
  9861. with self.proc_container.new(_("Disabling plots ...")):
  9862. for obj in objs:
  9863. # obj.options['plot'] = True
  9864. if isinstance(obj, FlatCAMCNCjob):
  9865. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9866. else:
  9867. obj.plot(visible=False)
  9868. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9869. def toggle_plots(self, objects):
  9870. """
  9871. Toggle plots visibility
  9872. :param objects: list of Objects for which to be toggled the visibility
  9873. :return:
  9874. """
  9875. # if no objects selected then do nothing
  9876. if not self.collection.get_selected():
  9877. return
  9878. log.debug("Toggling plots ...")
  9879. self.inform.emit(_("Working ..."))
  9880. for obj in objects:
  9881. if obj.options['plot'] is False:
  9882. obj.options['plot'] = True
  9883. else:
  9884. obj.options['plot'] = False
  9885. self.plots_updated.emit()
  9886. def clear_plots(self):
  9887. objects = self.collection.get_list()
  9888. for obj in objects:
  9889. obj.clear(obj == objects[-1])
  9890. # Clear pool to free memory
  9891. self.clear_pool()
  9892. def generate_cnc_job(self, objects):
  9893. self.report_usage("generate_cnc_job()")
  9894. # for obj in objects:
  9895. # obj.generatecncjob()
  9896. for obj in objects:
  9897. obj.on_generatecnc_button_click()
  9898. def save_project(self, filename, quit_action=False, silent=False):
  9899. """
  9900. Saves the current project to the specified file.
  9901. :param filename: Name of the file in which to save.
  9902. :type filename: str
  9903. :param quit_action: if the project saving will be followed by an app quit; boolean
  9904. :param silent: if True will not display status messages
  9905. :return: None
  9906. """
  9907. self.log.debug("save_project()")
  9908. self.save_in_progress = True
  9909. with self.proc_container.new(_("Saving FlatCAM Project")):
  9910. # Capture the latest changes
  9911. # Current object
  9912. try:
  9913. self.collection.get_active().read_form()
  9914. except Exception as e:
  9915. self.log.debug("There was no active object. %s" % str(e))
  9916. pass
  9917. # Serialize the whole project
  9918. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9919. "options": self.options,
  9920. "version": self.version}
  9921. if self.defaults["global_save_compressed"] is True:
  9922. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9923. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9924. # # Write
  9925. f.write(g)
  9926. self.inform.emit('[success] %s: %s' %
  9927. (_("Project saved to"), filename))
  9928. else:
  9929. # Open file
  9930. try:
  9931. f = open(filename, 'w')
  9932. except IOError:
  9933. App.log.error("Failed to open file for saving: %s", filename)
  9934. return
  9935. # Write
  9936. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9937. f.close()
  9938. # verification of the saved project
  9939. # Open and parse
  9940. try:
  9941. saved_f = open(filename, 'r')
  9942. except IOError:
  9943. if silent is False:
  9944. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9945. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9946. )
  9947. return
  9948. try:
  9949. saved_d = json.load(saved_f, object_hook=dict2obj)
  9950. except Exception:
  9951. if silent is False:
  9952. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9953. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9954. )
  9955. f.close()
  9956. return
  9957. saved_f.close()
  9958. if silent is False:
  9959. if 'version' in saved_d:
  9960. self.inform.emit('[success] %s: %s' %
  9961. (_("Project saved to"), filename))
  9962. else:
  9963. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9964. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9965. )
  9966. tb_settings = QSettings("Open Source", "FlatCAM")
  9967. lock_state = self.ui.lock_action.isChecked()
  9968. tb_settings.setValue('toolbar_lock', lock_state)
  9969. # This will write the setting to the platform specific storage.
  9970. del tb_settings
  9971. # if quit:
  9972. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9973. # t.start()
  9974. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9975. def start_delayed_quit(self, delay, filename, should_quit=None):
  9976. """
  9977. :param delay: period of checking if project file size is more than zero; in seconds
  9978. :param filename: the name of the project file to be checked periodically for size more than zero
  9979. :param should_quit: if the task finished will be followed by an app quit; boolean
  9980. :return:
  9981. """
  9982. to_quit = should_quit
  9983. self.save_timer = QtCore.QTimer()
  9984. self.save_timer.setInterval(delay)
  9985. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9986. self.save_timer.start()
  9987. def check_project_file_size(self, filename, should_quit=None):
  9988. """
  9989. :param filename: the name of the project file to be checked periodically for size more than zero
  9990. :param should_quit: will quit the app if True; boolean
  9991. :return:
  9992. """
  9993. try:
  9994. if os.stat(filename).st_size > 0:
  9995. self.save_in_progress = False
  9996. self.save_timer.stop()
  9997. if should_quit:
  9998. self.app_quit.emit()
  9999. except Exception:
  10000. traceback.print_exc()
  10001. def on_plotarea_tab_closed(self, tab_idx):
  10002. widget = self.ui.plot_tab_area.widget(tab_idx)
  10003. if widget is not None:
  10004. widget.deleteLater()
  10005. self.ui.plot_tab_area.removeTab(tab_idx)
  10006. def on_options_app2project(self):
  10007. """
  10008. Callback for Options->Transfer Options->App=>Project. Copies options
  10009. from application defaults to project defaults.
  10010. :return: None
  10011. """
  10012. self.report_usage("on_options_app2project")
  10013. self.defaults_read_form()
  10014. self.options.update(self.defaults)
  10015. # self.options_write_form()
  10016. class ArgsThread(QtCore.QObject):
  10017. open_signal = pyqtSignal(list)
  10018. start = pyqtSignal()
  10019. if sys.platform == 'win32':
  10020. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  10021. else:
  10022. address = ('/tmp/testipc', 'AF_UNIX')
  10023. def __init__(self):
  10024. super(ArgsThread, self).__init__()
  10025. self.start.connect(self.run)
  10026. def my_loop(self, address):
  10027. try:
  10028. listener = Listener(*address)
  10029. while True:
  10030. conn = listener.accept()
  10031. self.serve(conn)
  10032. except socket.error:
  10033. conn = Client(*address)
  10034. conn.send(sys.argv)
  10035. conn.send('close')
  10036. # close the current instance only if there are args
  10037. if len(sys.argv) > 1:
  10038. sys.exit()
  10039. def serve(self, conn):
  10040. while True:
  10041. msg = conn.recv()
  10042. if msg == 'close':
  10043. break
  10044. self.open_signal.emit(msg)
  10045. conn.close()
  10046. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10047. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10048. @pyqtSlot()
  10049. def run(self):
  10050. self.my_loop(self.address)
  10051. class GracefulException(Exception):
  10052. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  10053. def __init__(self):
  10054. super().__init__()
  10055. def __str__(self):
  10056. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  10057. # end of file