FlatCAMApp.py 553 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094
  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 getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Diverse
  37. from FlatCAMCommon import LoudDict, color_variant
  38. from FlatCAMBookmark import BookmarkManager
  39. from FlatCAMDB import ToolsDB2
  40. from vispy.gloo.util import _screenshot
  41. from vispy.io import write_png
  42. # FlatCAM Objects
  43. from defaults import FlatCAMDefaults
  44. from flatcamObjects.ObjectCollection import *
  45. from flatcamObjects.FlatCAMObj import FlatCAMObj
  46. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  47. from flatcamObjects.FlatCAMDocument import DocumentObject
  48. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  49. from flatcamObjects.FlatCAMGeometry import GeometryObject
  50. from flatcamObjects.FlatCAMGerber import GerberObject
  51. from flatcamObjects.FlatCAMScript import ScriptObject
  52. # FlatCAM Parsing files
  53. from flatcamParsers.ParseExcellon import Excellon
  54. from flatcamParsers.ParseGerber import Gerber
  55. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  56. # FlatCAM GUI
  57. from flatcamGUI.PlotCanvas import *
  58. from flatcamGUI.PlotCanvasLegacy import *
  59. from flatcamGUI.FlatCAMGUI import *
  60. from flatcamGUI.GUIElements import FCFileSaveDialog
  61. # FlatCAM Pre-processors
  62. from FlatCAMPostProc import load_preprocessors
  63. # FlatCAM Editors
  64. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  65. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  66. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  67. from flatcamEditors.FlatCAMTextEditor import TextEditor
  68. from flatcamParsers.ParseHPGL2 import HPGL2
  69. # FlatCAM Workers
  70. from FlatCAMProcess import *
  71. from FlatCAMWorkerStack import WorkerStack
  72. # FlatCAM Tools
  73. from flatcamTools import *
  74. # FlatCAM Translation
  75. import gettext
  76. import FlatCAMTranslation as fcTranslate
  77. import builtins
  78. if sys.platform == 'win32':
  79. import winreg
  80. fcTranslate.apply_language('strings')
  81. if '_' not in builtins.__dict__:
  82. _ = gettext.gettext
  83. class App(QtCore.QObject):
  84. """
  85. The main application class. The constructor starts the GUI.
  86. """
  87. # ###############################################################################################################
  88. # ########################################## App ################################################################
  89. # ###############################################################################################################
  90. # ###############################################################################################################
  91. # ######################################### LOGGING #############################################################
  92. # ###############################################################################################################
  93. log = logging.getLogger('base')
  94. log.setLevel(logging.DEBUG)
  95. # log.setLevel(logging.WARNING)
  96. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  97. handler = logging.StreamHandler()
  98. handler.setFormatter(formatter)
  99. log.addHandler(handler)
  100. # ###############################################################################################################
  101. # #################################### Get Cmd Line Options #####################################################
  102. # ###############################################################################################################
  103. cmd_line_shellfile = ''
  104. cmd_line_shellvar = ''
  105. cmd_line_headless = None
  106. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  107. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  108. "FlatCam.py --headless=1"
  109. try:
  110. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  111. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  112. "shellvar=",
  113. "headless=",
  114. "multiprocessing-fork="])
  115. except getopt.GetoptError:
  116. print(cmd_line_help)
  117. sys.exit(2)
  118. for opt, arg in cmd_line_options:
  119. if opt == '-h':
  120. print(cmd_line_help)
  121. sys.exit()
  122. elif opt == '--shellfile':
  123. cmd_line_shellfile = arg
  124. elif opt == '--shellvar':
  125. cmd_line_shellvar = arg
  126. elif opt == '--headless':
  127. try:
  128. cmd_line_headless = eval(arg)
  129. except NameError:
  130. pass
  131. # ###############################################################################################################
  132. # ################################### Version and VERSION DATE ##################################################
  133. # ###############################################################################################################
  134. version = 8.992
  135. version_date = "2020/05/01"
  136. beta = True
  137. engine = '3D'
  138. # current date now
  139. date = str(datetime.today()).rpartition('.')[0]
  140. date = ''.join(c for c in date if c not in ':-')
  141. date = date.replace(' ', '_')
  142. # ###############################################################################################################
  143. # ############################################ URLS's ###########################################################
  144. # ###############################################################################################################
  145. # URL for update checks and statistics
  146. version_url = "http://flatcam.org/version"
  147. # App URL
  148. app_url = "http://flatcam.org"
  149. # Manual URL
  150. manual_url = "http://flatcam.org/manual/index.html"
  151. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  152. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  153. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  154. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  155. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  156. # this variable will hold the project status
  157. # if True it will mean that the project was modified and not saved
  158. should_we_save = False
  159. # flag is True if saving action has been triggered
  160. save_in_progress = False
  161. # ###############################################################################################################
  162. # ####################################### APP Signals ######################################################
  163. # ###############################################################################################################
  164. # Inform the user
  165. # Handled by:
  166. # * App.info() --> Print on the status bar
  167. inform = QtCore.pyqtSignal(str)
  168. app_quit = QtCore.pyqtSignal()
  169. # General purpose background task
  170. worker_task = QtCore.pyqtSignal(dict)
  171. # File opened
  172. # Handled by:
  173. # * register_folder()
  174. # * register_recent()
  175. # Note: Setting the parameters to unicode does not seem
  176. # to have an effect. Then are received as Qstring
  177. # anyway.
  178. # File type and filename
  179. file_opened = QtCore.pyqtSignal(str, str)
  180. # File type and filename
  181. file_saved = QtCore.pyqtSignal(str, str)
  182. # Percentage of progress
  183. progress = QtCore.pyqtSignal(int)
  184. plots_updated = QtCore.pyqtSignal()
  185. # Emitted by new_object() and passes the new object as argument, plot flag.
  186. # on_object_created() adds the object to the collection, plots on appropriate flag
  187. # and emits new_object_available.
  188. object_created = QtCore.pyqtSignal(object, bool, bool)
  189. # Emitted when a object has been changed (like scaled, mirrored)
  190. object_changed = QtCore.pyqtSignal(object)
  191. # Emitted after object has been plotted.
  192. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  193. object_plotted = QtCore.pyqtSignal(object)
  194. # Emitted when a new object has been added or deleted from/to the collection
  195. object_status_changed = QtCore.pyqtSignal(object, str, str)
  196. message = QtCore.pyqtSignal(str, str, str)
  197. # Emmited when shell command is finished(one command only)
  198. shell_command_finished = QtCore.pyqtSignal(object)
  199. # Emitted when multiprocess pool has been recreated
  200. pool_recreated = QtCore.pyqtSignal(object)
  201. # Emitted when an unhandled exception happens
  202. # in the worker task.
  203. thread_exception = QtCore.pyqtSignal(object)
  204. # used to signal that there are arguments for the app
  205. args_at_startup = QtCore.pyqtSignal(list)
  206. # a reusable signal to replot a list of objects
  207. # should be disconnected after use so it can be reused
  208. replot_signal = pyqtSignal(list)
  209. # signal emitted when jumping
  210. jump_signal = pyqtSignal(tuple)
  211. # signal emitted when jumping
  212. locate_signal = pyqtSignal(tuple, str)
  213. # close app signal
  214. close_app_signal = pyqtSignal()
  215. # will perform the cleanup operation after a Graceful Exit
  216. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  217. # graphic residues behind
  218. cleanup = pyqtSignal()
  219. def __init__(self, user_defaults=True):
  220. """
  221. Starts the application.
  222. :return: app
  223. :rtype: App
  224. """
  225. App.log.info("FlatCAM Starting...")
  226. self.main_thread = QtWidgets.QApplication.instance().thread()
  227. # ############################################################################################################
  228. # ################# Setup the listening thread for another instance launching with args ######################
  229. # ############################################################################################################
  230. if sys.platform == 'win32' or sys.platform == 'linux':
  231. # make sure the thread is stored by using a self. otherwise it's garbage collected
  232. self.th = QtCore.QThread()
  233. self.th.start(priority=QtCore.QThread.LowestPriority)
  234. self.new_launch = ArgsThread()
  235. self.new_launch.open_signal[list].connect(self.on_startup_args)
  236. self.new_launch.moveToThread(self.th)
  237. self.new_launch.start.emit()
  238. # ############################################################################################################
  239. # # ######################################## OS-specific #####################################################
  240. # ############################################################################################################
  241. portable = False
  242. # Folder for user settings.
  243. if sys.platform == 'win32':
  244. from win32comext.shell import shell, shellcon
  245. if platform.architecture()[0] == '32bit':
  246. App.log.debug("Win32!")
  247. else:
  248. App.log.debug("Win64!")
  249. # #######################################################################################################
  250. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  251. # #######################################################################################################
  252. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  253. try:
  254. with open(config_file, 'r'):
  255. pass
  256. except FileNotFoundError:
  257. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  258. try:
  259. with open(config_file, 'r') as f:
  260. try:
  261. for line in f:
  262. param = str(line).replace('\n', '').rpartition('=')
  263. if param[0] == 'portable':
  264. try:
  265. portable = eval(param[2])
  266. except NameError:
  267. portable = False
  268. if param[0] == 'headless':
  269. if param[2].lower() == 'true':
  270. self.cmd_line_headless = 1
  271. else:
  272. self.cmd_line_headless = None
  273. except Exception as e:
  274. log.debug('App.__init__() -->%s' % str(e))
  275. return
  276. except FileNotFoundError as e:
  277. log.debug(str(e))
  278. pass
  279. if portable is False:
  280. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  281. else:
  282. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  283. self.os = 'windows'
  284. else: # Linux/Unix/MacOS
  285. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  286. self.os = 'unix'
  287. # ############################################################################################################
  288. # ################################# Setup folders and files ##################################################
  289. # ############################################################################################################
  290. if not os.path.exists(self.data_path):
  291. os.makedirs(self.data_path)
  292. App.log.debug('Created data folder: ' + self.data_path)
  293. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  294. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  295. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  296. if not os.path.exists(self.preprocessorpaths):
  297. os.makedirs(self.preprocessorpaths)
  298. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  299. # create geo_tools_db.FlatDB file if there is none
  300. try:
  301. f = open(self.data_path + '/geo_tools_db.FlatDB')
  302. f.close()
  303. except IOError:
  304. App.log.debug('Creating empty geo_tool_db.FlatDB')
  305. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  306. json.dump({}, f)
  307. f.close()
  308. # create current_defaults.FlatConfig file if there is none
  309. try:
  310. f = open(self.data_path + '/current_defaults.FlatConfig')
  311. f.close()
  312. except IOError:
  313. App.log.debug('Creating empty current_defaults.FlatConfig')
  314. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  315. json.dump({}, f)
  316. f.close()
  317. # Write factory_defaults.FlatConfig file to disk
  318. FlatCAMDefaults.save_factory_defaults_file(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  319. # create a recent files json file if there is none
  320. try:
  321. f = open(self.data_path + '/recent.json')
  322. f.close()
  323. except IOError:
  324. App.log.debug('Creating empty recent.json')
  325. f = open(self.data_path + '/recent.json', 'w')
  326. json.dump([], f)
  327. f.close()
  328. # create a recent projects json file if there is none
  329. try:
  330. fp = open(self.data_path + '/recent_projects.json')
  331. fp.close()
  332. except IOError:
  333. App.log.debug('Creating empty recent_projects.json')
  334. fp = open(self.data_path + '/recent_projects.json', 'w')
  335. json.dump([], fp)
  336. fp.close()
  337. # Application directory. CHDIR to it. Otherwise, trying to load
  338. # GUI icons will fail as their path is relative.
  339. # This will fail under cx_freeze ...
  340. self.app_home = os.path.dirname(os.path.realpath(__file__))
  341. App.log.debug("Application path is " + self.app_home)
  342. App.log.debug("Started in " + os.getcwd())
  343. # cx_freeze workaround
  344. if os.path.isfile(self.app_home):
  345. self.app_home = os.path.dirname(self.app_home)
  346. os.chdir(self.app_home)
  347. # ############################################################################################################
  348. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  349. # ############################################################################################################
  350. self.fcDefaults = FlatCAMDefaults()
  351. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  352. if user_defaults:
  353. self.fcDefaults.load_defaults(filename=current_defaults_path)
  354. self.defaults = self.fcDefaults.defaults
  355. if self.defaults["global_gray_icons"] is False:
  356. self.resource_location = 'share'
  357. else:
  358. self.resource_location = 'share/dark_resources'
  359. if self.defaults['units'] == 'MM':
  360. self.decimals = int(self.defaults['decimals_metric'])
  361. else:
  362. self.decimals = int(self.defaults['decimals_inch'])
  363. self.current_units = self.defaults['units']
  364. # ###########################################################################################################
  365. # #################################### SETUP OBJECT CLASSES #################################################
  366. # ###########################################################################################################
  367. self.setup_obj_classes()
  368. # ###########################################################################################################
  369. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  370. # ###########################################################################################################
  371. self.pool = Pool()
  372. # ###########################################################################################################
  373. # ###################################### Setting the Splash Screen ##########################################
  374. # ###########################################################################################################
  375. splash_settings = QSettings("Open Source", "FlatCAM")
  376. if splash_settings.contains("splash_screen"):
  377. show_splash = splash_settings.value("splash_screen")
  378. else:
  379. splash_settings.setValue('splash_screen', 1)
  380. # This will write the setting to the platform specific storage.
  381. del splash_settings
  382. show_splash = 1
  383. if show_splash and self.cmd_line_headless != 1:
  384. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  385. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  386. # self.splash.setMask(splash_pix.mask())
  387. # move splashscreen to the current monitor
  388. desktop = QtWidgets.QApplication.desktop()
  389. screen = desktop.screenNumber(QtGui.QCursor.pos())
  390. current_screen_center = desktop.availableGeometry(screen).center()
  391. self.splash.move(current_screen_center - self.splash.rect().center())
  392. self.splash.show()
  393. self.splash.showMessage(_("FlatCAM is initializing ..."),
  394. alignment=Qt.AlignBottom | Qt.AlignLeft,
  395. color=QtGui.QColor("gray"))
  396. else:
  397. show_splash = 0
  398. # ###########################################################################################################
  399. # ######################################### Initialize GUI ##################################################
  400. # ###########################################################################################################
  401. # FlatCAM colors used in plotting
  402. self.FC_light_green = '#BBF268BF'
  403. self.FC_dark_green = '#006E20BF'
  404. self.FC_light_blue = '#a5a5ffbf'
  405. self.FC_dark_blue = '#0000ffbf'
  406. QtCore.QObject.__init__(self)
  407. self.ui = FlatCAMGUI(self)
  408. self.on_grid_snap_triggered(state=True)
  409. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  410. if theme_settings.contains("theme"):
  411. theme = theme_settings.value('theme', type=str)
  412. else:
  413. theme = 'white'
  414. if self.defaults["global_cursor_color_enabled"]:
  415. self.cursor_color_3D = self.defaults["global_cursor_color"]
  416. else:
  417. if theme == 'white':
  418. self.cursor_color_3D = 'black'
  419. else:
  420. self.cursor_color_3D = 'gray'
  421. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  422. self.ui.final_save.connect(self.final_save)
  423. # restore the toolbar view
  424. self.restore_toolbar_view()
  425. # restore the GUI geometry
  426. self.restore_main_win_geom()
  427. # set FlatCAM units in the Status bar
  428. self.set_screen_units(self.defaults['units'])
  429. # ###########################################################################################################
  430. # ########################################### AUTOSAVE SETUP ################################################
  431. # ###########################################################################################################
  432. self.block_autosave = False
  433. self.autosave_timer = QtCore.QTimer(self)
  434. self.save_project_auto_update()
  435. self.autosave_timer.timeout.connect(self.save_project_auto)
  436. # ###########################################################################################################
  437. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  438. # ###########################################################################################################
  439. # when adding entries here read the comments in the method found bellow named:
  440. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  441. self.defaults_form_fields = {
  442. # General App
  443. "decimals_inch": self.ui.general_defaults_form.general_app_group.precision_inch_entry,
  444. "decimals_metric": self.ui.general_defaults_form.general_app_group.precision_metric_entry,
  445. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  446. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  447. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  448. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  449. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  450. "global_systray_icon": self.ui.general_defaults_form.general_app_group.systray_cb,
  451. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  452. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  453. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  454. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  455. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  456. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  457. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  458. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  459. "global_autosave": self.ui.general_defaults_form.general_app_group.autosave_cb,
  460. "global_autosave_timeout": self.ui.general_defaults_form.general_app_group.autosave_entry,
  461. "global_tpdf_tmargin": self.ui.general_defaults_form.general_app_group.tmargin_entry,
  462. "global_tpdf_bmargin": self.ui.general_defaults_form.general_app_group.bmargin_entry,
  463. "global_tpdf_lmargin": self.ui.general_defaults_form.general_app_group.lmargin_entry,
  464. "global_tpdf_rmargin": self.ui.general_defaults_form.general_app_group.rmargin_entry,
  465. # General GUI Preferences
  466. "global_theme": self.ui.general_defaults_form.general_gui_group.theme_radio,
  467. "global_gray_icons": self.ui.general_defaults_form.general_gui_group.gray_icons_cb,
  468. "global_layout": self.ui.general_defaults_form.general_gui_group.layout_combo,
  469. "global_hover": self.ui.general_defaults_form.general_gui_group.hover_cb,
  470. "global_selection_shape": self.ui.general_defaults_form.general_gui_group.selection_cb,
  471. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  472. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  473. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  474. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  475. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  476. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  477. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  478. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  479. "global_project_autohide": self.ui.general_defaults_form.general_gui_group.project_autohide_cb,
  480. # General GUI Settings
  481. "global_gridx": self.ui.general_defaults_form.general_app_set_group.gridx_entry,
  482. "global_gridy": self.ui.general_defaults_form.general_app_set_group.gridy_entry,
  483. "global_snap_max": self.ui.general_defaults_form.general_app_set_group.snap_max_dist_entry,
  484. "global_workspace": self.ui.general_defaults_form.general_app_set_group.workspace_cb,
  485. "global_workspaceT": self.ui.general_defaults_form.general_app_set_group.wk_cb,
  486. "global_workspace_orientation": self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio,
  487. "global_cursor_type": self.ui.general_defaults_form.general_app_set_group.cursor_radio,
  488. "global_cursor_size": self.ui.general_defaults_form.general_app_set_group.cursor_size_entry,
  489. "global_cursor_width": self.ui.general_defaults_form.general_app_set_group.cursor_width_entry,
  490. "global_cursor_color_enabled": self.ui.general_defaults_form.general_app_set_group.mouse_cursor_color_cb,
  491. "global_cursor_color": self.ui.general_defaults_form.general_app_set_group.mouse_cursor_entry,
  492. "global_pan_button": self.ui.general_defaults_form.general_app_set_group.pan_button_radio,
  493. "global_mselect_key": self.ui.general_defaults_form.general_app_set_group.mselect_radio,
  494. "global_delete_confirmation": self.ui.general_defaults_form.general_app_set_group.delete_conf_cb,
  495. "global_open_style": self.ui.general_defaults_form.general_app_set_group.open_style_cb,
  496. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_set_group.toggle_tooltips_cb,
  497. "global_machinist_setting": self.ui.general_defaults_form.general_app_set_group.machinist_cb,
  498. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_set_group.bm_limit_spinner,
  499. "global_activity_icon": self.ui.general_defaults_form.general_app_set_group.activity_combo,
  500. # Gerber General
  501. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  502. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  503. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  504. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  505. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  506. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  507. "gerber_clean_apertures": self.ui.gerber_defaults_form.gerber_gen_group.gerber_clean_cb,
  508. "gerber_extra_buffering": self.ui.gerber_defaults_form.gerber_gen_group.gerber_extra_buffering,
  509. "gerber_plot_fill": self.ui.gerber_defaults_form.gerber_gen_group.pf_color_entry,
  510. "gerber_plot_line": self.ui.gerber_defaults_form.gerber_gen_group.pl_color_entry,
  511. # Gerber Options
  512. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  513. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  514. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  515. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  516. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  517. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  518. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  519. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  520. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  521. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  522. # Gerber Advanced Options
  523. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  524. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  525. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  526. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  527. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  528. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  529. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  530. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  531. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  532. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  533. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  534. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  535. # Gerber Export
  536. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  537. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  538. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  539. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  540. # Gerber Editor
  541. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  542. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  543. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  544. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  545. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  546. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  547. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  548. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  549. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  550. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  551. "gerber_editor_circ_angle":
  552. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  553. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  554. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  555. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  556. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  557. # Excellon General
  558. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  559. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  560. "excellon_format_upper_in":
  561. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  562. "excellon_format_lower_in":
  563. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  564. "excellon_format_upper_mm":
  565. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  566. "excellon_format_lower_mm":
  567. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  568. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  569. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  570. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  571. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  572. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  573. "excellon_plot_fill": self.ui.excellon_defaults_form.excellon_gen_group.fill_color_entry,
  574. "excellon_plot_line": self.ui.excellon_defaults_form.excellon_gen_group.line_color_entry,
  575. # Excellon Options
  576. "excellon_operation": self.ui.excellon_defaults_form.excellon_opt_group.operation_radio,
  577. "excellon_milling_type": self.ui.excellon_defaults_form.excellon_opt_group.milling_type_radio,
  578. "excellon_milling_dia": self.ui.excellon_defaults_form.excellon_opt_group.mill_dia_entry,
  579. "excellon_cutz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  580. "excellon_multidepth": self.ui.excellon_defaults_form.excellon_opt_group.mpass_cb,
  581. "excellon_depthperpass": self.ui.excellon_defaults_form.excellon_opt_group.maxdepth_entry,
  582. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  583. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.endz_entry,
  584. "excellon_endxy": self.ui.excellon_defaults_form.excellon_opt_group.endxy_entry,
  585. "excellon_feedrate_z": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_z_entry,
  586. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  587. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  588. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  589. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  590. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  591. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  592. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  593. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  594. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  595. # Excellon Advanced Options
  596. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  597. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  598. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  599. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  600. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  601. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  602. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  603. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  604. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  605. # Excellon Export
  606. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  607. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  608. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  609. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  610. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  611. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  612. # Excellon Editor
  613. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  614. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  615. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  616. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  617. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  618. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  619. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  620. "excellon_editor_circ_angle":
  621. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  622. # Excellon Slots
  623. "excellon_editor_slot_direction":
  624. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  625. "excellon_editor_slot_angle":
  626. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  627. "excellon_editor_slot_length":
  628. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  629. # Excellon Slots
  630. "excellon_editor_slot_array_size":
  631. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  632. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  633. "excellon_editor_slot_lin_pitch":
  634. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  635. "excellon_editor_slot_lin_angle":
  636. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  637. "excellon_editor_slot_circ_dir":
  638. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  639. "excellon_editor_slot_circ_angle":
  640. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  641. # Geometry General
  642. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  643. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  644. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  645. "geometry_plot_line": self.ui.geometry_defaults_form.geometry_gen_group.line_color_entry,
  646. # Geometry Options
  647. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  648. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  649. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  650. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.feedrate_z_entry,
  651. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  652. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  653. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  654. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  655. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  656. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  657. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.endz_entry,
  658. "geometry_endxy": self.ui.geometry_defaults_form.geometry_opt_group.endxy_entry,
  659. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  660. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  661. # Geometry Advanced Options
  662. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  663. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  664. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_rapid_entry,
  665. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  666. "geometry_extracut_length": self.ui.geometry_defaults_form.geometry_adv_opt_group.e_cut_entry,
  667. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  668. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  669. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  670. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  671. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  672. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  673. # Geometry Editor
  674. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  675. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  676. # CNCJob General
  677. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  678. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  679. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  680. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  681. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  682. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  683. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  684. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  685. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  686. "cncjob_plot_line": self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_entry,
  687. "cncjob_plot_fill": self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_entry,
  688. "cncjob_travel_line": self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_entry,
  689. "cncjob_travel_fill": self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_entry,
  690. # CNC Job Options
  691. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  692. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  693. # CNC Job Advanced Options
  694. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  695. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  696. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  697. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  698. # NCC Tool
  699. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  700. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  701. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  702. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  703. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_combo,
  704. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  705. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  706. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  707. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  708. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  709. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.select_combo,
  710. "tools_ncc_area_shape": self.ui.tools_defaults_form.tools_ncc_group.area_shape_radio,
  711. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  712. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  713. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  714. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  715. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  716. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  717. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  718. # CutOut Tool
  719. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  720. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  721. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  722. "tools_cutout_z": self.ui.tools_defaults_form.tools_cutout_group.cutz_entry,
  723. "tools_cutout_depthperpass": self.ui.tools_defaults_form.tools_cutout_group.maxdepth_entry,
  724. "tools_cutout_mdepth": self.ui.tools_defaults_form.tools_cutout_group.mpass_cb,
  725. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  726. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  727. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  728. # Paint Area Tool
  729. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  730. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  731. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  732. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  733. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  734. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  735. "tools_paint_area_shape": self.ui.tools_defaults_form.tools_paint_group.area_shape_radio,
  736. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  737. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  738. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  739. "tools_paintrest": self.ui.tools_defaults_form.tools_paint_group.rest_cb,
  740. "tools_painttool_type": self.ui.tools_defaults_form.tools_paint_group.tool_type_radio,
  741. "tools_paintcutz": self.ui.tools_defaults_form.tools_paint_group.cutz_entry,
  742. "tools_painttipdia": self.ui.tools_defaults_form.tools_paint_group.tipdia_entry,
  743. "tools_painttipangle": self.ui.tools_defaults_form.tools_paint_group.tipangle_entry,
  744. "tools_paintnewdia": self.ui.tools_defaults_form.tools_paint_group.newdia_entry,
  745. # 2-sided Tool
  746. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  747. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  748. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  749. "tools_2sided_allign_axis": self.ui.tools_defaults_form.tools_2sided_group.align_axis_radio,
  750. # Film Tool
  751. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  752. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  753. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  754. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  755. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  756. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  757. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  758. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  759. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  760. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  761. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  762. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  763. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  764. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  765. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  766. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  767. # Panelize Tool
  768. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  769. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  770. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  771. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  772. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  773. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  774. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  775. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  776. # Calculators Tool
  777. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  778. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  779. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  780. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  781. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  782. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  783. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  784. # Transformations Tool
  785. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  786. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  787. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  788. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  789. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  790. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  791. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  792. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  793. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  794. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  795. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  796. "tools_transform_buffer_dis": self.ui.tools_defaults_form.tools_transform_group.buffer_entry,
  797. "tools_transform_buffer_factor": self.ui.tools_defaults_form.tools_transform_group.buffer_factor_entry,
  798. "tools_transform_buffer_corner": self.ui.tools_defaults_form.tools_transform_group.buffer_rounded_cb,
  799. # SolderPaste Dispensing Tool
  800. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  801. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  802. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  803. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  804. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  805. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  806. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  807. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  808. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  809. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  810. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  811. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  812. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  813. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  814. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  815. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  816. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  817. # #######################################################################################################
  818. # ########################################## TOOLS 2 ####################################################
  819. # #######################################################################################################
  820. # Optimal Tool
  821. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  822. # Check Rules Tool
  823. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  824. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  825. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  826. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  827. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  828. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  829. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  830. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  831. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  832. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  833. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  834. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  835. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  836. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  837. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  838. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  839. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  840. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  841. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  842. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  843. # QRCode Tool
  844. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  845. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  846. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  847. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  848. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  849. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  850. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  851. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  852. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  853. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  854. # Copper Thieving Tool
  855. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  856. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  857. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  858. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  859. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  860. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  861. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  862. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  863. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  864. "tools_copper_thieving_squares_spacing":
  865. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  866. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  867. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  868. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  869. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  870. "tools_copper_thieving_mask_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_ppm_entry,
  871. # Fiducials Tool
  872. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  873. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  874. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  875. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  876. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  877. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  878. # Calibration Tool
  879. "tools_cal_calsource": self.ui.tools2_defaults_form.tools2_cal_group.cal_source_radio,
  880. "tools_cal_travelz": self.ui.tools2_defaults_form.tools2_cal_group.travelz_entry,
  881. "tools_cal_verz": self.ui.tools2_defaults_form.tools2_cal_group.verz_entry,
  882. "tools_cal_zeroz": self.ui.tools2_defaults_form.tools2_cal_group.zeroz_cb,
  883. "tools_cal_toolchangez": self.ui.tools2_defaults_form.tools2_cal_group.toolchangez_entry,
  884. "tools_cal_toolchange_xy": self.ui.tools2_defaults_form.tools2_cal_group.toolchange_xy_entry,
  885. "tools_cal_sec_point": self.ui.tools2_defaults_form.tools2_cal_group.second_point_radio,
  886. # Extract Drills Tool
  887. "tools_edrills_hole_type": self.ui.tools2_defaults_form.tools2_edrills_group.hole_size_radio,
  888. "tools_edrills_hole_fixed_dia": self.ui.tools2_defaults_form.tools2_edrills_group.dia_entry,
  889. "tools_edrills_hole_prop_factor": self.ui.tools2_defaults_form.tools2_edrills_group.factor_entry,
  890. "tools_edrills_circular_ring": self.ui.tools2_defaults_form.tools2_edrills_group.circular_ring_entry,
  891. "tools_edrills_oblong_ring": self.ui.tools2_defaults_form.tools2_edrills_group.oblong_ring_entry,
  892. "tools_edrills_square_ring": self.ui.tools2_defaults_form.tools2_edrills_group.square_ring_entry,
  893. "tools_edrills_rectangular_ring": self.ui.tools2_defaults_form.tools2_edrills_group.rectangular_ring_entry,
  894. "tools_edrills_others_ring": self.ui.tools2_defaults_form.tools2_edrills_group.other_ring_entry,
  895. "tools_edrills_circular": self.ui.tools2_defaults_form.tools2_edrills_group.circular_cb,
  896. "tools_edrills_oblong": self.ui.tools2_defaults_form.tools2_edrills_group.oblong_cb,
  897. "tools_edrills_square": self.ui.tools2_defaults_form.tools2_edrills_group.square_cb,
  898. "tools_edrills_rectangular": self.ui.tools2_defaults_form.tools2_edrills_group.rectangular_cb,
  899. "tools_edrills_others": self.ui.tools2_defaults_form.tools2_edrills_group.other_cb,
  900. # Punch Gerber Tool
  901. "tools_punch_hole_type": self.ui.tools2_defaults_form.tools2_punch_group.hole_size_radio,
  902. "tools_punch_hole_fixed_dia": self.ui.tools2_defaults_form.tools2_punch_group.dia_entry,
  903. "tools_punch_hole_prop_factor": self.ui.tools2_defaults_form.tools2_punch_group.factor_entry,
  904. "tools_punch_circular_ring": self.ui.tools2_defaults_form.tools2_punch_group.circular_ring_entry,
  905. "tools_punch_oblong_ring": self.ui.tools2_defaults_form.tools2_punch_group.oblong_ring_entry,
  906. "tools_punch_square_ring": self.ui.tools2_defaults_form.tools2_punch_group.square_ring_entry,
  907. "tools_punch_rectangular_ring": self.ui.tools2_defaults_form.tools2_punch_group.rectangular_ring_entry,
  908. "tools_punch_others_ring": self.ui.tools2_defaults_form.tools2_punch_group.other_ring_entry,
  909. "tools_punch_circular": self.ui.tools2_defaults_form.tools2_punch_group.circular_cb,
  910. "tools_punch_oblong": self.ui.tools2_defaults_form.tools2_punch_group.oblong_cb,
  911. "tools_punch_square": self.ui.tools2_defaults_form.tools2_punch_group.square_cb,
  912. "tools_punch_rectangular": self.ui.tools2_defaults_form.tools2_punch_group.rectangular_cb,
  913. "tools_punch_others": self.ui.tools2_defaults_form.tools2_punch_group.other_cb,
  914. # Invert Gerber Tool
  915. "tools_invert_margin": self.ui.tools2_defaults_form.tools2_invert_group.margin_entry,
  916. "tools_invert_join_style": self.ui.tools2_defaults_form.tools2_invert_group.join_radio,
  917. # Utilities
  918. # File associations
  919. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  920. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  921. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  922. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  923. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  924. }
  925. # update the Preferences GUI elements with the values in the self.defaults
  926. self.defaults_write_form()
  927. # When the self.defaults dictionary changes will update the Preferences GUI forms
  928. self.defaults.set_change_callback(self.on_defaults_dict_change)
  929. # ###########################################################################################################
  930. # ##################################### FIRST RUN SECTION ###################################################
  931. # ################################ It's done only once after install #####################################
  932. # ###########################################################################################################
  933. if self.defaults["first_run"] is True:
  934. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  935. initial_lay = 'compact'
  936. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  937. # Set the combobox in Preferences to the current layout
  938. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  939. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  940. # after the first run, this object should be False
  941. self.defaults["first_run"] = False
  942. self.save_defaults(silent=True)
  943. # ###########################################################################################################
  944. # ############################################ Data #########################################################
  945. # ###########################################################################################################
  946. self.recent = []
  947. self.recent_projects = []
  948. self.clipboard = QtWidgets.QApplication.clipboard()
  949. self.project_filename = None
  950. self.toggle_units_ignore = False
  951. # ###########################################################################################################
  952. # #################################### LOAD PREPROCESSORS ###################################################
  953. # ###########################################################################################################
  954. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  955. # the preprocessor file
  956. self.preprocessors = load_preprocessors(self)
  957. # make sure that always the 'default' preprocessor is the first item in the dictionary
  958. if 'default' in self.preprocessors.keys():
  959. new_ppp_dict = {}
  960. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  961. default_pp = self.preprocessors.pop('default')
  962. new_ppp_dict['default'] = default_pp
  963. # then add the rest of the keys
  964. for name, val_class in self.preprocessors.items():
  965. new_ppp_dict[name] = val_class
  966. # and now put back the ordered dict with 'default' key first
  967. self.preprocessors = new_ppp_dict
  968. for name in list(self.preprocessors.keys()):
  969. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  970. if name.partition('_')[0] == 'Paste':
  971. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  972. continue
  973. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  974. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  975. if name == 'hpgl':
  976. continue
  977. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  978. # ###########################################################################################################
  979. # ########################################## LOAD LANGUAGES ################################################
  980. # ###########################################################################################################
  981. self.languages = fcTranslate.load_languages()
  982. for name in sorted(self.languages.values()):
  983. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  984. # ###########################################################################################################
  985. # ####################################### APPLY APP LANGUAGE ################################################
  986. # ###########################################################################################################
  987. ret_val = fcTranslate.apply_language('strings')
  988. if ret_val == "no language":
  989. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  990. log.debug("Could not find the Language files. The App strings are missing.")
  991. else:
  992. # make the current language the current selection on the language combobox
  993. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  994. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  995. # ###########################################################################################################
  996. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  997. # ###########################################################################################################
  998. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  999. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1000. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1001. self.save_defaults(silent=True, first_time=True)
  1002. self.propagate_defaults(silent=True)
  1003. # def auto_save_defaults():
  1004. # try:
  1005. # self.save_defaults(silent=True)
  1006. # self.propagate_defaults(silent=True)
  1007. # finally:
  1008. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1009. # the following lines activates automatic defaults save
  1010. # if user_defaults:
  1011. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1012. # ###########################################################################################################
  1013. # ######################################## UPDATE THE OPTIONS ###############################################
  1014. # ###########################################################################################################
  1015. self.options = LoudDict()
  1016. # -----------------------------------------------------------------------------------------------------------
  1017. # Update the self.options from the self.defaults
  1018. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1019. # -----------------------------------------------------------------------------------------------------------
  1020. # Copy app defaults to project options
  1021. for def_key, def_val in self.defaults.items():
  1022. self.options[def_key] = deepcopy(def_val)
  1023. # self.options.update(self.defaults)
  1024. self.gen_form = None
  1025. self.ger_form = None
  1026. self.exc_form = None
  1027. self.geo_form = None
  1028. self.cnc_form = None
  1029. self.tools_form = None
  1030. self.tools2_form = None
  1031. self.fa_form = None
  1032. # Will show the Preferences GUI
  1033. self.show_preferences_gui()
  1034. # Initialize the color box's color in Preferences -> Global -> Color
  1035. self.init_color_pickers_in_preferences_gui()
  1036. # ### End of Data ####
  1037. # ###########################################################################################################
  1038. # #################################### SETUP OBJECT COLLECTION ##############################################
  1039. # ###########################################################################################################
  1040. self.collection = ObjectCollection(self)
  1041. self.ui.project_tab_layout.addWidget(self.collection.view)
  1042. # ### Adjust tabs width ## ##
  1043. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1044. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1045. self.collection.view.setMinimumWidth(290)
  1046. self.log.debug("Finished creating Object Collection.")
  1047. # ###########################################################################################################
  1048. # ######################################## SETUP Plot Area ##################################################
  1049. # ###########################################################################################################
  1050. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1051. if self.defaults["global_graphic_engine"] == '3D':
  1052. self.is_legacy = False
  1053. else:
  1054. self.is_legacy = True
  1055. # Event signals disconnect id holders
  1056. self.mp = None
  1057. self.mm = None
  1058. self.mr = None
  1059. self.mdc = None
  1060. self.mp_zc = None
  1061. self.kp = None
  1062. # Matplotlib axis
  1063. self.axes = None
  1064. if show_splash:
  1065. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1066. "Canvas initialization started."),
  1067. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1068. color=QtGui.QColor("gray"))
  1069. start_plot_time = time.time() # debug
  1070. self.plotcanvas = None
  1071. self.app_cursor = None
  1072. self.hover_shapes = None
  1073. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  1074. # setup the PlotCanvas
  1075. self.on_plotcanvas_setup()
  1076. end_plot_time = time.time()
  1077. self.used_time = end_plot_time - start_plot_time
  1078. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1079. if show_splash:
  1080. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1081. "Canvas initialization started.\n"
  1082. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1083. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1084. color=QtGui.QColor("gray"))
  1085. self.ui.splitter.setStretchFactor(1, 2)
  1086. # ###########################################################################################################
  1087. # ############################################### SYS TRAY ##################################################
  1088. # ###########################################################################################################
  1089. if self.defaults["global_systray_icon"]:
  1090. self.parent_w = QtWidgets.QWidget()
  1091. if self.cmd_line_headless == 1:
  1092. self.trayIcon = FlatCAMSystemTray(app=self,
  1093. icon=QtGui.QIcon(self.resource_location +
  1094. '/flatcam_icon32_green.png'),
  1095. headless=True,
  1096. parent=self.parent_w)
  1097. else:
  1098. self.trayIcon = FlatCAMSystemTray(app=self,
  1099. icon=QtGui.QIcon(self.resource_location +
  1100. '/flatcam_icon32_green.png'),
  1101. parent=self.parent_w)
  1102. # ###########################################################################################################
  1103. # ############################################### Worker SETUP ##############################################
  1104. # ###########################################################################################################
  1105. if self.defaults["global_worker_number"]:
  1106. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1107. else:
  1108. self.workers = WorkerStack(workers_number=2)
  1109. self.worker_task.connect(self.workers.add_task)
  1110. self.log.debug("Finished creating Workers crew.")
  1111. # ###########################################################################################################
  1112. # ############################################# Activity Monitor ###########################################
  1113. # ###########################################################################################################
  1114. self.activity_view = FlatCAMActivityView(app=self)
  1115. self.ui.infobar.addWidget(self.activity_view)
  1116. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1117. # ###########################################################################################################
  1118. # ############################################# Signal handling #############################################
  1119. # ###########################################################################################################
  1120. # ########################################## Custom signals ################################################
  1121. # signal for displaying messages in status bar
  1122. self.inform.connect(self.info)
  1123. # signal to be called when the app is quiting
  1124. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1125. self.message.connect(self.message_dialog)
  1126. # self.progress.connect(self.set_progress_bar)
  1127. # signals that are emitted when object state changes
  1128. self.object_created.connect(self.on_object_created)
  1129. self.object_changed.connect(self.on_object_changed)
  1130. self.object_plotted.connect(self.on_object_plotted)
  1131. self.plots_updated.connect(self.on_plots_updated)
  1132. # signals emitted when file state change
  1133. self.file_opened.connect(self.register_recent)
  1134. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1135. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1136. # ########################################## Standard signals ###############################################
  1137. # ### Menu
  1138. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1139. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1140. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1141. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1142. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1143. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1144. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1145. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1146. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1147. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1148. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1149. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1150. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1151. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1152. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1153. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1154. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1155. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  1156. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1157. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1158. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1159. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1160. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1161. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  1162. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1163. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1164. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1165. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1166. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1167. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1168. self.ui.menufile_exit.triggered.connect(self.final_save)
  1169. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1170. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1171. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1172. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1173. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1174. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1175. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1176. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1177. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1178. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1179. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1180. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1181. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  1182. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1183. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1184. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1185. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1186. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1187. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1188. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1189. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1190. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1191. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1192. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1193. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1194. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1195. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1196. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1197. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1198. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1199. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  1200. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1201. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1202. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1203. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1204. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1205. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1206. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1207. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1208. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1209. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1210. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1211. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1212. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1213. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1214. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1215. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1216. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1217. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1218. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1219. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1220. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1221. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1222. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1223. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1224. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1225. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1226. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1227. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1228. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1229. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1230. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1231. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1232. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1233. # ToolBar signals
  1234. self.connect_toolbar_signals()
  1235. # Notebook and Plot Tab Area signals
  1236. # make the right click on the notebook tab and plot tab area tab raise a menu
  1237. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1238. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1239. self.on_tab_setup_context_menu()
  1240. # activate initial state
  1241. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1242. # Context Menu
  1243. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1244. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1245. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1246. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1247. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1248. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1249. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1250. self.ui.clearplot.triggered.connect(self.clear_plots)
  1251. self.ui.replot.triggered.connect(self.plot_all)
  1252. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1253. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1254. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1255. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1256. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1257. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1258. # Project Context Menu -> Color Setting
  1259. for act in self.ui.menuprojectcolor.actions():
  1260. act.triggered.connect(self.on_set_color_action_triggered)
  1261. # Preferences Plot Area TAB
  1262. self.ui.pref_save_button.clicked.connect(lambda: self.on_save_button(save_to_file=True))
  1263. self.ui.pref_apply_button.clicked.connect(lambda: self.on_save_button(save_to_file=False))
  1264. self.ui.pref_close_button.clicked.connect(self.on_pref_close_button)
  1265. self.ui.pref_defaults_button.clicked.connect(self.on_restore_defaults_preferences)
  1266. # ###########################################################################################################
  1267. # #################################### GUI PREFERENCES SIGNALS ##############################################
  1268. # ###########################################################################################################
  1269. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1270. lambda: self.on_toggle_units(no_pref=False))
  1271. # ##################################### Workspace Setting Signals ###########################################
  1272. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1273. self.on_workspace_modified)
  1274. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1275. self.on_workspace_modified
  1276. )
  1277. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1278. # ###########################################################################################################
  1279. # ######################################## GUI SETTINGS SIGNALS #############################################
  1280. # ###########################################################################################################
  1281. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1282. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1283. # ######################################## Tools related signals ############################################
  1284. # Film Tool
  1285. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1286. self.on_film_color_entry)
  1287. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1288. self.on_film_color_button)
  1289. # QRCode Tool
  1290. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1291. self.on_qrcode_fill_color_entry)
  1292. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1293. self.on_qrcode_fill_color_button)
  1294. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1295. self.on_qrcode_back_color_entry)
  1296. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1297. self.on_qrcode_back_color_button)
  1298. # portability changed signal
  1299. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1300. # Object list
  1301. self.collection.view.activated.connect(self.on_row_activated)
  1302. self.collection.item_selected.connect(self.on_row_selected)
  1303. self.object_status_changed.connect(self.on_collection_updated)
  1304. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1305. # Export Excellon parameters.
  1306. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1307. self.on_update_exc_export
  1308. )
  1309. # call it once to make sure it is updated at startup
  1310. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1311. # when there are arguments at application startup this get launched
  1312. self.args_at_startup[list].connect(self.on_startup_args)
  1313. # ###########################################################################################################
  1314. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  1315. # ###########################################################################################################
  1316. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1317. lambda: self.restore_extensions(ext_type='excellon'))
  1318. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1319. lambda: self.restore_extensions(ext_type='gcode'))
  1320. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1321. lambda: self.restore_extensions(ext_type='gerber'))
  1322. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1323. lambda: self.delete_all_extensions(ext_type='excellon'))
  1324. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1325. lambda: self.delete_all_extensions(ext_type='gcode'))
  1326. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1327. lambda: self.delete_all_extensions(ext_type='gerber'))
  1328. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1329. lambda: self.add_extension(ext_type='excellon'))
  1330. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1331. lambda: self.add_extension(ext_type='gcode'))
  1332. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1333. lambda: self.add_extension(ext_type='gerber'))
  1334. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1335. lambda: self.del_extension(ext_type='excellon'))
  1336. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1337. lambda: self.del_extension(ext_type='gcode'))
  1338. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1339. lambda: self.del_extension(ext_type='gerber'))
  1340. # connect the 'Apply' buttons from the Preferences/File Associations
  1341. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1342. lambda: self.on_register_files(obj_type='excellon'))
  1343. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1344. lambda: self.on_register_files(obj_type='gcode'))
  1345. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1346. lambda: self.on_register_files(obj_type='gerber'))
  1347. # ###########################################################################################################
  1348. # ########################################### KEYWORDS SIGNALS ##############################################
  1349. # ###########################################################################################################
  1350. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1351. lambda: self.restore_extensions(ext_type='keyword'))
  1352. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1353. lambda: self.delete_all_extensions(ext_type='keyword'))
  1354. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1355. lambda: self.add_extension(ext_type='keyword'))
  1356. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1357. lambda: self.del_extension(ext_type='keyword'))
  1358. # connect the abort_all_tasks related slots to the related signals
  1359. self.proc_container.idle_flag.connect(self.app_is_idle)
  1360. # signal emitted when a tab is closed in the Plot Area
  1361. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1362. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  1363. self.ui.snap_infobar_label.clicked.connect(self.on_grid_icon_snap_clicked)
  1364. # signal to close the application
  1365. self.close_app_signal.connect(self.kill_app)
  1366. # ################################# FINISHED CONNECTING SIGNALS #############################################
  1367. # ###########################################################################################################
  1368. # ###########################################################################################################
  1369. # ###########################################################################################################
  1370. self.log.debug("Finished connecting Signals.")
  1371. # ###########################################################################################################
  1372. # ########################################## Other setups ###################################################
  1373. # ###########################################################################################################
  1374. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1375. # depending on from where those tools are called different actions can be done
  1376. self.call_source = 'app'
  1377. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1378. self.tool_tab_locked = False
  1379. # decide if to show or hide the Notebook side of the screen at startup
  1380. if self.defaults["global_project_at_startup"] is True:
  1381. self.ui.splitter.setSizes([1, 1])
  1382. else:
  1383. self.ui.splitter.setSizes([0, 1])
  1384. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1385. self.setup_component_editor()
  1386. # ###########################################################################################################
  1387. # ####################################### Auto-complete KEYWORDS ############################################
  1388. # ###########################################################################################################
  1389. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1390. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  1391. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  1392. 'export_exc',
  1393. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  1394. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_sys', 'help', 'import_svg',
  1395. 'interiors', 'isolate', 'join_excellon',
  1396. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  1397. 'mirror', 'ncc',
  1398. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1399. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1400. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  1401. 'save', 'save_project',
  1402. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1403. 'skew', 'subtract_poly', 'subtract_rectangle',
  1404. 'version', 'write_gcode'
  1405. ]
  1406. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  1407. 'Paste_1',
  1408. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1409. 'Toolchange_manual', 'True', 'Users',
  1410. 'all', 'auto', 'axis',
  1411. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  1412. 'contour', 'default',
  1413. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  1414. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  1415. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  1416. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1417. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  1418. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1419. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1420. 'spacing_columns',
  1421. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  1422. 'toolchange_xy', 'toolchangez', 'travelz',
  1423. 'tooldia', 'use_threads', 'value',
  1424. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1425. ]
  1426. self.tcl_keywords = [
  1427. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1428. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1429. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1430. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1431. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1432. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1433. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1434. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1435. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1436. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1437. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1438. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1439. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1440. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1441. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1442. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1443. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1444. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1445. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1446. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1447. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1448. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1449. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1450. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1451. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1452. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1453. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1454. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1455. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1456. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1457. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1458. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1459. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1460. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1461. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1462. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1463. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1464. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1465. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1466. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1467. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1468. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1469. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1470. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1471. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1472. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1473. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1474. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1475. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1476. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1477. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1478. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1479. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1480. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1481. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1482. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1483. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1484. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1485. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1486. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1487. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1488. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1489. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1490. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1491. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1492. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1493. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1494. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1495. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1496. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1497. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1498. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1499. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1500. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1501. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1502. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1503. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1504. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1505. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1506. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1507. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1508. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1509. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1510. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1511. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1512. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1513. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1514. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1515. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1516. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1517. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1518. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1519. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1520. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1521. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1522. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1523. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1524. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1525. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1526. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1527. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1528. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1529. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1530. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1531. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1532. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1533. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1534. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1535. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1536. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1537. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1538. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1539. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1540. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1541. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1542. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1543. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1544. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1545. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1546. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1547. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1548. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1549. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1550. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1551. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1552. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1553. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1554. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1555. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1556. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1557. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1558. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1559. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1560. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1561. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1562. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1563. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1564. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1565. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1566. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1567. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1568. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1569. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1570. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1571. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1572. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1573. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1574. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1575. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1576. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1577. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1578. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1579. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1580. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1581. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1582. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1583. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1584. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1585. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1586. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1587. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1588. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1589. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1590. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1591. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1592. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1593. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1594. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1595. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1596. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1597. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1598. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1599. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1600. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1601. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1602. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1603. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1604. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1605. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1606. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1607. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1608. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1609. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1610. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1611. ]
  1612. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1613. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1614. # ###########################################################################################################
  1615. # ############################################## Shell SETUP ################################################
  1616. # ###########################################################################################################
  1617. self.shell = FCShell(app=self, version=self.version)
  1618. self.ui.shell_dock.setWidget(self.shell)
  1619. self.log.debug("TCL Shell has been initialized.")
  1620. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1621. if self.defaults["global_shell_at_startup"]:
  1622. self.ui.shell_dock.show()
  1623. else:
  1624. self.ui.shell_dock.hide()
  1625. # ###########################################################################################################
  1626. # ########################################## Tools and Plugins ##############################################
  1627. # ###########################################################################################################
  1628. self.dblsidedtool = None
  1629. self.distance_tool = None
  1630. self.distance_min_tool = None
  1631. self.panelize_tool = None
  1632. self.film_tool = None
  1633. self.paste_tool = None
  1634. self.calculator_tool = None
  1635. self.rules_tool = None
  1636. self.sub_tool = None
  1637. self.move_tool = None
  1638. self.cutout_tool = None
  1639. self.ncclear_tool = None
  1640. self.optimal_tool = None
  1641. self.paint_tool = None
  1642. self.transform_tool = None
  1643. self.properties_tool = None
  1644. self.pdf_tool = None
  1645. self.image_tool = None
  1646. self.pcb_wizard_tool = None
  1647. self.cal_exc_tool = None
  1648. self.qrcode_tool = None
  1649. self.copper_thieving_tool = None
  1650. self.fiducial_tool = None
  1651. self.edrills_tool = None
  1652. self.align_objects_tool = None
  1653. self.punch_tool = None
  1654. self.invert_tool = None
  1655. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1656. try:
  1657. self.install_tools()
  1658. except AttributeError as e:
  1659. log.debug("App.__init__() install tools() --> %s" % str(e))
  1660. # ###########################################################################################################
  1661. # ############################################ SETUP RECENT ITEMS ###########################################
  1662. # ###########################################################################################################
  1663. self.setup_recent_items()
  1664. # ###########################################################################################################
  1665. # ######################################### BookMarks Manager ###############################################
  1666. # ###########################################################################################################
  1667. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1668. self.install_bookmarks()
  1669. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1670. # ###########################################################################################################
  1671. # ########################################### Tools Database ################################################
  1672. # ###########################################################################################################
  1673. self.tools_db_tab = None
  1674. # ### System Font Parsing ###
  1675. # self.f_parse = ParseFont(self)
  1676. # self.parse_system_fonts()
  1677. # ###########################################################################################################
  1678. # ######################################### Check for updates ###############################################
  1679. # ###########################################################################################################
  1680. # Separate thread (Not worker)
  1681. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1682. if (self.beta is False or self.beta is None) and \
  1683. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1684. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1685. self.thr2 = QtCore.QThread()
  1686. self.worker_task.emit({'fcn': self.version_check,
  1687. 'params': []})
  1688. self.thr2.start(QtCore.QThread.LowPriority)
  1689. # ###########################################################################################################
  1690. # ##################################### Register files with FlatCAM; #######################################
  1691. # ################################### It works only for Windows for now ####################################
  1692. # ###########################################################################################################
  1693. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1694. self.on_register_files()
  1695. # ###########################################################################################################
  1696. # ######################################## Variables for global usage #######################################
  1697. # ###########################################################################################################
  1698. # hold the App units
  1699. self.units = 'MM'
  1700. # coordinates for relative position display
  1701. self.rel_point1 = (0, 0)
  1702. self.rel_point2 = (0, 0)
  1703. # variable to store coordinates
  1704. self.pos = (0, 0)
  1705. self.pos_canvas = (0, 0)
  1706. self.pos_jump = (0, 0)
  1707. # variable to store mouse coordinates
  1708. self.mouse = [0, 0]
  1709. # variable to store the delta positions on cavnas
  1710. self.dx = 0
  1711. self.dy = 0
  1712. # decide if we have a double click or single click
  1713. self.doubleclick = False
  1714. # store here the is_dragging value
  1715. self.event_is_dragging = False
  1716. # variable to store if a command is active (then the var is not None) and which one it is
  1717. self.command_active = None
  1718. # variable to store the status of moving selection action
  1719. # None value means that it's not an selection action
  1720. # True value = a selection from left to right
  1721. # False value = a selection from right to left
  1722. self.selection_type = None
  1723. # List to store the objects that are currently loaded in FlatCAM
  1724. # This list is updated on each object creation or object delete
  1725. self.all_objects_list = []
  1726. self.objects_under_the_click_list = []
  1727. # List to store the objects that are selected
  1728. self.sel_objects_list = []
  1729. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1730. self.key_modifiers = None
  1731. # Variable to hold the status of the axis
  1732. self.toggle_axis = True
  1733. # Variable to hold the status of the grid lines
  1734. self.toggle_grid_lines = True
  1735. # Variable to store the status of the fullscreen event
  1736. self.toggle_fscreen = False
  1737. # Variable to store the status of the code editor
  1738. self.toggle_codeeditor = False
  1739. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1740. self.click_noproject = False
  1741. self.cursor = None
  1742. # Variable to store the GCODE that was edited
  1743. self.gcode_edited = ""
  1744. self.text_editor_tab = None
  1745. # reference for the self.ui.code_editor
  1746. self.reference_code_editor = None
  1747. self.script_code = ''
  1748. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1749. self.preferences_changed_flag = False
  1750. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1751. self.tools_db_changed_flag = False
  1752. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1753. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1754. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1755. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1756. 'tsm']
  1757. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1758. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1759. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1760. 'sbp', 'tap', 'xpi']
  1761. self.svg_list = ['svg']
  1762. self.dxf_list = ['dxf']
  1763. self.pdf_list = ['pdf']
  1764. self.prj_list = ['flatprj']
  1765. self.conf_list = ['flatconfig']
  1766. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1767. # flag for polygons not cleared
  1768. self.poly_not_cleared = False
  1769. # VisPy visuals
  1770. self.isHovering = False
  1771. self.notHovering = True
  1772. # Window geometry
  1773. self.x_pos = None
  1774. self.y_pos = None
  1775. self.width = None
  1776. self.height = None
  1777. # when True, the app has to return from any thread
  1778. self.abort_flag = False
  1779. # set the value used in the Windows Title
  1780. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1781. # this holds a widget that is installed in the Plot Area when View Source option is used
  1782. self.source_editor_tab = None
  1783. self.pagesize = {}
  1784. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1785. # VisPy visuals
  1786. if self.is_legacy is False:
  1787. try:
  1788. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1789. except AttributeError:
  1790. self.tool_shapes = None
  1791. else:
  1792. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1793. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1794. # used in the delayed shutdown self.start_delayed_quit() method
  1795. self.save_timer = None
  1796. # ###########################################################################################################
  1797. # ################################## ADDING FlatCAM EDITORS section #########################################
  1798. # ###########################################################################################################
  1799. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1800. # at the first launch of the App , the editors will not be functional.
  1801. try:
  1802. self.geo_editor = FlatCAMGeoEditor(self)
  1803. except AttributeError:
  1804. pass
  1805. try:
  1806. self.exc_editor = FlatCAMExcEditor(self)
  1807. except AttributeError:
  1808. pass
  1809. try:
  1810. self.grb_editor = FlatCAMGrbEditor(self)
  1811. except AttributeError:
  1812. pass
  1813. self.log.debug("Finished adding FlatCAM Editor's.")
  1814. self.set_ui_title(name=_("New Project - Not saved"))
  1815. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1816. current_platform = platform.architecture()[0]
  1817. if current_platform != '64bit':
  1818. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1819. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1820. # ###########################################################################################################
  1821. # ##################################### Finished the CONSTRUCTOR ############################################
  1822. # ###########################################################################################################
  1823. App.log.debug("END of constructor. Releasing control.")
  1824. # ###########################################################################################################
  1825. # ########################################## SHOW GUI #######################################################
  1826. # ###########################################################################################################
  1827. # if the app is not started as headless, show it
  1828. if self.cmd_line_headless != 1:
  1829. if show_splash:
  1830. # finish the splash
  1831. self.splash.finish(self.ui)
  1832. mgui_settings = QSettings("Open Source", "FlatCAM")
  1833. if mgui_settings.contains("maximized_gui"):
  1834. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1835. if maximized_ui is True:
  1836. self.ui.showMaximized()
  1837. else:
  1838. self.ui.show()
  1839. else:
  1840. self.ui.show()
  1841. if self.defaults["global_systray_icon"]:
  1842. self.trayIcon.show()
  1843. else:
  1844. log.warning("******************* RUNNING HEADLESS *******************")
  1845. # ###########################################################################################################
  1846. # ######################################## START-UP ARGUMENTS ###############################################
  1847. # ###########################################################################################################
  1848. # test if the program was started with a script as parameter
  1849. if self.cmd_line_shellvar:
  1850. try:
  1851. cnt = 0
  1852. command_tcl = 0
  1853. for i in self.cmd_line_shellvar.split(','):
  1854. if i is not None:
  1855. # noinspection PyBroadException
  1856. try:
  1857. command_tcl = eval(i)
  1858. except Exception:
  1859. command_tcl = i
  1860. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1861. cnt += 1
  1862. # if there are Windows paths then replace the path separator with a Unix like one
  1863. if sys.platform == 'win32':
  1864. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1865. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1866. except Exception as ext:
  1867. print("ERROR: ", ext)
  1868. sys.exit(2)
  1869. if self.cmd_line_shellfile:
  1870. if self.cmd_line_headless != 1:
  1871. if self.ui.shell_dock.isHidden():
  1872. self.ui.shell_dock.show()
  1873. try:
  1874. with open(self.cmd_line_shellfile, "r") as myfile:
  1875. # if show_splash:
  1876. # self.splash.showMessage('%s: %ssec\n%s' % (
  1877. # _("Canvas initialization started.\n"
  1878. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1879. # _("Executing Tcl Script ...")),
  1880. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1881. # color=QtGui.QColor("gray"))
  1882. cmd_line_shellfile_text = myfile.read()
  1883. if self.cmd_line_headless != 1:
  1884. self.shell.exec_command(cmd_line_shellfile_text)
  1885. else:
  1886. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1887. except Exception as ext:
  1888. print("ERROR: ", ext)
  1889. sys.exit(2)
  1890. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1891. # the path/file_name must be enclosed in quotes if it contain spaces
  1892. if App.args:
  1893. self.args_at_startup.emit(App.args)
  1894. if self.fcDefaults.old_defaults_found is True:
  1895. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1896. "Please reboot the application to update."))
  1897. self.fcDefaults.old_defaults_found = False
  1898. # ######################################### INIT FINISHED #######################################################
  1899. # #################################################################################################################
  1900. # #################################################################################################################
  1901. # #################################################################################################################
  1902. # #################################################################################################################
  1903. # #################################################################################################################
  1904. @staticmethod
  1905. def copy_and_overwrite(from_path, to_path):
  1906. """
  1907. From here:
  1908. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1909. :param from_path: source path
  1910. :param to_path: destination path
  1911. :return: None
  1912. """
  1913. if os.path.exists(to_path):
  1914. shutil.rmtree(to_path)
  1915. try:
  1916. shutil.copytree(from_path, to_path)
  1917. except FileNotFoundError:
  1918. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1919. shutil.copytree(from_new_path, to_path)
  1920. def on_startup_args(self, args, silent=False):
  1921. """
  1922. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1923. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1924. :param args: a list containing the application args at startup
  1925. :return: None
  1926. """
  1927. if args is not None:
  1928. args_to_process = args
  1929. else:
  1930. args_to_process = App.args
  1931. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1932. for argument in args_to_process:
  1933. if '.FlatPrj'.lower() in argument.lower():
  1934. try:
  1935. project_name = str(argument)
  1936. if project_name == "":
  1937. if silent is False:
  1938. self.inform.emit(_("Cancelled."))
  1939. else:
  1940. # self.open_project(project_name)
  1941. run_from_arg = True
  1942. # self.worker_task.emit({'fcn': self.open_project,
  1943. # 'params': [project_name, run_from_arg]})
  1944. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1945. except Exception as e:
  1946. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1947. elif '.FlatConfig'.lower() in argument.lower():
  1948. try:
  1949. file_name = str(argument)
  1950. if file_name == "":
  1951. if silent is False:
  1952. self.inform.emit(_("Open Config file failed."))
  1953. else:
  1954. run_from_arg = True
  1955. # self.worker_task.emit({'fcn': self.open_config_file,
  1956. # 'params': [file_name, run_from_arg]})
  1957. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1958. except Exception as e:
  1959. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1960. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1961. try:
  1962. file_name = str(argument)
  1963. if file_name == "":
  1964. if silent is False:
  1965. self.inform.emit(_("Open Script file failed."))
  1966. else:
  1967. if silent is False:
  1968. self.on_fileopenscript(name=file_name)
  1969. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1970. self.on_filerunscript(name=file_name)
  1971. except Exception as e:
  1972. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1973. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1974. log.debug("App.on_startup_args() --> Quit event.")
  1975. sys.exit()
  1976. elif 'save'.lower() in argument.lower():
  1977. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1978. self.save_defaults()
  1979. else:
  1980. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1981. proc_arg = argument.lower()
  1982. for ext in exc_list:
  1983. proc_ext = ext.replace(' ', '')
  1984. proc_ext = '.%s' % proc_ext
  1985. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1986. file_name = str(argument)
  1987. if file_name == "":
  1988. if silent is False:
  1989. self.inform.emit(_("Open Excellon file failed."))
  1990. else:
  1991. self.on_fileopenexcellon(name=file_name)
  1992. return
  1993. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1994. for ext in gco_list:
  1995. proc_ext = ext.replace(' ', '')
  1996. proc_ext = '.%s' % proc_ext
  1997. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1998. file_name = str(argument)
  1999. if file_name == "":
  2000. if silent is False:
  2001. self.inform.emit(_("Open GCode file failed."))
  2002. else:
  2003. self.on_fileopengcode(name=file_name)
  2004. return
  2005. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2006. for ext in grb_list:
  2007. proc_ext = ext.replace(' ', '')
  2008. proc_ext = '.%s' % proc_ext
  2009. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2010. file_name = str(argument)
  2011. if file_name == "":
  2012. if silent is False:
  2013. self.inform.emit(_("Open Gerber file failed."))
  2014. else:
  2015. self.on_fileopengerber(name=file_name)
  2016. return
  2017. # if it reached here without already returning then the app was registered with a file that it does not
  2018. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2019. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2020. # for arg in args_to_process:
  2021. # if 'FlatCAM.exe' in arg:
  2022. # continue
  2023. # else:
  2024. # sys.exit(2)
  2025. def set_ui_title(self, name):
  2026. """
  2027. Sets the title of the main window.
  2028. :param name: String that store the project path and project name
  2029. :return: None
  2030. """
  2031. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2032. (self.version,
  2033. ('BETA' if self.beta else ''),
  2034. platform.architecture()[0],
  2035. self.engine,
  2036. name)
  2037. )
  2038. def on_app_restart(self):
  2039. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2040. # be left in the SySTray
  2041. try:
  2042. self.trayIcon.hide()
  2043. except Exception:
  2044. pass
  2045. fcTranslate.restart_program(app=self)
  2046. def defaults_read_form(self):
  2047. """
  2048. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2049. :return: None
  2050. """
  2051. for option in self.defaults_form_fields:
  2052. try:
  2053. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2054. except Exception as e:
  2055. log.debug("App.defaults_read_form() --> %s" % str(e))
  2056. def defaults_write_form(self, factor=None, fl_units=None, source_dict=None):
  2057. """
  2058. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2059. self.defaults dictionary.
  2060. :param factor: will apply a factor to the values that written in the GUI elements
  2061. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2062. :param source_dict: the repository of options, usually is the self.defaults
  2063. :return: None
  2064. """
  2065. options_storage = self.defaults if source_dict is None else source_dict
  2066. for option in options_storage:
  2067. if source_dict:
  2068. self.defaults_write_form_field(option, factor=factor, units=fl_units, defaults_dict=source_dict)
  2069. else:
  2070. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2071. # try:
  2072. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2073. # except KeyError:
  2074. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2075. # pass
  2076. def defaults_write_form_field(self, field, factor=None, units=None, defaults_dict=None):
  2077. """
  2078. Basically it is the worker in the self.defaults_write_form()
  2079. :param field: the GUI element in Preferences GUI to be updated
  2080. :param factor: factor to be applied to the field parameter
  2081. :param units: current FLatCAM measuring units
  2082. :param defaults_dict: the defaults storage
  2083. :return: None, it updates GUI elements
  2084. """
  2085. def_dict = self.defaults if defaults_dict is None else defaults_dict
  2086. try:
  2087. if factor is None:
  2088. if units is None:
  2089. self.defaults_form_fields[field].set_value(def_dict[field])
  2090. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2091. self.defaults_form_fields[field].set_value(def_dict[field])
  2092. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2093. self.defaults_form_fields[field].set_value(def_dict[field])
  2094. else:
  2095. if units is None:
  2096. self.defaults_form_fields[field].set_value(def_dict[field] * factor)
  2097. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2098. self.defaults_form_fields[field].set_value((def_dict[field] * factor))
  2099. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2100. self.defaults_form_fields[field].set_value((def_dict[field] * factor))
  2101. except KeyError:
  2102. pass
  2103. except AttributeError:
  2104. log.debug(field)
  2105. def clear_pool(self):
  2106. """
  2107. Clear the multiprocessing pool and calls garbage collector.
  2108. :return: None
  2109. """
  2110. self.pool.close()
  2111. self.pool = Pool()
  2112. self.pool_recreated.emit(self.pool)
  2113. gc.collect()
  2114. def install_tools(self):
  2115. """
  2116. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2117. Instantiation of the Tools classes.
  2118. The order that the tools are installed is important as they can depend on each other install position.
  2119. :return: None
  2120. """
  2121. self.distance_tool = Distance(self)
  2122. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  2123. before=self.ui.menueditorigin,
  2124. separator=False)
  2125. self.distance_min_tool = DistanceMin(self)
  2126. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  2127. pos=self.ui.menuedit,
  2128. before=self.ui.menueditorigin,
  2129. separator=True)
  2130. self.dblsidedtool = DblSidedTool(self)
  2131. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  2132. self.cal_exc_tool = ToolCalibration(self)
  2133. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  2134. before=self.dblsidedtool.menuAction,
  2135. separator=False)
  2136. self.align_objects_tool = AlignObjects(self)
  2137. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  2138. self.edrills_tool = ToolExtractDrills(self)
  2139. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  2140. self.panelize_tool = Panelize(self)
  2141. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  2142. self.film_tool = Film(self)
  2143. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  2144. self.paste_tool = SolderPaste(self)
  2145. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  2146. self.calculator_tool = ToolCalculator(self)
  2147. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  2148. self.sub_tool = ToolSub(self)
  2149. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  2150. pos=self.ui.menutool, separator=True)
  2151. self.rules_tool = RulesCheck(self)
  2152. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  2153. pos=self.ui.menutool, separator=False)
  2154. self.optimal_tool = ToolOptimal(self)
  2155. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  2156. pos=self.ui.menutool, separator=True)
  2157. self.move_tool = ToolMove(self)
  2158. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  2159. before=self.ui.menueditorigin, separator=True)
  2160. self.cutout_tool = CutOut(self)
  2161. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  2162. before=self.sub_tool.menuAction)
  2163. self.ncclear_tool = NonCopperClear(self)
  2164. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  2165. before=self.sub_tool.menuAction, separator=True)
  2166. self.paint_tool = ToolPaint(self)
  2167. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  2168. before=self.sub_tool.menuAction, separator=True)
  2169. self.copper_thieving_tool = ToolCopperThieving(self)
  2170. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  2171. pos=self.ui.menutool)
  2172. self.fiducial_tool = ToolFiducials(self)
  2173. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  2174. pos=self.ui.menutool)
  2175. self.qrcode_tool = QRCode(self)
  2176. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  2177. pos=self.ui.menutool)
  2178. self.punch_tool = ToolPunchGerber(self)
  2179. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  2180. self.invert_tool = ToolInvertGerber(self)
  2181. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  2182. self.transform_tool = ToolTransform(self)
  2183. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  2184. pos=self.ui.menuoptions, separator=True)
  2185. self.properties_tool = Properties(self)
  2186. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  2187. pos=self.ui.menuoptions)
  2188. self.pdf_tool = ToolPDF(self)
  2189. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  2190. pos=self.ui.menufileimport,
  2191. separator=True)
  2192. self.image_tool = ToolImage(self)
  2193. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  2194. pos=self.ui.menufileimport,
  2195. separator=True)
  2196. self.pcb_wizard_tool = PcbWizard(self)
  2197. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  2198. pos=self.ui.menufileimport)
  2199. self.log.debug("Tools are installed.")
  2200. def remove_tools(self):
  2201. """
  2202. Will remove all the actions in the Tool menu.
  2203. :return: None
  2204. """
  2205. for act in self.ui.menutool.actions():
  2206. self.ui.menutool.removeAction(act)
  2207. def init_tools(self):
  2208. """
  2209. Initialize the Tool tab in the notebook side of the central widget.
  2210. Remove the actions in the Tools menu.
  2211. Instantiate again the FlatCAM tools (plugins).
  2212. All this is required when changing the layout: standard, compact etc.
  2213. :return: None
  2214. """
  2215. log.debug("init_tools()")
  2216. # delete the data currently in the Tools Tab and the Tab itself
  2217. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2218. if widget is not None:
  2219. widget.deleteLater()
  2220. self.ui.notebook.removeTab(2)
  2221. # rebuild the Tools Tab
  2222. self.ui.tool_tab = QtWidgets.QWidget()
  2223. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2224. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2225. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2226. self.ui.tool_scroll_area = VerticalScrollArea()
  2227. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2228. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2229. # first remove all of them
  2230. self.remove_tools()
  2231. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2232. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  2233. '&Command Line\tS')
  2234. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  2235. # third install all of them
  2236. try:
  2237. self.install_tools()
  2238. except AttributeError:
  2239. pass
  2240. self.log.debug("Tools are initialized.")
  2241. # def parse_system_fonts(self):
  2242. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2243. # 'params': []})
  2244. def connect_toolbar_signals(self):
  2245. """
  2246. Reconnect the signals to the actions in the toolbar.
  2247. This has to be done each time after the FlatCAM tools are removed/installed.
  2248. :return: None
  2249. """
  2250. # Toolbar
  2251. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2252. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2253. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2254. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2255. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2256. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2257. self.ui.replot_btn.triggered.connect(self.plot_all)
  2258. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2259. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2260. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2261. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2262. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2263. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2264. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2265. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2266. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  2267. self.ui.delete_btn.triggered.connect(self.on_delete)
  2268. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2269. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2270. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2271. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  2272. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2273. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  2274. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  2275. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2276. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2277. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2278. # Tools Toolbar Signals
  2279. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2280. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  2281. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  2282. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  2283. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2284. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2285. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2286. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2287. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2288. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2289. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2290. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2291. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2292. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2293. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2294. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2295. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2296. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2297. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  2298. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  2299. def object2editor(self):
  2300. """
  2301. Send the current Geometry or Excellon object (if any) into the it's editor.
  2302. :return: None
  2303. """
  2304. self.report_usage("object2editor()")
  2305. # disable the objects menu as it may interfere with the Editors
  2306. self.ui.menuobjects.setDisabled(True)
  2307. edited_object = self.collection.get_active()
  2308. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  2309. isinstance(edited_object, ExcellonObject):
  2310. pass
  2311. else:
  2312. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  2313. return
  2314. if isinstance(edited_object, GeometryObject):
  2315. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2316. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2317. # we set the notebook to hidden
  2318. # self.ui.splitter.setSizes([0, 1])
  2319. if edited_object.multigeo is True:
  2320. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2321. if len(sel_rows) > 1:
  2322. self.inform.emit('[WARNING_NOTCL] %s' %
  2323. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2324. "is not possible.\n"
  2325. "Edit only one geometry at a time."))
  2326. # determine the tool dia of the selected tool
  2327. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2328. # now find the key in the edited_object.tools that has this tooldia
  2329. multi_tool = 1
  2330. for tool in edited_object.tools:
  2331. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2332. multi_tool = tool
  2333. break
  2334. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2335. else:
  2336. self.geo_editor.edit_fcgeometry(edited_object)
  2337. # set call source to the Editor we go into
  2338. self.call_source = 'geo_editor'
  2339. elif isinstance(edited_object, ExcellonObject):
  2340. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2341. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2342. if self.ui.splitter.sizes()[0] == 0:
  2343. self.ui.splitter.setSizes([1, 1])
  2344. self.exc_editor.edit_fcexcellon(edited_object)
  2345. # set call source to the Editor we go into
  2346. self.call_source = 'exc_editor'
  2347. elif isinstance(edited_object, GerberObject):
  2348. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2349. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2350. if self.ui.splitter.sizes()[0] == 0:
  2351. self.ui.splitter.setSizes([1, 1])
  2352. self.grb_editor.edit_fcgerber(edited_object)
  2353. # set call source to the Editor we go into
  2354. self.call_source = 'grb_editor'
  2355. # reset the following variables so the UI is built again after edit
  2356. edited_object.ui_build = False
  2357. edited_object.build_aperture_storage = False
  2358. # make sure that we can't select another object while in Editor Mode:
  2359. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2360. self.ui.project_frame.setDisabled(True)
  2361. # delete any selection shape that might be active as they are not relevant in Editor
  2362. self.delete_selection_shape()
  2363. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2364. self.ui.plot_tab_area.protectTab(0)
  2365. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  2366. self.should_we_save = True
  2367. def editor2object(self, cleanup=None):
  2368. """
  2369. Transfers the Geometry or Excellon from it's editor to the current object.
  2370. :return: None
  2371. """
  2372. self.report_usage("editor2object()")
  2373. # re-enable the objects menu that was disabled on entry in Editor mode
  2374. self.ui.menuobjects.setDisabled(False)
  2375. # do not update a geometry or excellon object unless it comes out of an editor
  2376. if self.call_source != 'app':
  2377. edited_obj = self.collection.get_active()
  2378. if cleanup is None:
  2379. msgbox = QtWidgets.QMessageBox()
  2380. msgbox.setText(_("Do you want to save the edited object?"))
  2381. msgbox.setWindowTitle(_("Close Editor"))
  2382. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2383. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2384. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2385. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2386. msgbox.setDefaultButton(bt_yes)
  2387. msgbox.exec_()
  2388. response = msgbox.clickedButton()
  2389. if response == bt_yes:
  2390. # clean the Tools Tab
  2391. self.ui.tool_scroll_area.takeWidget()
  2392. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2393. self.ui.notebook.setTabText(2, "Tool")
  2394. if isinstance(edited_obj, GeometryObject):
  2395. obj_type = "Geometry"
  2396. if cleanup is None:
  2397. self.geo_editor.update_fcgeometry(edited_obj)
  2398. # self.geo_editor.update_options(edited_obj)
  2399. self.geo_editor.deactivate()
  2400. # restore GUI to the Selected TAB
  2401. # Remove anything else in the GUI
  2402. self.ui.tool_scroll_area.takeWidget()
  2403. # update the geo object options so it is including the bounding box values
  2404. try:
  2405. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  2406. edited_obj.options['xmin'] = xmin
  2407. edited_obj.options['ymin'] = ymin
  2408. edited_obj.options['xmax'] = xmax
  2409. edited_obj.options['ymax'] = ymax
  2410. except AttributeError as e:
  2411. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  2412. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2413. edited_obj.build_ui()
  2414. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2415. elif isinstance(edited_obj, GerberObject):
  2416. obj_type = "Gerber"
  2417. if cleanup is None:
  2418. self.grb_editor.update_fcgerber()
  2419. self.grb_editor.update_options(edited_obj)
  2420. self.grb_editor.deactivate_grb_editor()
  2421. # delete the old object (the source object) if it was an empty one
  2422. try:
  2423. if len(edited_obj.solid_geometry) == 0:
  2424. old_name = edited_obj.options['name']
  2425. self.collection.set_active(old_name)
  2426. self.collection.delete_active()
  2427. except TypeError:
  2428. # if the solid_geometry is a single Polygon the len() will not work
  2429. # in any case, falling here means that we have something in the solid_geometry, even if only
  2430. # a single Polygon, therefore we pass this
  2431. pass
  2432. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2433. # restore GUI to the Selected TAB
  2434. # Remove anything else in the GUI
  2435. self.ui.selected_scroll_area.takeWidget()
  2436. elif isinstance(edited_obj, ExcellonObject):
  2437. obj_type = "Excellon"
  2438. if cleanup is None:
  2439. self.exc_editor.update_fcexcellon(edited_obj)
  2440. # self.exc_editor.update_options(edited_obj)
  2441. self.exc_editor.deactivate()
  2442. # restore GUI to the Selected TAB
  2443. # Remove anything else in the GUI
  2444. self.ui.tool_scroll_area.takeWidget()
  2445. # delete the old object (the source object) if it was an empty one
  2446. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2447. old_name = edited_obj.options['name']
  2448. self.collection.delete_by_name(name=old_name)
  2449. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2450. else:
  2451. self.inform.emit('[WARNING_NOTCL] %s' %
  2452. _("Select a Gerber, Geometry or Excellon Object to update."))
  2453. return
  2454. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  2455. elif response == bt_no:
  2456. # clean the Tools Tab
  2457. self.ui.tool_scroll_area.takeWidget()
  2458. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2459. self.ui.notebook.setTabText(2, "Tool")
  2460. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  2461. if isinstance(edited_obj, GeometryObject):
  2462. self.geo_editor.deactivate()
  2463. edited_obj.build_ui()
  2464. elif isinstance(edited_obj, GerberObject):
  2465. self.grb_editor.deactivate_grb_editor()
  2466. edited_obj.build_ui()
  2467. elif isinstance(edited_obj, ExcellonObject):
  2468. self.exc_editor.deactivate()
  2469. edited_obj.build_ui()
  2470. else:
  2471. self.inform.emit('[WARNING_NOTCL] %s' %
  2472. _("Select a Gerber, Geometry or Excellon Object to update."))
  2473. return
  2474. elif response == bt_cancel:
  2475. return
  2476. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2477. # edited_obj.build_ui()
  2478. # Switch notebook to Selected page
  2479. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2480. else:
  2481. if isinstance(edited_obj, GeometryObject):
  2482. self.geo_editor.deactivate()
  2483. elif isinstance(edited_obj, GerberObject):
  2484. self.grb_editor.deactivate_grb_editor()
  2485. elif isinstance(edited_obj, ExcellonObject):
  2486. self.exc_editor.deactivate()
  2487. else:
  2488. self.inform.emit('[WARNING_NOTCL] %s' %
  2489. _("Select a Gerber, Geometry or Excellon Object to update."))
  2490. return
  2491. # if notebook is hidden we show it
  2492. if self.ui.splitter.sizes()[0] == 0:
  2493. self.ui.splitter.setSizes([1, 1])
  2494. # restore the call_source to app
  2495. self.call_source = 'app'
  2496. edited_obj.plot()
  2497. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2498. self.ui.plot_tab_area.protectTab(0)
  2499. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2500. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2501. self.ui.project_frame.setDisabled(False)
  2502. def get_last_folder(self):
  2503. """
  2504. Get the folder path from where the last file was opened.
  2505. :return: String, last opened folder path
  2506. """
  2507. return self.defaults["global_last_folder"]
  2508. def get_last_save_folder(self):
  2509. """
  2510. Get the folder path from where the last file was saved.
  2511. :return: String, last saved folder path
  2512. """
  2513. loc = self.defaults["global_last_save_folder"]
  2514. if loc is None:
  2515. loc = self.defaults["global_last_folder"]
  2516. if loc is None:
  2517. loc = os.path.dirname(__file__)
  2518. return loc
  2519. def report_usage(self, resource):
  2520. """
  2521. Increments usage counter for the given resource
  2522. in self.defaults['global_stats'].
  2523. :param resource: Name of the resource.
  2524. :return: None
  2525. """
  2526. if resource in self.defaults['global_stats']:
  2527. self.defaults['global_stats'][resource] += 1
  2528. else:
  2529. self.defaults['global_stats'][resource] = 1
  2530. def info(self, msg):
  2531. """
  2532. Informs the user. Normally on the status bar, optionally
  2533. also on the shell.
  2534. :param msg: Text to write.
  2535. :return: None
  2536. """
  2537. # Type of message in brackets at the beginning of the message.
  2538. match = re.search(r"\[(.*)\](.*)", msg)
  2539. if match:
  2540. level = match.group(1)
  2541. msg_ = match.group(2)
  2542. self.ui.fcinfo.set_status(str(msg_), level=level)
  2543. if level.lower() == "error":
  2544. self.shell_message(msg, error=True, show=True)
  2545. elif level.lower() == "warning":
  2546. self.shell_message(msg, warning=True, show=True)
  2547. elif level.lower() == "error_notcl":
  2548. self.shell_message(msg, error=True, show=False)
  2549. elif level.lower() == "warning_notcl":
  2550. self.shell_message(msg, warning=True, show=False)
  2551. elif level.lower() == "success":
  2552. self.shell_message(msg, success=True, show=False)
  2553. elif level.lower() == "selected":
  2554. self.shell_message(msg, selected=True, show=False)
  2555. else:
  2556. self.shell_message(msg, show=False)
  2557. else:
  2558. self.ui.fcinfo.set_status(str(msg), level="info")
  2559. # make sure that if the message is to clear the infobar with a space
  2560. # is not printed over and over on the shell
  2561. if msg != '':
  2562. self.shell_message(msg)
  2563. def restore_toolbar_view(self):
  2564. """
  2565. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2566. was saved in the defaults dictionary.
  2567. :return: None
  2568. """
  2569. tb = self.defaults["global_toolbar_view"]
  2570. if tb & 1:
  2571. self.ui.toolbarfile.setVisible(True)
  2572. else:
  2573. self.ui.toolbarfile.setVisible(False)
  2574. if tb & 2:
  2575. self.ui.toolbargeo.setVisible(True)
  2576. else:
  2577. self.ui.toolbargeo.setVisible(False)
  2578. if tb & 4:
  2579. self.ui.toolbarview.setVisible(True)
  2580. else:
  2581. self.ui.toolbarview.setVisible(False)
  2582. if tb & 8:
  2583. self.ui.toolbartools.setVisible(True)
  2584. else:
  2585. self.ui.toolbartools.setVisible(False)
  2586. if tb & 16:
  2587. self.ui.exc_edit_toolbar.setVisible(True)
  2588. else:
  2589. self.ui.exc_edit_toolbar.setVisible(False)
  2590. if tb & 32:
  2591. self.ui.geo_edit_toolbar.setVisible(True)
  2592. else:
  2593. self.ui.geo_edit_toolbar.setVisible(False)
  2594. if tb & 64:
  2595. self.ui.grb_edit_toolbar.setVisible(True)
  2596. else:
  2597. self.ui.grb_edit_toolbar.setVisible(False)
  2598. if tb & 128:
  2599. self.ui.snap_toolbar.setVisible(True)
  2600. else:
  2601. self.ui.snap_toolbar.setVisible(False)
  2602. if tb & 256:
  2603. self.ui.toolbarshell.setVisible(True)
  2604. else:
  2605. self.ui.toolbarshell.setVisible(False)
  2606. def on_restore_defaults_preferences(self):
  2607. """
  2608. Loads the application's factory default settings from factory_defaults.FlatConfig into
  2609. ``self.defaults``.
  2610. :return: None
  2611. """
  2612. App.log.debug("App.on_restore_defaults_preferences()")
  2613. filename = self.data_path + '/factory_defaults.FlatConfig'
  2614. if filename == "":
  2615. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2616. else:
  2617. try:
  2618. f = open(filename)
  2619. options = f.read()
  2620. f.close()
  2621. except IOError:
  2622. self.log.error("Could not load factory defaults file.")
  2623. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  2624. return
  2625. try:
  2626. defaults_from_file = json.loads(options)
  2627. except Exception:
  2628. e = sys.exc_info()[0]
  2629. App.log.error(str(e))
  2630. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  2631. return
  2632. self.defaults.update(defaults_from_file)
  2633. # update the dict that is used to restore the values in the defaults form if Cancel is clicked in the
  2634. # Preferences window
  2635. self.current_defaults.update(defaults_from_file)
  2636. self.on_preferences_edited()
  2637. self.inform.emit('[success] %s' % _("Preferences default values are restored."))
  2638. def on_import_preferences(self):
  2639. """
  2640. Loads the application default settings from a saved file into
  2641. ``self.defaults`` dictionary.
  2642. :return: None
  2643. """
  2644. self.report_usage("on_import_preferences")
  2645. App.log.debug("App.on_import_preferences()")
  2646. # Show file chooser
  2647. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2648. try:
  2649. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2650. directory=self.data_path,
  2651. filter=filter_)
  2652. except TypeError:
  2653. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2654. filter=filter_)
  2655. filename = str(filename)
  2656. if filename == "":
  2657. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2658. return
  2659. # Load in the defaults from the chosen file
  2660. self.fcDefaults.load_defaults(filename=filename)
  2661. self.on_preferences_edited()
  2662. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2663. def on_export_preferences(self):
  2664. """
  2665. Save the defaults dictionary to a file.
  2666. :return: None
  2667. """
  2668. self.report_usage("on_export_preferences")
  2669. App.log.debug("on_export_preferences()")
  2670. defaults_file_content = None
  2671. self.date = str(datetime.today()).rpartition('.')[0]
  2672. self.date = ''.join(c for c in self.date if c not in ':-')
  2673. self.date = self.date.replace(' ', '_')
  2674. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2675. try:
  2676. filename, _f = FCFileSaveDialog.get_saved_filename(
  2677. caption=_("Export FlatCAM Preferences"),
  2678. directory=self.data_path + '/preferences_' + self.date,
  2679. filter=filter__
  2680. )
  2681. except TypeError:
  2682. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2683. filename = str(filename)
  2684. defaults_from_file = {}
  2685. if filename == "":
  2686. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2687. return
  2688. else:
  2689. try:
  2690. f = open(filename, 'w')
  2691. defaults_file_content = f.read()
  2692. f.close()
  2693. except PermissionError:
  2694. self.inform.emit('[WARNING] %s' %
  2695. _("Permission denied, saving not possible.\n"
  2696. "Most likely another app is holding the file open and not accessible."))
  2697. return
  2698. except IOError:
  2699. App.log.debug('Creating a new preferences file ...')
  2700. f = open(filename, 'w')
  2701. json.dump({}, f)
  2702. f.close()
  2703. except Exception:
  2704. e = sys.exc_info()[0]
  2705. App.log.error("Could not load defaults file.")
  2706. App.log.error(str(e))
  2707. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load preferences file."))
  2708. return
  2709. try:
  2710. defaults_from_file = json.loads(defaults_file_content)
  2711. except Exception:
  2712. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2713. # Update options
  2714. self.defaults_read_form()
  2715. defaults_from_file.update(self.defaults)
  2716. self.propagate_defaults(silent=True)
  2717. # Save update options
  2718. try:
  2719. f = open(filename, "w")
  2720. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2721. f.close()
  2722. except Exception:
  2723. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2724. return
  2725. if self.defaults["global_open_style"] is False:
  2726. self.file_opened.emit("preferences", filename)
  2727. self.file_saved.emit("preferences", filename)
  2728. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2729. def save_to_file(self, content_to_save, txt_content):
  2730. """
  2731. Save something to a file.
  2732. :return: None
  2733. """
  2734. self.report_usage("save_to_file")
  2735. App.log.debug("save_to_file()")
  2736. self.date = str(datetime.today()).rpartition('.')[0]
  2737. self.date = ''.join(c for c in self.date if c not in ':-')
  2738. self.date = self.date.replace(' ', '_')
  2739. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2740. path_to_save = self.defaults["global_last_save_folder"] if\
  2741. self.defaults["global_last_save_folder"] is not None else self.data_path
  2742. try:
  2743. filename, _f = FCFileSaveDialog.get_saved_filename(
  2744. caption=_("Save to file"),
  2745. directory=path_to_save + '/file_' + self.date,
  2746. filter=filter__
  2747. )
  2748. except TypeError:
  2749. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2750. filename = str(filename)
  2751. if filename == "":
  2752. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2753. return
  2754. else:
  2755. try:
  2756. with open(filename, 'w') as f:
  2757. ___ = f.read()
  2758. except PermissionError:
  2759. self.inform.emit('[WARNING] %s' %
  2760. _("Permission denied, saving not possible.\n"
  2761. "Most likely another app is holding the file open and not accessible."))
  2762. return
  2763. except IOError:
  2764. App.log.debug('Creating a new file ...')
  2765. f = open(filename, 'w')
  2766. f.close()
  2767. except Exception:
  2768. e = sys.exc_info()[0]
  2769. App.log.error("Could not load the file.")
  2770. App.log.error(str(e))
  2771. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2772. return
  2773. # Save content
  2774. if filename.rpartition('.')[2].lower() == 'html':
  2775. file_content = content_to_save
  2776. else:
  2777. file_content = txt_content
  2778. try:
  2779. with open(filename, "w") as f:
  2780. f.write(file_content)
  2781. except Exception:
  2782. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2783. return
  2784. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2785. def save_geometry(self, x, y, width, height, notebook_width):
  2786. """
  2787. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2788. launch of the application.
  2789. :param x: X position of the main window
  2790. :param y: Y position of the main window
  2791. :param width: width of the main window
  2792. :param height: height of the main window
  2793. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2794. :return: None
  2795. """
  2796. self.defaults["global_def_win_x"] = x
  2797. self.defaults["global_def_win_y"] = y
  2798. self.defaults["global_def_win_w"] = width
  2799. self.defaults["global_def_win_h"] = height
  2800. self.defaults["global_def_notebook_width"] = notebook_width
  2801. self.save_defaults()
  2802. def restore_main_win_geom(self):
  2803. try:
  2804. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2805. self.defaults["global_def_win_y"],
  2806. self.defaults["global_def_win_w"],
  2807. self.defaults["global_def_win_h"])
  2808. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2809. except KeyError as e:
  2810. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2811. def message_dialog(self, title, message, kind="info"):
  2812. """
  2813. Builds and show a custom QMessageBox to be used in FlatCAM.
  2814. :param title: title of the QMessageBox
  2815. :param message: message to be displayed
  2816. :param kind: type of QMessageBox; will display a specific icon.
  2817. :return:
  2818. """
  2819. icon = {"info": QtWidgets.QMessageBox.Information,
  2820. "warning": QtWidgets.QMessageBox.Warning,
  2821. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2822. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2823. dlg.setText(message)
  2824. dlg.exec_()
  2825. def register_recent(self, kind, filename):
  2826. """
  2827. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2828. dictionary.
  2829. :param kind: type of file that was opened
  2830. :param filename: the path and file name for the file that was opened
  2831. :return:
  2832. """
  2833. self.log.debug("register_recent()")
  2834. self.log.debug(" %s" % kind)
  2835. self.log.debug(" %s" % filename)
  2836. record = {'kind': str(kind), 'filename': str(filename)}
  2837. if record in self.recent:
  2838. return
  2839. if record in self.recent_projects:
  2840. return
  2841. if record['kind'] == 'project':
  2842. self.recent_projects.insert(0, record)
  2843. else:
  2844. self.recent.insert(0, record)
  2845. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2846. self.recent.pop()
  2847. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2848. self.recent_projects.pop()
  2849. try:
  2850. f = open(self.data_path + '/recent.json', 'w')
  2851. except IOError:
  2852. App.log.error("Failed to open recent items file for writing.")
  2853. self.inform.emit('[ERROR_NOTCL] %s' %
  2854. _('Failed to open recent files file for writing.'))
  2855. return
  2856. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2857. f.close()
  2858. try:
  2859. fp = open(self.data_path + '/recent_projects.json', 'w')
  2860. except IOError:
  2861. App.log.error("Failed to open recent items file for writing.")
  2862. self.inform.emit('[ERROR_NOTCL] %s' %
  2863. _('Failed to open recent projects file for writing.'))
  2864. return
  2865. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2866. fp.close()
  2867. # Re-build the recent items menu
  2868. self.setup_recent_items()
  2869. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2870. """
  2871. Creates a new specialized FlatCAMObj and attaches it to the application,
  2872. this is, updates the GUI accordingly, any other records and plots it.
  2873. This method is thread-safe.
  2874. Notes:
  2875. * If the name is in use, the self.collection will modify it
  2876. when appending it to the collection. There is no need to handle
  2877. name conflicts here.
  2878. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2879. :type kind: str
  2880. :param name: Name for the object.
  2881. :type name: str
  2882. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2883. The function is called with 2 parameters: the new object and the App instance.
  2884. :type initialize: function
  2885. :param active:
  2886. :param fit:
  2887. :param plot: If to plot the resulting object
  2888. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2889. self.collection
  2890. :return: None
  2891. :rtype: None
  2892. """
  2893. App.log.debug("new_object()")
  2894. obj_plot = plot
  2895. obj_autoselected = autoselected
  2896. t0 = time.time() # Debug
  2897. # ## Create object
  2898. classdict = {
  2899. "gerber": GerberObject,
  2900. "excellon": ExcellonObject,
  2901. "cncjob": CNCJobObject,
  2902. "geometry": GeometryObject,
  2903. "script": ScriptObject,
  2904. "document": DocumentObject
  2905. }
  2906. App.log.debug("Calling object constructor...")
  2907. # Object creation/instantiation
  2908. obj = classdict[kind](name)
  2909. obj.units = self.options["units"]
  2910. # IMPORTANT
  2911. # The key names in defaults and options dictionary's are not random:
  2912. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2913. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2914. # copied to self.options. After that, below, depending on the type of
  2915. # object that is created, it will strip the name of the object and the underline (if the original key was
  2916. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2917. # "toolchange"
  2918. for option in self.options:
  2919. if option.find(kind + "_") == 0:
  2920. oname = option[len(kind) + 1:]
  2921. obj.options[oname] = self.options[option]
  2922. obj.isHovering = False
  2923. obj.notHovering = True
  2924. # Initialize as per user request
  2925. # User must take care to implement initialize
  2926. # in a thread-safe way as is is likely that we
  2927. # have been invoked in a separate thread.
  2928. t1 = time.time()
  2929. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2930. try:
  2931. return_value = initialize(obj, self)
  2932. except Exception as e:
  2933. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2934. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2935. msg += traceback.format_exc()
  2936. self.inform.emit(msg)
  2937. return "fail"
  2938. t2 = time.time()
  2939. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2940. if return_value == 'fail':
  2941. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2942. return "fail"
  2943. # Check units and convert if necessary
  2944. # This condition CAN be true because initialize() can change obj.units
  2945. if self.options["units"].upper() != obj.units.upper():
  2946. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2947. obj.convert_units(self.options["units"])
  2948. t3 = time.time()
  2949. self.log.debug("%f seconds converting units." % (t3 - t2))
  2950. # Create the bounding box for the object and then add the results to the obj.options
  2951. # But not for Scripts or for Documents
  2952. if kind != 'document' and kind != 'script':
  2953. try:
  2954. xmin, ymin, xmax, ymax = obj.bounds()
  2955. obj.options['xmin'] = xmin
  2956. obj.options['ymin'] = ymin
  2957. obj.options['xmax'] = xmax
  2958. obj.options['ymax'] = ymax
  2959. except Exception as e:
  2960. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2961. return "fail"
  2962. try:
  2963. if kind == 'excellon':
  2964. obj.fill_color = self.defaults["excellon_plot_fill"]
  2965. obj.outline_color = self.defaults["excellon_plot_line"]
  2966. if kind == 'gerber':
  2967. obj.fill_color = self.defaults["gerber_plot_fill"]
  2968. obj.outline_color = self.defaults["gerber_plot_line"]
  2969. except Exception as e:
  2970. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2971. # update the KeyWords list with the name of the file
  2972. self.myKeywords.append(obj.options['name'])
  2973. log.debug("Moving new object back to main thread.")
  2974. # Move the object to the main thread and let the app know that it is available.
  2975. obj.moveToThread(self.main_thread)
  2976. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2977. return obj
  2978. def new_excellon_object(self):
  2979. """
  2980. Creates a new, blank Excellon object.
  2981. :return: None
  2982. """
  2983. self.report_usage("new_excellon_object()")
  2984. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2985. def new_geometry_object(self):
  2986. """
  2987. Creates a new, blank and single-tool Geometry object.
  2988. :return: None
  2989. """
  2990. self.report_usage("new_geometry_object()")
  2991. def initialize(obj, app):
  2992. obj.multitool = False
  2993. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2994. def new_gerber_object(self):
  2995. """
  2996. Creates a new, blank Gerber object.
  2997. :return: None
  2998. """
  2999. self.report_usage("new_gerber_object()")
  3000. def initialize(grb_obj, app):
  3001. grb_obj.multitool = False
  3002. grb_obj.source_file = []
  3003. grb_obj.multigeo = False
  3004. grb_obj.follow = False
  3005. grb_obj.apertures = {}
  3006. grb_obj.solid_geometry = []
  3007. try:
  3008. grb_obj.options['xmin'] = 0
  3009. grb_obj.options['ymin'] = 0
  3010. grb_obj.options['xmax'] = 0
  3011. grb_obj.options['ymax'] = 0
  3012. except KeyError:
  3013. pass
  3014. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3015. def new_script_object(self, name=None, text=None):
  3016. """
  3017. Creates a new, blank TCL Script object.
  3018. :param name: a name for the new object
  3019. :param text: pass a source file to the newly created script to be loaded in it
  3020. :return: None
  3021. """
  3022. self.report_usage("new_script_object()")
  3023. if text is not None:
  3024. new_source_file = text
  3025. else:
  3026. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3027. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  3028. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  3029. "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  3030. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3031. "ListSys, MillDrills,\n" \
  3032. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3033. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  3034. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3035. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3036. "# SubtractRectangle, Version, WriteGCode\n"
  3037. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3038. '# %s:\n' % _('TCL Tutorial is here') + \
  3039. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3040. '# %s:\n' % _("FlatCAM commands list")
  3041. new_source_file += commands_list + '\n'
  3042. def initialize(obj, app):
  3043. obj.source_file = deepcopy(new_source_file)
  3044. if name is None:
  3045. outname = 'new_script'
  3046. else:
  3047. outname = name
  3048. self.new_object('script', outname, initialize, plot=False)
  3049. def new_document_object(self):
  3050. """
  3051. Creates a new, blank Document object.
  3052. :return: None
  3053. """
  3054. self.report_usage("new_document_object()")
  3055. def initialize(obj, app):
  3056. obj.source_file = ""
  3057. self.new_object('document', 'new_document', initialize, plot=False)
  3058. def on_object_created(self, obj, plot, auto_select):
  3059. """
  3060. Event callback for object creation.
  3061. It will add the new object to the collection. After that it will plot the object in a threaded way
  3062. :param obj: The newly created FlatCAM object.
  3063. :param plot: if the newly create object t obe plotted
  3064. :param auto_select: if the newly created object to be autoselected after creation
  3065. :return: None
  3066. """
  3067. t0 = time.time() # DEBUG
  3068. self.log.debug("on_object_created()")
  3069. # The Collection might change the name if there is a collision
  3070. self.collection.append(obj)
  3071. # after adding the object to the collection always update the list of objects that are in the collection
  3072. self.all_objects_list = self.collection.get_list()
  3073. # self.inform.emit('[selected] %s created & selected: %s' %
  3074. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3075. if obj.kind == 'gerber':
  3076. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3077. kind=obj.kind.capitalize(),
  3078. color='green',
  3079. name=str(obj.options['name']), tx=_("created/selected"))
  3080. )
  3081. elif obj.kind == 'excellon':
  3082. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3083. kind=obj.kind.capitalize(),
  3084. color='brown',
  3085. name=str(obj.options['name']), tx=_("created/selected"))
  3086. )
  3087. elif obj.kind == 'cncjob':
  3088. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3089. kind=obj.kind.capitalize(),
  3090. color='blue',
  3091. name=str(obj.options['name']), tx=_("created/selected"))
  3092. )
  3093. elif obj.kind == 'geometry':
  3094. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3095. kind=obj.kind.capitalize(),
  3096. color='red',
  3097. name=str(obj.options['name']), tx=_("created/selected"))
  3098. )
  3099. elif obj.kind == 'script':
  3100. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3101. kind=obj.kind.capitalize(),
  3102. color='orange',
  3103. name=str(obj.options['name']), tx=_("created/selected"))
  3104. )
  3105. elif obj.kind == 'document':
  3106. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3107. kind=obj.kind.capitalize(),
  3108. color='darkCyan',
  3109. name=str(obj.options['name']), tx=_("created/selected"))
  3110. )
  3111. # update the SHELL auto-completer model with the name of the new object
  3112. self.shell._edit.set_model_data(self.myKeywords)
  3113. if auto_select:
  3114. # select the just opened object but deselect the previous ones
  3115. self.collection.set_all_inactive()
  3116. self.collection.set_active(obj.options["name"])
  3117. else:
  3118. self.collection.set_all_inactive()
  3119. # here it is done the object plotting
  3120. def worker_task(t_obj):
  3121. with self.proc_container.new(_("Plotting")):
  3122. if isinstance(t_obj, CNCJobObject):
  3123. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3124. else:
  3125. t_obj.plot()
  3126. t1 = time.time() # DEBUG
  3127. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3128. self.object_plotted.emit(t_obj)
  3129. # Send to worker
  3130. # self.worker.add_task(worker_task, [self])
  3131. if plot is True:
  3132. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3133. def on_object_changed(self, obj):
  3134. """
  3135. Called whenever the geometry of the object was changed in some way.
  3136. This require the update of it's bounding values so it can be the selected on canvas.
  3137. Update the bounding box data from obj.options
  3138. :param obj: the object that was changed
  3139. :return: None
  3140. """
  3141. xmin, ymin, xmax, ymax = obj.bounds()
  3142. obj.options['xmin'] = xmin
  3143. obj.options['ymin'] = ymin
  3144. obj.options['xmax'] = xmax
  3145. obj.options['ymax'] = ymax
  3146. log.debug("Object changed, updating the bounding box data on self.options")
  3147. # delete the old selection shape
  3148. self.delete_selection_shape()
  3149. self.should_we_save = True
  3150. def on_object_plotted(self):
  3151. """
  3152. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3153. :return: None
  3154. """
  3155. self.on_zoom_fit(None)
  3156. def on_about(self):
  3157. """
  3158. Displays the "about" dialog found in the Menu --> Help.
  3159. :return: None
  3160. """
  3161. self.report_usage("on_about")
  3162. version = self.version
  3163. version_date = self.version_date
  3164. beta = self.beta
  3165. class AboutDialog(QtWidgets.QDialog):
  3166. def __init__(self, app, parent=None):
  3167. QtWidgets.QDialog.__init__(self, parent)
  3168. self.app = app
  3169. # Icon and title
  3170. self.setWindowIcon(parent.app_icon)
  3171. self.setWindowTitle(_("About FlatCAM"))
  3172. self.resize(600, 200)
  3173. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3174. # self.setStyleSheet(
  3175. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3176. # "background-attachment: fixed"
  3177. # )
  3178. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  3179. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3180. # palette = QtGui.QPalette()
  3181. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3182. # self.setPalette(palette)
  3183. logo = QtWidgets.QLabel()
  3184. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  3185. title = QtWidgets.QLabel(
  3186. "<font size=8><B>FlatCAM</B></font><BR>"
  3187. "{title}<BR>"
  3188. "<BR>"
  3189. "<BR>"
  3190. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3191. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3192. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3193. "<B>{issue}</B></a><BR>".format(
  3194. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3195. devel=_("Development"),
  3196. down=_("DOWNLOAD"),
  3197. issue=_("Issue tracker"))
  3198. )
  3199. title.setOpenExternalLinks(True)
  3200. closebtn = QtWidgets.QPushButton(_("Close"))
  3201. tab_widget = QtWidgets.QTabWidget()
  3202. description_label = QtWidgets.QLabel(
  3203. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3204. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3205. version=version,
  3206. beta=('BETA' if beta else ''),
  3207. date=version_date,
  3208. arch=platform.architecture()[0])
  3209. )
  3210. description_label.setOpenExternalLinks(True)
  3211. lic_lbl_header = QtWidgets.QLabel(
  3212. '%s:<br>%s<br>' % (
  3213. _('Licensed under the MIT license'),
  3214. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3215. "http://www.opensource.org/licenses/mit-license.php</a>"
  3216. )
  3217. )
  3218. lic_lbl_header.setOpenExternalLinks(True)
  3219. lic_lbl_body = QtWidgets.QLabel(
  3220. _(
  3221. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3222. 'of this software and associated documentation files (the "Software"), to deal\n'
  3223. 'in the Software without restriction, including without limitation the rights\n'
  3224. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3225. 'copies of the Software, and to permit persons to whom the Software is\n'
  3226. 'furnished to do so, subject to the following conditions:\n\n'
  3227. 'The above copyright notice and this permission notice shall be included in\n'
  3228. 'all copies or substantial portions of the Software.\n\n'
  3229. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3230. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3231. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3232. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3233. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3234. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3235. 'THE SOFTWARE.'
  3236. )
  3237. )
  3238. attributions_label = QtWidgets.QLabel(
  3239. _(
  3240. 'Some of the icons used are from the following sources:<br>'
  3241. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  3242. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3243. 'title="Flaticon">www.flaticon.com</a></div>'
  3244. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  3245. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  3246. )
  3247. )
  3248. attributions_label.setOpenExternalLinks(True)
  3249. # layouts
  3250. layout1 = QtWidgets.QVBoxLayout()
  3251. layout1_1 = QtWidgets.QHBoxLayout()
  3252. layout1_2 = QtWidgets.QHBoxLayout()
  3253. layout2 = QtWidgets.QHBoxLayout()
  3254. layout3 = QtWidgets.QHBoxLayout()
  3255. self.setLayout(layout1)
  3256. layout1.addLayout(layout1_1)
  3257. layout1.addLayout(layout1_2)
  3258. layout1.addLayout(layout2)
  3259. layout1.addLayout(layout3)
  3260. layout1_1.addStretch()
  3261. layout1_1.addWidget(description_label)
  3262. layout1_2.addWidget(tab_widget)
  3263. self.splash_tab = QtWidgets.QWidget()
  3264. self.splash_tab.setObjectName("splash_about")
  3265. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3266. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3267. tab_widget.addTab(self.splash_tab, _("Splash"))
  3268. self.programmmers_tab = QtWidgets.QWidget()
  3269. self.programmmers_tab.setObjectName("programmers_about")
  3270. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3271. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3272. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3273. self.translators_tab = QtWidgets.QWidget()
  3274. self.translators_tab.setObjectName("translators_about")
  3275. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3276. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3277. tab_widget.addTab(self.translators_tab, _("Translators"))
  3278. self.license_tab = QtWidgets.QWidget()
  3279. self.license_tab.setObjectName("license_about")
  3280. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3281. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3282. tab_widget.addTab(self.license_tab, _("License"))
  3283. self.attributions_tab = QtWidgets.QWidget()
  3284. self.attributions_tab.setObjectName("attributions_about")
  3285. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3286. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3287. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3288. self.splash_tab_layout.addWidget(logo, stretch=0)
  3289. self.splash_tab_layout.addWidget(title, stretch=1)
  3290. pal = QtGui.QPalette()
  3291. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3292. self.prog_grid_lay = QtWidgets.QGridLayout()
  3293. self.prog_grid_lay.setHorizontalSpacing(20)
  3294. self.prog_grid_lay.setColumnStretch(0, 0)
  3295. self.prog_grid_lay.setColumnStretch(2, 1)
  3296. prog_widget = QtWidgets.QWidget()
  3297. prog_widget.setLayout(self.prog_grid_lay)
  3298. prog_scroll = QtWidgets.QScrollArea()
  3299. prog_scroll.setWidget(prog_widget)
  3300. prog_scroll.setWidgetResizable(True)
  3301. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3302. prog_scroll.setPalette(pal)
  3303. self.programmmers_tab_layout.addWidget(prog_scroll)
  3304. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3308. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3313. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3315. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3317. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3318. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3319. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3320. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3321. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3322. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3323. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3325. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3328. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  3329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  3330. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  3331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  3332. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  3333. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  3334. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  3335. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  3336. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  3337. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  3338. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  3339. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 28, 0)
  3340. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 29, 0)
  3341. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 30, 0)
  3342. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 31, 0)
  3343. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 34, 0)
  3344. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  3345. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  3346. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  3347. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  3348. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  3349. self.translator_grid_lay = QtWidgets.QGridLayout()
  3350. self.translator_grid_lay.setColumnStretch(0, 0)
  3351. self.translator_grid_lay.setColumnStretch(1, 0)
  3352. self.translator_grid_lay.setColumnStretch(2, 1)
  3353. self.translator_grid_lay.setColumnStretch(3, 0)
  3354. # trans_widget = QtWidgets.QWidget()
  3355. # trans_widget.setLayout(self.translator_grid_lay)
  3356. # self.translators_tab_layout.addWidget(trans_widget)
  3357. # self.translators_tab_layout.addStretch()
  3358. trans_widget = QtWidgets.QWidget()
  3359. trans_widget.setLayout(self.translator_grid_lay)
  3360. trans_scroll = QtWidgets.QScrollArea()
  3361. trans_scroll.setWidget(trans_widget)
  3362. trans_scroll.setWidgetResizable(True)
  3363. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3364. trans_scroll.setPalette(pal)
  3365. self.translators_tab_layout.addWidget(trans_scroll)
  3366. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3367. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3368. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  3369. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  3370. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  3371. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3372. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  3373. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3374. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  3375. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  3376. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  3377. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3378. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  3379. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  3380. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  3381. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3382. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3383. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  3384. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3385. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3386. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  3387. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3388. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  3389. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  3390. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  3391. self.translator_grid_lay.setColumnStretch(0, 0)
  3392. self.translators_tab_layout.addStretch()
  3393. self.license_tab_layout.addWidget(lic_lbl_header)
  3394. self.license_tab_layout.addWidget(lic_lbl_body)
  3395. self.license_tab_layout.addStretch()
  3396. self.attributions_tab_layout.addWidget(attributions_label)
  3397. self.attributions_tab_layout.addStretch()
  3398. layout3.addStretch()
  3399. layout3.addWidget(closebtn)
  3400. closebtn.clicked.connect(self.accept)
  3401. AboutDialog(app=self, parent=self.ui).exec_()
  3402. def install_bookmarks(self, book_dict=None):
  3403. """
  3404. Install the bookmarks actions in the Help menu -> Bookmarks
  3405. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  3406. :return: None
  3407. """
  3408. if book_dict is None:
  3409. self.defaults["global_bookmarks"].update(
  3410. {
  3411. '1': ['FlatCAM', "http://flatcam.org"],
  3412. '2': ['Backup Site', ""]
  3413. }
  3414. )
  3415. else:
  3416. self.defaults["global_bookmarks"].clear()
  3417. self.defaults["global_bookmarks"].update(book_dict)
  3418. # first try to disconnect if somehow they get connected from elsewhere
  3419. for act in self.ui.menuhelp_bookmarks.actions():
  3420. try:
  3421. act.triggered.disconnect()
  3422. except TypeError:
  3423. pass
  3424. # clear all actions except the last one who is the Bookmark manager
  3425. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  3426. pass
  3427. else:
  3428. self.ui.menuhelp_bookmarks.removeAction(act)
  3429. bm_limit = int(self.defaults["global_bookmarks_limit"])
  3430. if self.defaults["global_bookmarks"]:
  3431. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  3432. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  3433. # the JSON is first making the keys as strings (therefore I have to use strings too
  3434. # or do the conversion :(
  3435. # )
  3436. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  3437. # the '10' entry jsut after '1' therefore ordering as strings
  3438. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  3439. key=lambda x: int(x[0]))
  3440. for entry, bookmark in sorted_bookmarks:
  3441. title = bookmark[0]
  3442. weblink = bookmark[1]
  3443. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  3444. act.setText(title)
  3445. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  3446. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  3447. if title == 'Backup Site' and weblink == "":
  3448. act.triggered.connect(self.on_backup_site)
  3449. else:
  3450. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  3451. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  3452. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  3453. def on_bookmarks_manager(self):
  3454. """
  3455. Adds the bookmark manager in a Tab in Plot Area
  3456. :return:
  3457. """
  3458. for idx in range(self.ui.plot_tab_area.count()):
  3459. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  3460. # there can be only one instance of Bookmark Manager at one time
  3461. return
  3462. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  3463. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  3464. # add the tab if it was closed
  3465. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  3466. # delete the absolute and relative position and messages in the infobar
  3467. self.ui.position_label.setText("")
  3468. self.ui.rel_position_label.setText("")
  3469. # Switch plot_area to preferences page
  3470. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  3471. def on_backup_site(self):
  3472. msgbox = QtWidgets.QMessageBox()
  3473. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  3474. "1. FlatCAM.org website is down\n"
  3475. "2. Someone forked FlatCAM project and wants to point\n"
  3476. "to his own website\n\n"
  3477. "If you can't get any informations about FlatCAM beta\n"
  3478. "use the YouTube channel link from the Help menu."))
  3479. msgbox.setWindowTitle(_("Alternative website"))
  3480. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  3481. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  3482. msgbox.setDefaultButton(bt_yes)
  3483. msgbox.exec_()
  3484. # response = msgbox.clickedButton()
  3485. def on_file_savedefaults(self):
  3486. """
  3487. Callback for menu item File->Save Defaults. Saves application default options
  3488. ``self.defaults`` to current_defaults.FlatConfig.
  3489. :return: None
  3490. """
  3491. self.save_defaults()
  3492. # def on_app_exit(self):
  3493. # self.report_usage("on_app_exit()")
  3494. #
  3495. # if self.collection.get_list():
  3496. # msgbox = QtWidgets.QMessageBox()
  3497. # # msgbox.setText("<B>Save changes ...</B>")
  3498. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3499. # "\n"
  3500. # "Do you want to Save the project?")
  3501. # msgbox.setWindowTitle("Save changes")
  3502. # msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  3503. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3504. # QtWidgets.QMessageBox.Cancel)
  3505. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3506. #
  3507. # response = msgbox.exec_()
  3508. #
  3509. # if response == QtWidgets.QMessageBox.Yes:
  3510. # self.on_file_saveprojectas(thread=False)
  3511. # elif response == QtWidgets.QMessageBox.Cancel:
  3512. # return
  3513. # self.save_defaults()
  3514. # else:
  3515. # self.save_defaults()
  3516. # log.debug("Application defaults saved ... Exit event.")
  3517. # QtWidgets.qApp.quit()
  3518. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3519. """
  3520. Saves application default options
  3521. ``self.defaults`` to current_defaults.FlatConfig file.
  3522. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3523. used at the next launch of the application.
  3524. :param silent: Whether to display a message in status bar or not; boolean
  3525. :param data_path: The path where to save the preferences file (current_defaults.FlatConfig)
  3526. When the application is portable it should be a mobile location.
  3527. :param first_time: Boolean. If True will execute some code when the app is run first time
  3528. :return: None
  3529. """
  3530. self.report_usage("save_defaults")
  3531. if data_path is None:
  3532. data_path = self.data_path
  3533. # Read options from file
  3534. try:
  3535. f = open(data_path + "/current_defaults.FlatConfig")
  3536. defaults_file_content = f.read()
  3537. f.close()
  3538. except Exception:
  3539. e = sys.exc_info()[0]
  3540. App.log.error("Could not load defaults file.")
  3541. App.log.error(str(e))
  3542. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  3543. return
  3544. try:
  3545. defaults = json.loads(defaults_file_content)
  3546. except Exception:
  3547. e = sys.exc_info()[0]
  3548. App.log.error("Failed to parse defaults file.")
  3549. App.log.error(str(e))
  3550. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  3551. return
  3552. # Update options
  3553. self.defaults_read_form()
  3554. defaults.update(self.defaults)
  3555. self.propagate_defaults(silent=True)
  3556. if first_time is False:
  3557. self.save_toolbar_view()
  3558. # Save update options
  3559. filename = data_path + "/current_defaults.FlatConfig"
  3560. try:
  3561. f = open(filename, "w")
  3562. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3563. f.close()
  3564. except Exception as e:
  3565. log.debug("App.save_defaults() --> %s" % str(e))
  3566. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  3567. return
  3568. if not silent:
  3569. self.inform.emit('[success] %s' % _("Preferences saved."))
  3570. # update the autosave timer
  3571. self.save_project_auto_update()
  3572. def save_toolbar_view(self):
  3573. """
  3574. Will save the toolbar view state to the defaults
  3575. :return: None
  3576. """
  3577. # Save the toolbar view
  3578. tb_status = 0
  3579. if self.ui.toolbarfile.isVisible():
  3580. tb_status += 1
  3581. if self.ui.toolbargeo.isVisible():
  3582. tb_status += 2
  3583. if self.ui.toolbarview.isVisible():
  3584. tb_status += 4
  3585. if self.ui.toolbartools.isVisible():
  3586. tb_status += 8
  3587. if self.ui.exc_edit_toolbar.isVisible():
  3588. tb_status += 16
  3589. if self.ui.geo_edit_toolbar.isVisible():
  3590. tb_status += 32
  3591. if self.ui.grb_edit_toolbar.isVisible():
  3592. tb_status += 64
  3593. if self.ui.snap_toolbar.isVisible():
  3594. tb_status += 128
  3595. if self.ui.toolbarshell.isVisible():
  3596. tb_status += 256
  3597. self.defaults["global_toolbar_view"] = tb_status
  3598. def final_save(self):
  3599. """
  3600. Callback for doing a preferences save to file whenever the application is about to quit.
  3601. If the project has changes, it will ask the user to save the project.
  3602. :return: None
  3603. """
  3604. if self.save_in_progress:
  3605. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  3606. return
  3607. if self.should_we_save and self.collection.get_list():
  3608. msgbox = QtWidgets.QMessageBox()
  3609. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3610. "\n"
  3611. "Do you want to Save the project?"))
  3612. msgbox.setWindowTitle(_("Save changes"))
  3613. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  3614. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3615. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3616. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3617. msgbox.setDefaultButton(bt_yes)
  3618. msgbox.exec_()
  3619. response = msgbox.clickedButton()
  3620. if response == bt_yes:
  3621. try:
  3622. self.trayIcon.hide()
  3623. except Exception:
  3624. pass
  3625. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3626. elif response == bt_no:
  3627. try:
  3628. self.trayIcon.hide()
  3629. except Exception:
  3630. pass
  3631. self.quit_application()
  3632. elif response == bt_cancel:
  3633. return
  3634. else:
  3635. try:
  3636. self.trayIcon.hide()
  3637. except Exception:
  3638. pass
  3639. self.quit_application()
  3640. def quit_application(self):
  3641. """
  3642. Called (as a pyslot or not) when the application is quit.
  3643. :return: None
  3644. """
  3645. self.save_defaults(silent=True)
  3646. log.debug("App.quit_application() --> App Defaults saved.")
  3647. if self.cmd_line_headless != 1:
  3648. # save app state to file
  3649. stgs = QSettings("Open Source", "FlatCAM")
  3650. stgs.setValue('saved_gui_state', self.ui.saveState())
  3651. stgs.setValue('maximized_gui', self.ui.isMaximized())
  3652. stgs.setValue(
  3653. 'language',
  3654. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  3655. )
  3656. stgs.setValue(
  3657. 'notebook_font_size',
  3658. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  3659. )
  3660. stgs.setValue(
  3661. 'axis_font_size',
  3662. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  3663. )
  3664. stgs.setValue(
  3665. 'textbox_font_size',
  3666. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  3667. )
  3668. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3669. stgs.setValue(
  3670. 'machinist',
  3671. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  3672. )
  3673. # This will write the setting to the platform specific storage.
  3674. del stgs
  3675. log.debug("App.quit_application() --> App UI state saved.")
  3676. # try to quit the QThread that run ArgsThread class
  3677. try:
  3678. self.th.quit()
  3679. except Exception as e:
  3680. log.debug("App.quit_application() --> %s" % str(e))
  3681. # try to quit the Socket opened by ArgsThread class
  3682. try:
  3683. self.new_launch.listener.close()
  3684. except Exception as err:
  3685. log.debug("App.quit_application() --> %s" % str(err))
  3686. # quit app by signalling for self.kill_app() method
  3687. # self.close_app_signal.emit()
  3688. QtWidgets.qApp.quit()
  3689. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  3690. # we use the following command
  3691. # sys.exit(0)
  3692. os._exit(0) # fix to work with Python 3.8
  3693. @staticmethod
  3694. def kill_app():
  3695. # QtCore.QCoreApplication.quit()
  3696. QtWidgets.qApp.quit()
  3697. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  3698. # we use the following command
  3699. sys.exit(0)
  3700. def on_portable_checked(self, state):
  3701. """
  3702. Callback called when the checkbox in Preferences GUI is checked.
  3703. It will set the application as portable by creating the preferences and recent files in the
  3704. 'config' folder found in the FlatCAM installation folder.
  3705. :param state: boolean, the state of the checkbox when clicked/checked
  3706. :return:
  3707. """
  3708. line_no = 0
  3709. data = None
  3710. if sys.platform != 'win32':
  3711. # this won't work in Linux or MacOS
  3712. return
  3713. # test if the app was frozen and choose the path for the configuration file
  3714. if getattr(sys, "frozen", False) is True:
  3715. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3716. else:
  3717. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3718. config_file = current_data_path + '\\configuration.txt'
  3719. try:
  3720. with open(config_file, 'r') as f:
  3721. try:
  3722. data = f.readlines()
  3723. except Exception as e:
  3724. log.debug('App.__init__() -->%s' % str(e))
  3725. return
  3726. except FileNotFoundError:
  3727. pass
  3728. for line in data:
  3729. line = line.strip('\n')
  3730. param = str(line).rpartition('=')
  3731. if param[0] == 'portable':
  3732. break
  3733. line_no += 1
  3734. if state:
  3735. data[line_no] = 'portable=True\n'
  3736. # create the new defauults files
  3737. # create current_defaults.FlatConfig file if there is none
  3738. try:
  3739. f = open(current_data_path + '/current_defaults.FlatConfig')
  3740. f.close()
  3741. except IOError:
  3742. App.log.debug('Creating empty current_defaults.FlatConfig')
  3743. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3744. json.dump({}, f)
  3745. f.close()
  3746. # create factory_defaults.FlatConfig file if there is none
  3747. try:
  3748. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3749. f.close()
  3750. except IOError:
  3751. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3752. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3753. json.dump({}, f)
  3754. f.close()
  3755. try:
  3756. f = open(current_data_path + '/recent.json')
  3757. f.close()
  3758. except IOError:
  3759. App.log.debug('Creating empty recent.json')
  3760. f = open(current_data_path + '/recent.json', 'w')
  3761. json.dump([], f)
  3762. f.close()
  3763. try:
  3764. fp = open(current_data_path + '/recent_projects.json')
  3765. fp.close()
  3766. except IOError:
  3767. App.log.debug('Creating empty recent_projects.json')
  3768. fp = open(current_data_path + '/recent_projects.json', 'w')
  3769. json.dump([], fp)
  3770. fp.close()
  3771. # save the current defaults to the new defaults file
  3772. self.save_defaults(silent=True, data_path=current_data_path)
  3773. else:
  3774. data[line_no] = 'portable=False\n'
  3775. with open(config_file, 'w') as f:
  3776. f.writelines(data)
  3777. def on_register_files(self, obj_type=None):
  3778. """
  3779. Called whenever there is a need to register file extensions with FlatCAM.
  3780. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3781. :param obj_type: the type of object to be register for.
  3782. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3783. :return: None
  3784. """
  3785. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3786. new_reg_path = 'Software\\Classes\\'
  3787. # find if the current user is admin
  3788. try:
  3789. is_admin = os.getuid() == 0
  3790. except AttributeError:
  3791. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3792. if is_admin is True:
  3793. root_path = winreg.HKEY_LOCAL_MACHINE
  3794. else:
  3795. root_path = winreg.HKEY_CURRENT_USER
  3796. # create the keys
  3797. def set_reg(name, root_path, new_reg_path, value):
  3798. try:
  3799. winreg.CreateKey(root_path, new_reg_path)
  3800. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3801. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3802. return True
  3803. except WindowsError:
  3804. return False
  3805. # delete key in registry
  3806. def delete_reg(root_path, reg_path, key_to_del):
  3807. key_to_del_path = reg_path + key_to_del
  3808. try:
  3809. winreg.DeleteKey(root_path, key_to_del_path)
  3810. return True
  3811. except WindowsError:
  3812. return False
  3813. if obj_type is None or obj_type == 'excellon':
  3814. exc_list = \
  3815. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3816. exc_list = [x for x in exc_list if x != '']
  3817. # register all keys in the Preferences window
  3818. for ext in exc_list:
  3819. new_k = new_reg_path + '.%s' % ext
  3820. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3821. # and unregister those that are no longer in the Preferences windows but are in the file
  3822. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3823. if ext not in exc_list:
  3824. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3825. # now write the updated extensions to the self.defaults
  3826. # new_ext = ''
  3827. # for ext in exc_list:
  3828. # new_ext = new_ext + ext + ', '
  3829. # self.defaults["fa_excellon"] = new_ext
  3830. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3831. if obj_type is None or obj_type == 'gcode':
  3832. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3833. gco_list = [x for x in gco_list if x != '']
  3834. # register all keys in the Preferences window
  3835. for ext in gco_list:
  3836. new_k = new_reg_path + '.%s' % ext
  3837. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3838. # and unregister those that are no longer in the Preferences windows but are in the file
  3839. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3840. if ext not in gco_list:
  3841. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3842. # now write the updated extensions to the self.defaults
  3843. # new_ext = ''
  3844. # for ext in gco_list:
  3845. # new_ext = new_ext + ext + ', '
  3846. # self.defaults["fa_gcode"] = new_ext
  3847. self.inform.emit('[success] %s' %
  3848. _("Selected GCode file extensions registered with FlatCAM."))
  3849. if obj_type is None or obj_type == 'gerber':
  3850. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3851. grb_list = [x for x in grb_list if x != '']
  3852. # register all keys in the Preferences window
  3853. for ext in grb_list:
  3854. new_k = new_reg_path + '.%s' % ext
  3855. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3856. # and unregister those that are no longer in the Preferences windows but are in the file
  3857. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3858. if ext not in grb_list:
  3859. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3860. # now write the updated extensions to the self.defaults
  3861. # new_ext = ''
  3862. # for ext in grb_list:
  3863. # new_ext = new_ext + ext + ', '
  3864. # self.defaults["fa_gerber"] = new_ext
  3865. self.inform.emit('[success] %s' %
  3866. _("Selected Gerber file extensions registered with FlatCAM."))
  3867. def add_extension(self, ext_type):
  3868. """
  3869. Add a file extension to the list for a specific object
  3870. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3871. :return:
  3872. """
  3873. if ext_type == 'excellon':
  3874. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3875. if new_ext == '':
  3876. return
  3877. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3878. if new_ext in old_val:
  3879. return
  3880. old_val.append(new_ext)
  3881. old_val.sort()
  3882. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3883. if ext_type == 'gcode':
  3884. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3885. if new_ext == '':
  3886. return
  3887. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3888. if new_ext in old_val:
  3889. return
  3890. old_val.append(new_ext)
  3891. old_val.sort()
  3892. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3893. if ext_type == 'gerber':
  3894. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3895. if new_ext == '':
  3896. return
  3897. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3898. if new_ext in old_val:
  3899. return
  3900. old_val.append(new_ext)
  3901. old_val.sort()
  3902. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3903. if ext_type == 'keyword':
  3904. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3905. if new_kw == '':
  3906. return
  3907. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3908. if new_kw in old_val:
  3909. return
  3910. old_val.append(new_kw)
  3911. old_val.sort()
  3912. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3913. # update the self.myKeywords so the model is updated
  3914. self.autocomplete_kw_list = \
  3915. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3916. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3917. self.shell._edit.set_model_data(self.myKeywords)
  3918. def del_extension(self, ext_type):
  3919. """
  3920. Remove a file extension from the list for a specific object
  3921. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3922. :return:
  3923. """
  3924. if ext_type == 'excellon':
  3925. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3926. if new_ext == '':
  3927. return
  3928. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3929. if new_ext not in old_val:
  3930. return
  3931. old_val.remove(new_ext)
  3932. old_val.sort()
  3933. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3934. if ext_type == 'gcode':
  3935. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3936. if new_ext == '':
  3937. return
  3938. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3939. if new_ext not in old_val:
  3940. return
  3941. old_val.remove(new_ext)
  3942. old_val.sort()
  3943. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3944. if ext_type == 'gerber':
  3945. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3946. if new_ext == '':
  3947. return
  3948. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3949. if new_ext not in old_val:
  3950. return
  3951. old_val.remove(new_ext)
  3952. old_val.sort()
  3953. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3954. if ext_type == 'keyword':
  3955. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3956. if new_kw == '':
  3957. return
  3958. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3959. if new_kw not in old_val:
  3960. return
  3961. old_val.remove(new_kw)
  3962. old_val.sort()
  3963. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3964. # update the self.myKeywords so the model is updated
  3965. self.autocomplete_kw_list = \
  3966. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3967. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3968. self.shell._edit.set_model_data(self.myKeywords)
  3969. def restore_extensions(self, ext_type):
  3970. """
  3971. Restore all file extensions associations with FlatCAM, for a specific object
  3972. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3973. :return:
  3974. """
  3975. if ext_type == 'excellon':
  3976. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3977. # for the ability to open Excellon files with .txt extension
  3978. new_exc_list = deepcopy(self.exc_list)
  3979. try:
  3980. new_exc_list.remove('txt')
  3981. except ValueError:
  3982. pass
  3983. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3984. if ext_type == 'gcode':
  3985. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3986. if ext_type == 'gerber':
  3987. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3988. if ext_type == 'keyword':
  3989. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3990. # update the self.myKeywords so the model is updated
  3991. self.autocomplete_kw_list = self.default_keywords
  3992. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3993. self.shell._edit.set_model_data(self.myKeywords)
  3994. def delete_all_extensions(self, ext_type):
  3995. """
  3996. Delete all file extensions associations with FlatCAM, for a specific object
  3997. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3998. :return:
  3999. """
  4000. if ext_type == 'excellon':
  4001. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4002. if ext_type == 'gcode':
  4003. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4004. if ext_type == 'gerber':
  4005. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4006. if ext_type == 'keyword':
  4007. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4008. # update the self.myKeywords so the model is updated
  4009. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4010. self.shell._edit.set_model_data(self.myKeywords)
  4011. def on_edit_join(self, name=None):
  4012. """
  4013. Callback for Edit->Join. Joins the selected geometry objects into
  4014. a new one.
  4015. :return: None
  4016. """
  4017. self.report_usage("on_edit_join()")
  4018. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4019. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4020. geo_type_set = set()
  4021. objs = self.collection.get_selected()
  4022. if len(objs) < 2:
  4023. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4024. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4025. return 'fail'
  4026. for obj in objs:
  4027. geo_type_set.add(obj.multigeo)
  4028. # if len(geo_type_list) == 1 means that all list elements are the same
  4029. if len(geo_type_set) != 1:
  4030. self.inform.emit('[ERROR] %s' %
  4031. _("Failed join. The Geometry objects are of different types.\n"
  4032. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4033. "convert from one to another and retry joining \n"
  4034. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4035. "the result may not be what was expected. \n"
  4036. "Check the generated GCODE."))
  4037. return
  4038. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4039. if True in geo_type_set:
  4040. def initialize(geo_obj, app):
  4041. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4042. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4043. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4044. for v in geo_obj.tools.values():
  4045. v['data']['name'] = obj_name_multi
  4046. self.new_object("geometry", obj_name_multi, initialize)
  4047. else:
  4048. def initialize(geo_obj, app):
  4049. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4050. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4051. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4052. for v in geo_obj.tools.values():
  4053. v['data']['name'] = obj_name_single
  4054. self.new_object("geometry", obj_name_single, initialize)
  4055. self.should_we_save = True
  4056. def on_edit_join_exc(self):
  4057. """
  4058. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4059. a new Excellon.
  4060. :return: None
  4061. """
  4062. self.report_usage("on_edit_join_exc()")
  4063. objs = self.collection.get_selected()
  4064. for obj in objs:
  4065. if not isinstance(obj, ExcellonObject):
  4066. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4067. return
  4068. if len(objs) < 2:
  4069. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4070. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4071. return 'fail'
  4072. def initialize(exc_obj, app):
  4073. ExcellonObject.merge(self, exc_list=objs, exc_final=exc_obj)
  4074. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4075. self.new_object("excellon", 'Combo_Excellon', initialize)
  4076. self.should_we_save = True
  4077. def on_edit_join_grb(self):
  4078. """
  4079. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4080. a new Gerber object.
  4081. :return: None
  4082. """
  4083. self.report_usage("on_edit_join_grb()")
  4084. objs = self.collection.get_selected()
  4085. for obj in objs:
  4086. if not isinstance(obj, GerberObject):
  4087. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4088. return
  4089. if len(objs) < 2:
  4090. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4091. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4092. return 'fail'
  4093. def initialize(grb_obj, app):
  4094. GerberObject.merge(self, grb_list=objs, grb_final=grb_obj)
  4095. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4096. self.new_object("gerber", 'Combo_Gerber', initialize)
  4097. self.should_we_save = True
  4098. def on_convert_singlegeo_to_multigeo(self):
  4099. """
  4100. Called for converting a Geometry object from single-geo to multi-geo.
  4101. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4102. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4103. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4104. the solid-geometry of that tool.
  4105. :return: None
  4106. """
  4107. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4108. obj = self.collection.get_active()
  4109. if obj is None:
  4110. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4111. return
  4112. if not isinstance(obj, GeometryObject):
  4113. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  4114. return
  4115. obj.multigeo = True
  4116. for tooluid, dict_value in obj.tools.items():
  4117. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4118. if not isinstance(obj.solid_geometry, list):
  4119. obj.solid_geometry = [obj.solid_geometry]
  4120. obj.solid_geometry[:] = []
  4121. obj.plot()
  4122. self.should_we_save = True
  4123. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4124. def on_convert_multigeo_to_singlegeo(self):
  4125. """
  4126. Called for converting a Geometry object from multi-geo to single-geo.
  4127. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4128. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4129. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4130. the solid-geometry of that tool.
  4131. :return: None
  4132. """
  4133. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4134. obj = self.collection.get_active()
  4135. if obj is None:
  4136. self.inform.emit('[ERROR_NOTCL] %s' %
  4137. _("Failed. Select a Geometry Object and try again."))
  4138. return
  4139. if not isinstance(obj, GeometryObject):
  4140. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4141. (_("Expected a GeometryObject, got"), type(obj)))
  4142. return
  4143. obj.multigeo = False
  4144. total_solid_geometry = []
  4145. for tooluid, dict_value in obj.tools.items():
  4146. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4147. # clear the original geometry
  4148. dict_value['solid_geometry'][:] = []
  4149. obj.solid_geometry = deepcopy(total_solid_geometry)
  4150. obj.plot()
  4151. self.should_we_save = True
  4152. self.inform.emit('[success] %s' %
  4153. _("A Geometry object was converted to SingleGeo type."))
  4154. def on_defaults_dict_change(self, field):
  4155. """
  4156. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4157. Edit -> Preferences tab window.
  4158. :param field: the key of the self.defaults dictionary that was changed.
  4159. :return: None
  4160. """
  4161. self.defaults_write_form_field(field)
  4162. if field == "units":
  4163. self.set_screen_units(self.defaults['units'])
  4164. def set_screen_units(self, units):
  4165. """
  4166. Set the FlatCAM units on the status bar.
  4167. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4168. :return: None
  4169. """
  4170. self.ui.units_label.setText("[" + units.lower() + "]")
  4171. def on_toggle_units_click(self):
  4172. try:
  4173. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4174. except (TypeError, AttributeError):
  4175. pass
  4176. if self.defaults["units"] == 'MM':
  4177. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4178. else:
  4179. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4180. self.on_toggle_units(no_pref=True)
  4181. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4182. lambda: self.on_toggle_units(no_pref=False))
  4183. def on_toggle_units(self, no_pref=False):
  4184. """
  4185. Callback for the Units radio-button change in the Preferences tab.
  4186. Changes the application's default units adn for the project too.
  4187. If changing the project's units, the change propagates to all of
  4188. the objects in the project.
  4189. :return: None
  4190. """
  4191. self.report_usage("on_toggle_units")
  4192. if self.toggle_units_ignore:
  4193. return
  4194. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4195. # If option is the same, then ignore
  4196. if new_units == self.defaults["units"].upper():
  4197. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4198. return
  4199. # Options to scale
  4200. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4201. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4202. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  4203. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4204. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  4205. "excellon_feedrate_probe",
  4206. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4207. "excellon_editor_slot_lin_pitch",
  4208. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4209. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4210. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  4211. "geometry_z_pdepth",
  4212. "geometry_feedrate_probe", "geometry_startz",
  4213. 'cncjob_tooldia',
  4214. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4215. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4216. "tools_nccnewdia",
  4217. "tools_2sided_drilldia", "tools_film_boundary",
  4218. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4219. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4220. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4221. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4222. "tools_transform_offset_y",
  4223. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4224. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4225. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4226. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4227. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4228. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4229. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4230. "tools_fiducials_line_thickness",
  4231. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4232. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4233. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4234. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4235. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4236. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  4237. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  4238. def scale_defaults(sfactor):
  4239. for dim in dimensions:
  4240. if dim == 'excellon_toolchangexy':
  4241. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4242. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4243. coords_xy[0] *= sfactor
  4244. coords_xy[1] *= sfactor
  4245. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4246. self.decimals, coords_xy[1])
  4247. elif dim == 'geometry_toolchangexy':
  4248. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4249. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4250. coords_xy[0] *= sfactor
  4251. coords_xy[1] *= sfactor
  4252. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4253. self.decimals, coords_xy[1])
  4254. elif dim == 'excellon_endxy':
  4255. coordinates = self.defaults["excellon_endxy"].split(",")
  4256. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4257. end_coords_xy[0] *= sfactor
  4258. end_coords_xy[1] *= sfactor
  4259. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  4260. self.decimals, end_coords_xy[1])
  4261. elif dim == 'geometry_endxy':
  4262. coordinates = self.defaults["geometry_endxy"].split(",")
  4263. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4264. end_coords_xy[0] *= sfactor
  4265. end_coords_xy[1] *= sfactor
  4266. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  4267. self.decimals, end_coords_xy[1])
  4268. elif dim == 'geometry_cnctooldia':
  4269. if type(self.defaults["geometry_cnctooldia"]) == float:
  4270. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  4271. else:
  4272. try:
  4273. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4274. tools_diameters = [eval(a) for a in tools_string if a != '']
  4275. except Exception as e:
  4276. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4277. continue
  4278. self.defaults['geometry_cnctooldia'] = ''
  4279. for t in range(len(tools_diameters)):
  4280. tools_diameters[t] *= sfactor
  4281. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  4282. elif dim == 'tools_ncctools':
  4283. if type(self.defaults["tools_ncctools"]) == float:
  4284. ncctools = [self.defaults["tools_ncctools"]]
  4285. else:
  4286. try:
  4287. tools_string = self.defaults["tools_ncctools"].split(",")
  4288. ncctools = [eval(a) for a in tools_string if a != '']
  4289. except Exception as e:
  4290. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4291. continue
  4292. self.defaults['tools_ncctools'] = ''
  4293. for t in range(len(ncctools)):
  4294. ncctools[t] *= sfactor
  4295. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  4296. elif dim == 'tools_solderpaste_tools':
  4297. if type(self.defaults["tools_solderpaste_tools"]) == float:
  4298. sptools = [self.defaults["tools_solderpaste_tools"]]
  4299. else:
  4300. try:
  4301. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4302. sptools = [eval(a) for a in tools_string if a != '']
  4303. except Exception as e:
  4304. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4305. continue
  4306. self.defaults['tools_solderpaste_tools'] = ""
  4307. for t in range(len(sptools)):
  4308. sptools[t] *= sfactor
  4309. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  4310. elif dim == 'tools_solderpaste_xy_toolchange':
  4311. try:
  4312. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4313. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4314. sp_coords[0] *= sfactor
  4315. sp_coords[1] *= sfactor
  4316. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  4317. self.decimals, sp_coords[1])
  4318. except Exception as e:
  4319. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4320. continue
  4321. elif dim == 'global_gridx' or dim == 'global_gridy':
  4322. if new_units == 'IN':
  4323. try:
  4324. val = float(self.defaults[dim]) * sfactor
  4325. except Exception as e:
  4326. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4327. continue
  4328. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4329. else:
  4330. try:
  4331. val = float(self.defaults[dim]) * sfactor
  4332. except Exception as e:
  4333. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4334. continue
  4335. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4336. else:
  4337. if self.defaults[dim]:
  4338. try:
  4339. val = float(self.defaults[dim]) * sfactor
  4340. except Exception as e:
  4341. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  4342. continue
  4343. self.defaults[dim] = val
  4344. # The scaling factor depending on choice of units.
  4345. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  4346. # Changing project units. Warn user.
  4347. msgbox = QtWidgets.QMessageBox()
  4348. msgbox.setWindowTitle(_("Toggle Units"))
  4349. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  4350. msgbox.setText(_("Changing the units of the project\n"
  4351. "will scale all objects.\n\n"
  4352. "Do you want to continue?"))
  4353. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4354. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4355. msgbox.setDefaultButton(bt_ok)
  4356. msgbox.exec_()
  4357. response = msgbox.clickedButton()
  4358. if response == bt_ok:
  4359. if no_pref is False:
  4360. self.defaults_read_form()
  4361. scale_defaults(factor)
  4362. self.defaults_write_form(fl_units=new_units)
  4363. self.defaults["units"] = new_units
  4364. # update the defaults from form, some may assume that the conversion is enough and it's not
  4365. self.on_options_app2project()
  4366. # update the objects
  4367. for obj in self.collection.get_list():
  4368. obj.convert_units(new_units)
  4369. # make that the properties stored in the object are also updated
  4370. self.object_changed.emit(obj)
  4371. # rebuild the object UI
  4372. obj.build_ui()
  4373. # change this only if the workspace is active
  4374. if self.defaults['global_workspace'] is True:
  4375. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  4376. # adjust the grid values on the main toolbar
  4377. val_x = float(self.defaults['global_gridx']) * factor
  4378. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  4379. current = self.collection.get_active()
  4380. if current is not None:
  4381. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4382. if not isinstance(current, GeometryObject):
  4383. current.to_form()
  4384. # replot all objects
  4385. self.plot_all()
  4386. # set the status labels to reflect the current FlatCAM units
  4387. self.set_screen_units(new_units)
  4388. # signal to the app that we changed the object properties and it shoud save the project
  4389. self.should_we_save = True
  4390. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  4391. else:
  4392. # Undo toggling
  4393. self.toggle_units_ignore = True
  4394. if self.defaults['units'].upper() == 'MM':
  4395. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4396. else:
  4397. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4398. self.toggle_units_ignore = False
  4399. # store the grid values so they are not changed in the next step
  4400. val_x = float(self.defaults['global_gridx'])
  4401. val_y = float(self.defaults['global_gridy'])
  4402. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  4403. self.defaults_read_form()
  4404. # the self.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  4405. # I don't want it for the grid values, so I update them here
  4406. self.defaults['global_gridx'] = val_x
  4407. self.defaults['global_gridy'] = val_y
  4408. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  4409. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  4410. def on_fullscreen(self, disable=False):
  4411. self.report_usage("on_fullscreen()")
  4412. flags = self.ui.windowFlags()
  4413. if self.toggle_fscreen is False and disable is False:
  4414. # self.ui.showFullScreen()
  4415. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  4416. a = self.ui.geometry()
  4417. self.x_pos = a.x()
  4418. self.y_pos = a.y()
  4419. self.width = a.width()
  4420. self.height = a.height()
  4421. # set new geometry to full desktop rect
  4422. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4423. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4424. # everything else will not work without this hack. This happen in Windows.
  4425. # https://bugreports.qt.io/browse/QTBUG-41309
  4426. desktop = QtWidgets.QApplication.desktop()
  4427. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4428. rec = desktop.screenGeometry(screen)
  4429. x = rec.x() - 1
  4430. y = rec.y() - 1
  4431. h = rec.height() + 2
  4432. w = rec.width() + 2
  4433. self.ui.setGeometry(x, y, w, h)
  4434. self.ui.show()
  4435. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4436. tb.setVisible(False)
  4437. self.ui.splitter_left.setVisible(False)
  4438. self.toggle_fscreen = True
  4439. elif self.toggle_fscreen is True or disable is True:
  4440. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  4441. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4442. self.ui.showNormal()
  4443. self.restore_toolbar_view()
  4444. self.ui.splitter_left.setVisible(True)
  4445. self.toggle_fscreen = False
  4446. def on_toggle_plotarea(self):
  4447. self.report_usage("on_toggle_plotarea()")
  4448. try:
  4449. name = self.ui.plot_tab_area.widget(0).objectName()
  4450. except AttributeError:
  4451. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4452. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4453. self.ui.plot_tab_area.protectTab(0)
  4454. return
  4455. if name != 'plotarea':
  4456. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4457. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4458. self.ui.plot_tab_area.protectTab(0)
  4459. else:
  4460. self.ui.plot_tab_area.closeTab(0)
  4461. def on_toggle_notebook(self):
  4462. if self.ui.splitter.sizes()[0] == 0:
  4463. self.ui.splitter.setSizes([1, 1])
  4464. self.ui.menu_toggle_nb.setChecked(True)
  4465. else:
  4466. self.ui.splitter.setSizes([0, 1])
  4467. self.ui.menu_toggle_nb.setChecked(False)
  4468. def on_toggle_axis(self):
  4469. self.report_usage("on_toggle_axis()")
  4470. if self.toggle_axis is False:
  4471. if self.is_legacy is False:
  4472. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4473. parent=self.plotcanvas.view.scene)
  4474. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4475. parent=self.plotcanvas.view.scene)
  4476. else:
  4477. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  4478. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  4479. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4480. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4481. self.plotcanvas.canvas.draw()
  4482. self.toggle_axis = True
  4483. else:
  4484. if self.is_legacy is False:
  4485. self.plotcanvas.v_line.parent = None
  4486. self.plotcanvas.h_line.parent = None
  4487. else:
  4488. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  4489. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  4490. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  4491. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  4492. self.plotcanvas.canvas.draw()
  4493. self.toggle_axis = False
  4494. def on_toggle_grid(self):
  4495. self.report_usage("on_toggle_grid()")
  4496. self.ui.grid_snap_btn.trigger()
  4497. self.on_grid_snap_triggered(state=True)
  4498. def on_toggle_grid_lines(self):
  4499. self.report_usage("on_toggle_grd_lines()")
  4500. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  4501. if tt_settings.contains("theme"):
  4502. theme = tt_settings.value('theme', type=str)
  4503. else:
  4504. theme = 'white'
  4505. if self.toggle_grid_lines is False:
  4506. if self.is_legacy is False:
  4507. if theme == 'white':
  4508. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  4509. else:
  4510. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  4511. else:
  4512. self.plotcanvas.axes.grid(True)
  4513. try:
  4514. self.plotcanvas.canvas.draw()
  4515. except IndexError:
  4516. pass
  4517. pass
  4518. self.toggle_grid_lines = True
  4519. else:
  4520. if self.is_legacy is False:
  4521. if theme == 'white':
  4522. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  4523. else:
  4524. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  4525. else:
  4526. self.plotcanvas.axes.grid(False)
  4527. try:
  4528. self.plotcanvas.canvas.draw()
  4529. except IndexError:
  4530. pass
  4531. self.toggle_grid_lines = False
  4532. if self.is_legacy is False:
  4533. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  4534. # - perhaps is a bug in VisPy implementation
  4535. if self.grid_status() is True:
  4536. self.app_cursor.enabled = False
  4537. self.app_cursor.enabled = True
  4538. else:
  4539. self.app_cursor.enabled = True
  4540. self.app_cursor.enabled = False
  4541. def show_preferences_gui(self):
  4542. """
  4543. Called to initialize and show the Preferences GUI
  4544. :return: None
  4545. """
  4546. self.gen_form = self.ui.general_defaults_form
  4547. self.ger_form = self.ui.gerber_defaults_form
  4548. self.exc_form = self.ui.excellon_defaults_form
  4549. self.geo_form = self.ui.geometry_defaults_form
  4550. self.cnc_form = self.ui.cncjob_defaults_form
  4551. self.tools_form = self.ui.tools_defaults_form
  4552. self.tools2_form = self.ui.tools2_defaults_form
  4553. self.fa_form = self.ui.util_defaults_form
  4554. try:
  4555. self.ui.general_scroll_area.takeWidget()
  4556. except Exception:
  4557. self.log.debug("Nothing to remove")
  4558. self.ui.general_scroll_area.setWidget(self.gen_form)
  4559. self.gen_form.show()
  4560. try:
  4561. self.ui.gerber_scroll_area.takeWidget()
  4562. except Exception:
  4563. self.log.debug("Nothing to remove")
  4564. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4565. self.ger_form.show()
  4566. try:
  4567. self.ui.excellon_scroll_area.takeWidget()
  4568. except Exception:
  4569. self.log.debug("Nothing to remove")
  4570. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4571. self.exc_form.show()
  4572. try:
  4573. self.ui.geometry_scroll_area.takeWidget()
  4574. except Exception:
  4575. self.log.debug("Nothing to remove")
  4576. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4577. self.geo_form.show()
  4578. try:
  4579. self.ui.cncjob_scroll_area.takeWidget()
  4580. except Exception:
  4581. self.log.debug("Nothing to remove")
  4582. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4583. self.cnc_form.show()
  4584. try:
  4585. self.ui.tools_scroll_area.takeWidget()
  4586. except Exception:
  4587. self.log.debug("Nothing to remove")
  4588. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4589. self.tools_form.show()
  4590. try:
  4591. self.ui.tools2_scroll_area.takeWidget()
  4592. except Exception:
  4593. self.log.debug("Nothing to remove")
  4594. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  4595. self.tools2_form.show()
  4596. try:
  4597. self.ui.fa_scroll_area.takeWidget()
  4598. except Exception:
  4599. self.log.debug("Nothing to remove")
  4600. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4601. self.fa_form.show()
  4602. self.log.debug("Finished Preferences GUI form initialization.")
  4603. # self.options2form()
  4604. def init_color_pickers_in_preferences_gui(self):
  4605. # Init Gerber Plot Colors
  4606. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_entry.set_value(self.defaults['gerber_plot_fill'])
  4607. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_button.setStyleSheet(
  4608. "background-color:%s;"
  4609. "border-color: dimgray" % str(self.defaults['gerber_plot_fill'])[:7])
  4610. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_spinner.set_value(
  4611. int(self.defaults['gerber_plot_fill'][7:9], 16))
  4612. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.setValue(
  4613. int(self.defaults['gerber_plot_fill'][7:9], 16))
  4614. self.ui.gerber_defaults_form.gerber_gen_group.pl_color_entry.set_value(self.defaults['gerber_plot_line'])
  4615. self.ui.gerber_defaults_form.gerber_gen_group.pl_color_button.setStyleSheet(
  4616. "background-color:%s;"
  4617. "border-color: dimgray" % str(self.defaults['gerber_plot_line'])[:7])
  4618. # Init Excellon Plot Colors
  4619. self.ui.excellon_defaults_form.excellon_gen_group.fill_color_entry.set_value(
  4620. self.defaults['excellon_plot_fill'])
  4621. self.ui.excellon_defaults_form.excellon_gen_group.fill_color_button.setStyleSheet(
  4622. "background-color:%s;"
  4623. "border-color: dimgray" % str(self.defaults['excellon_plot_fill'])[:7])
  4624. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_spinner.set_value(
  4625. int(self.defaults['excellon_plot_fill'][7:9], 16))
  4626. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.setValue(
  4627. int(self.defaults['excellon_plot_fill'][7:9], 16))
  4628. self.ui.excellon_defaults_form.excellon_gen_group.line_color_entry.set_value(
  4629. self.defaults['excellon_plot_line'])
  4630. self.ui.excellon_defaults_form.excellon_gen_group.line_color_button.setStyleSheet(
  4631. "background-color:%s;"
  4632. "border-color: dimgray" % str(self.defaults['excellon_plot_line'])[:7])
  4633. # Init Geometry Plot Colors
  4634. self.ui.geometry_defaults_form.geometry_gen_group.line_color_entry.set_value(
  4635. self.defaults['geometry_plot_line'])
  4636. self.ui.geometry_defaults_form.geometry_gen_group.line_color_button.setStyleSheet(
  4637. "background-color:%s;"
  4638. "border-color: dimgray" % str(self.defaults['geometry_plot_line'])[:7])
  4639. # Init CNCJob Travel Line Colors
  4640. self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_entry.set_value(
  4641. self.defaults['cncjob_travel_fill'])
  4642. self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_button.setStyleSheet(
  4643. "background-color:%s;"
  4644. "border-color: dimgray" % str(self.defaults['cncjob_travel_fill'])[:7])
  4645. self.ui.cncjob_defaults_form.cncjob_gen_group.tcolor_alpha_spinner.set_value(
  4646. int(self.defaults['cncjob_travel_fill'][7:9], 16))
  4647. self.ui.cncjob_defaults_form.cncjob_gen_group.tcolor_alpha_slider.setValue(
  4648. int(self.defaults['cncjob_travel_fill'][7:9], 16))
  4649. self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_entry.set_value(
  4650. self.defaults['cncjob_travel_line'])
  4651. self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_button.setStyleSheet(
  4652. "background-color:%s;"
  4653. "border-color: dimgray" % str(self.defaults['cncjob_travel_line'])[:7])
  4654. # Init CNCJob Plot Colors
  4655. self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_entry.set_value(
  4656. self.defaults['cncjob_plot_fill'])
  4657. self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_button.setStyleSheet(
  4658. "background-color:%s;"
  4659. "border-color: dimgray" % str(self.defaults['cncjob_plot_fill'])[:7])
  4660. self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_entry.set_value(
  4661. self.defaults['cncjob_plot_line'])
  4662. self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_button.setStyleSheet(
  4663. "background-color:%s;"
  4664. "border-color: dimgray" % str(self.defaults['cncjob_plot_line'])[:7])
  4665. # Init Left-Right Selection colors
  4666. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  4667. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4668. "background-color:%s;"
  4669. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  4670. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  4671. int(self.defaults['global_sel_fill'][7:9], 16))
  4672. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  4673. int(self.defaults['global_sel_fill'][7:9], 16))
  4674. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  4675. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4676. "background-color:%s;"
  4677. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  4678. # Init Right-Left Selection colors
  4679. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  4680. self.defaults['global_alt_sel_fill'])
  4681. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4682. "background-color:%s;"
  4683. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  4684. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  4685. int(self.defaults['global_sel_fill'][7:9], 16))
  4686. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  4687. int(self.defaults['global_sel_fill'][7:9], 16))
  4688. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  4689. self.defaults['global_alt_sel_line'])
  4690. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4691. "background-color:%s;"
  4692. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  4693. # Init Draw color and Selection Draw Color
  4694. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  4695. self.defaults['global_draw_color'])
  4696. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4697. "background-color:%s;"
  4698. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  4699. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  4700. self.defaults['global_sel_draw_color'])
  4701. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4702. "background-color:%s;"
  4703. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  4704. # Init Project Items color
  4705. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  4706. self.defaults['global_proj_item_color'])
  4707. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4708. "background-color:%s;"
  4709. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  4710. # Init Project Disabled Items color
  4711. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  4712. self.defaults['global_proj_item_dis_color'])
  4713. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4714. "background-color:%s;"
  4715. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  4716. # Init Project Disabled Items color
  4717. self.ui.general_defaults_form.general_app_set_group.mouse_cursor_entry.set_value(
  4718. self.defaults['global_cursor_color'])
  4719. self.ui.general_defaults_form.general_app_set_group.mouse_cursor_button.setStyleSheet(
  4720. "background-color:%s;"
  4721. "border-color: dimgray" % str(self.defaults['global_cursor_color'])[:7])
  4722. # Init the Annotation CNC Job color
  4723. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  4724. self.defaults['cncjob_annotation_fontcolor'])
  4725. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  4726. "background-color:%s;"
  4727. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  4728. # Init the Tool Film color
  4729. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  4730. self.defaults['tools_film_color'])
  4731. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  4732. "background-color:%s;"
  4733. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  4734. )
  4735. # Init the Tool QRCode colors
  4736. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  4737. self.defaults['tools_qrcode_fill_color'])
  4738. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4739. "background-color:%s;"
  4740. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  4741. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  4742. self.defaults['tools_qrcode_back_color'])
  4743. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4744. "background-color:%s;"
  4745. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  4746. def on_update_exc_export(self, state):
  4747. """
  4748. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4749. if the update_excellon_cb checkbox is checked
  4750. :param state: state of the checkbox whose signals is tied to his slot
  4751. :return:
  4752. """
  4753. if state:
  4754. # first try to disconnect
  4755. try:
  4756. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  4757. disconnect(self.on_excellon_format_changed)
  4758. except TypeError:
  4759. pass
  4760. try:
  4761. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  4762. disconnect(self.on_excellon_format_changed)
  4763. except TypeError:
  4764. pass
  4765. try:
  4766. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  4767. disconnect(self.on_excellon_format_changed)
  4768. except TypeError:
  4769. pass
  4770. try:
  4771. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  4772. disconnect(self.on_excellon_format_changed)
  4773. except TypeError:
  4774. pass
  4775. try:
  4776. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4777. disconnect(self.on_excellon_zeros_changed)
  4778. except TypeError:
  4779. pass
  4780. try:
  4781. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4782. disconnect(self.on_excellon_zeros_changed)
  4783. except TypeError:
  4784. pass
  4785. # the connect them
  4786. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  4787. self.on_excellon_format_changed)
  4788. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  4789. self.on_excellon_format_changed)
  4790. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  4791. self.on_excellon_format_changed)
  4792. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  4793. self.on_excellon_format_changed)
  4794. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4795. self.on_excellon_zeros_changed)
  4796. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4797. self.on_excellon_units_changed)
  4798. else:
  4799. # disconnect the signals
  4800. try:
  4801. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  4802. disconnect(self.on_excellon_format_changed)
  4803. except TypeError:
  4804. pass
  4805. try:
  4806. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  4807. disconnect(self.on_excellon_format_changed)
  4808. except TypeError:
  4809. pass
  4810. try:
  4811. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  4812. disconnect(self.on_excellon_format_changed)
  4813. except TypeError:
  4814. pass
  4815. try:
  4816. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  4817. disconnect(self.on_excellon_format_changed)
  4818. except TypeError:
  4819. pass
  4820. try:
  4821. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4822. disconnect(self.on_excellon_zeros_changed)
  4823. except TypeError:
  4824. pass
  4825. try:
  4826. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4827. disconnect(self.on_excellon_zeros_changed)
  4828. except TypeError:
  4829. pass
  4830. def on_excellon_format_changed(self):
  4831. """
  4832. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4833. :return: None
  4834. """
  4835. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4836. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4837. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4838. )
  4839. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4840. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4841. )
  4842. else:
  4843. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4844. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4845. )
  4846. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4847. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4848. )
  4849. def on_excellon_zeros_changed(self):
  4850. """
  4851. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4852. :return: None
  4853. """
  4854. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4855. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4856. )
  4857. def on_excellon_units_changed(self):
  4858. """
  4859. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4860. :return: None
  4861. """
  4862. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4863. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4864. )
  4865. self.on_excellon_format_changed()
  4866. def on_film_color_entry(self):
  4867. self.defaults['tools_film_color'] = \
  4868. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  4869. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  4870. "background-color:%s;"
  4871. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  4872. )
  4873. def on_film_color_button(self):
  4874. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  4875. c_dialog = QtWidgets.QColorDialog()
  4876. film_color = c_dialog.getColor(initial=current_color)
  4877. if film_color.isValid() is False:
  4878. return
  4879. # if new color is different then mark that the Preferences are changed
  4880. if film_color != current_color:
  4881. self.on_preferences_edited()
  4882. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  4883. "background-color:%s;"
  4884. "border-color: dimgray" % str(film_color.name())
  4885. )
  4886. new_val_sel = str(film_color.name())
  4887. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  4888. self.defaults['tools_film_color'] = new_val_sel
  4889. def on_qrcode_fill_color_entry(self):
  4890. self.defaults['tools_qrcode_fill_color'] = \
  4891. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  4892. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4893. "background-color:%s;"
  4894. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  4895. )
  4896. def on_qrcode_fill_color_button(self):
  4897. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  4898. c_dialog = QtWidgets.QColorDialog()
  4899. fill_color = c_dialog.getColor(initial=current_color)
  4900. if fill_color.isValid() is False:
  4901. return
  4902. # if new color is different then mark that the Preferences are changed
  4903. if fill_color != current_color:
  4904. self.on_preferences_edited()
  4905. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4906. "background-color:%s;"
  4907. "border-color: dimgray" % str(fill_color.name())
  4908. )
  4909. new_val_sel = str(fill_color.name())
  4910. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  4911. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  4912. def on_qrcode_back_color_entry(self):
  4913. self.defaults['tools_qrcode_back_color'] = \
  4914. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  4915. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4916. "background-color:%s;"
  4917. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  4918. )
  4919. def on_qrcode_back_color_button(self):
  4920. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  4921. c_dialog = QtWidgets.QColorDialog()
  4922. back_color = c_dialog.getColor(initial=current_color)
  4923. if back_color.isValid() is False:
  4924. return
  4925. # if new color is different then mark that the Preferences are changed
  4926. if back_color != current_color:
  4927. self.on_preferences_edited()
  4928. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4929. "background-color:%s;"
  4930. "border-color: dimgray" % str(back_color.name())
  4931. )
  4932. new_val_sel = str(back_color.name())
  4933. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  4934. self.defaults['tools_qrcode_back_color'] = new_val_sel
  4935. def on_tab_rmb_click(self, checked):
  4936. self.ui.notebook.set_detachable(val=checked)
  4937. self.defaults["global_tabs_detachable"] = checked
  4938. self.ui.plot_tab_area.set_detachable(val=checked)
  4939. self.defaults["global_tabs_detachable"] = checked
  4940. def on_tab_setup_context_menu(self):
  4941. initial_checked = self.defaults["global_tabs_detachable"]
  4942. action_name = str(_("Detachable Tabs"))
  4943. action = QtWidgets.QAction(self)
  4944. action.setCheckable(True)
  4945. action.setText(action_name)
  4946. action.setChecked(initial_checked)
  4947. self.ui.notebook.tabBar.addAction(action)
  4948. self.ui.plot_tab_area.tabBar.addAction(action)
  4949. try:
  4950. action.triggered.disconnect()
  4951. except TypeError:
  4952. pass
  4953. action.triggered.connect(self.on_tab_rmb_click)
  4954. def on_deselect_all(self):
  4955. self.collection.set_all_inactive()
  4956. self.delete_selection_shape()
  4957. def on_workspace_modified(self):
  4958. # self.save_defaults(silent=True)
  4959. if self.is_legacy is True:
  4960. self.plotcanvas.delete_workspace()
  4961. self.defaults_read_form()
  4962. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4963. def on_workspace(self):
  4964. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4965. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4966. else:
  4967. self.plotcanvas.delete_workspace()
  4968. self.defaults_read_form()
  4969. # self.save_defaults(silent=True)
  4970. def on_workspace_toggle(self):
  4971. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4972. try:
  4973. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4974. except TypeError:
  4975. pass
  4976. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4977. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4978. self.on_workspace()
  4979. def on_cursor_type(self, val):
  4980. """
  4981. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4982. :return: None
  4983. """
  4984. self.app_cursor.enabled = False
  4985. if val == 'small':
  4986. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4987. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4988. self.app_cursor = self.plotcanvas.new_cursor()
  4989. else:
  4990. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4991. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4992. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4993. if self.ui.grid_snap_btn.isChecked():
  4994. self.app_cursor.enabled = True
  4995. else:
  4996. self.app_cursor.enabled = False
  4997. def on_save_button(self, save_to_file=True):
  4998. log.debug("App.on_save_button() --> Applying preferences to file.")
  4999. # Preferences saved, update flag
  5000. self.preferences_changed_flag = False
  5001. # Preferences save, update the color of the Preferences Tab text
  5002. for idx in range(self.ui.plot_tab_area.count()):
  5003. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5004. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5005. # restore the default stylesheet by setting a blank one
  5006. self.ui.pref_apply_button.setStyleSheet("")
  5007. self.inform.emit('%s' % _("Preferences applied."))
  5008. # make sure we update the self.current_defaults dict used to undo changes to self.defaults
  5009. self.current_defaults.update(self.defaults)
  5010. if save_to_file:
  5011. self.save_defaults(silent=False)
  5012. # load the defaults so they are updated into the app
  5013. self.load_defaults(filename='current_defaults')
  5014. # Re-fresh project options
  5015. self.on_options_app2project()
  5016. settgs = QSettings("Open Source", "FlatCAM")
  5017. # save the notebook font size
  5018. fsize = self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  5019. settgs.setValue('notebook_font_size', fsize)
  5020. # save the axis font size
  5021. g_fsize = self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  5022. settgs.setValue('axis_font_size', g_fsize)
  5023. # save the textbox font size
  5024. tb_fsize = self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  5025. settgs.setValue('textbox_font_size', tb_fsize)
  5026. settgs.setValue(
  5027. 'machinist',
  5028. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  5029. )
  5030. # This will write the setting to the platform specific storage.
  5031. del settgs
  5032. if save_to_file:
  5033. # close the tab and delete it
  5034. for idx in range(self.ui.plot_tab_area.count()):
  5035. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5036. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5037. self.ui.plot_tab_area.closeTab(idx)
  5038. break
  5039. def on_pref_close_button(self):
  5040. # Preferences saved, update flag
  5041. self.preferences_changed_flag = False
  5042. try:
  5043. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_plot_area_tab_closed)
  5044. except TypeError:
  5045. pass
  5046. try:
  5047. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  5048. except (TypeError, AttributeError):
  5049. pass
  5050. self.defaults_write_form(source_dict=self.current_defaults)
  5051. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  5052. lambda: self.on_toggle_units(no_pref=False))
  5053. self.defaults.update(self.current_defaults)
  5054. # shared_items = {k: self.defaults[k] for k in self.defaults if k in self.current_defaults and
  5055. # self.defaults[k] == self.current_defaults[k]}
  5056. # print(len(self.defaults), len(shared_items))
  5057. # Preferences save, update the color of the Preferences Tab text
  5058. for idx in range(self.ui.plot_tab_area.count()):
  5059. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5060. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5061. self.ui.plot_tab_area.closeTab(idx)
  5062. break
  5063. self.inform.emit('%s' % _("Preferences closed without saving."))
  5064. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  5065. def on_tool_add_keypress(self):
  5066. # ## Current application units in Upper Case
  5067. self.units = self.defaults['units'].upper()
  5068. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5069. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5070. if notebook_widget_name == 'selected_tab':
  5071. if self.collection.get_active().kind == 'geometry':
  5072. # Tool add works for Geometry only if Advanced is True in Preferences
  5073. if self.defaults["global_app_level"] == 'a':
  5074. tool_add_popup = FCInputDialog(title="New Tool ...",
  5075. text='Enter a Tool Diameter:',
  5076. min=0.0000, max=99.9999, decimals=4)
  5077. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  5078. val, ok = tool_add_popup.get_value()
  5079. if ok:
  5080. if float(val) == 0:
  5081. self.inform.emit('[WARNING_NOTCL] %s' %
  5082. _("Please enter a tool diameter with non-zero value, in Float format."))
  5083. return
  5084. self.collection.get_active().on_tool_add(dia=float(val))
  5085. else:
  5086. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  5087. else:
  5088. msgbox = QtWidgets.QMessageBox()
  5089. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5090. "Go to Preferences -> General - Show Advanced Options."))
  5091. msgbox.setWindowTitle("Tool adding ...")
  5092. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  5093. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5094. msgbox.setDefaultButton(bt_ok)
  5095. msgbox.exec_()
  5096. # work only if the notebook tab on focus is the Tools_Tab
  5097. if notebook_widget_name == 'tool_tab':
  5098. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5099. # and only if the tool is NCC Tool
  5100. if tool_widget == self.ncclear_tool.toolName:
  5101. self.ncclear_tool.on_add_tool_by_key()
  5102. # and only if the tool is Paint Area Tool
  5103. elif tool_widget == self.paint_tool.toolName:
  5104. self.paint_tool.on_add_tool_by_key()
  5105. # and only if the tool is Solder Paste Dispensing Tool
  5106. elif tool_widget == self.paste_tool.toolName:
  5107. self.paste_tool.on_add_tool_by_key()
  5108. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5109. # See description bellow.
  5110. def on_delete_keypress(self):
  5111. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5112. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5113. if notebook_widget_name == 'selected_tab':
  5114. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  5115. self.collection.get_active().on_tool_delete()
  5116. # work only if the notebook tab on focus is the Tools_Tab
  5117. elif notebook_widget_name == 'tool_tab':
  5118. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5119. # and only if the tool is NCC Tool
  5120. if tool_widget == self.ncclear_tool.toolName:
  5121. self.ncclear_tool.on_tool_delete()
  5122. # and only if the tool is Paint Tool
  5123. elif tool_widget == self.paint_tool.toolName:
  5124. self.paint_tool.on_tool_delete()
  5125. # and only if the tool is Solder Paste Dispensing Tool
  5126. elif tool_widget == self.paste_tool.toolName:
  5127. self.paste_tool.on_tool_delete()
  5128. else:
  5129. self.on_delete()
  5130. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5131. # some screens you have to be careful where you hover with your mouse.
  5132. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5133. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5134. # Complicated, I know :)
  5135. def on_delete(self, force_deletion=False):
  5136. """
  5137. Delete the currently selected FlatCAMObjs.
  5138. :param force_deletion: used by Tcl command
  5139. :return: None
  5140. """
  5141. self.report_usage("on_delete()")
  5142. response = None
  5143. bt_ok = None
  5144. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5145. # a geometry object before we update it.
  5146. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5147. and self.grb_editor.editor_active is False:
  5148. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  5149. msgbox = QtWidgets.QMessageBox()
  5150. msgbox.setWindowTitle(_("Delete objects"))
  5151. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  5152. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5153. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5154. "the selected objects?"))
  5155. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5156. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5157. msgbox.setDefaultButton(bt_ok)
  5158. msgbox.exec_()
  5159. response = msgbox.clickedButton()
  5160. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  5161. response = bt_ok
  5162. if response == bt_ok:
  5163. if self.collection.get_active():
  5164. self.log.debug("App.on_delete()")
  5165. for obj_active in self.collection.get_selected():
  5166. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  5167. if isinstance(obj_active, GerberObject):
  5168. for el in obj_active.mark_shapes:
  5169. obj_active.mark_shapes[el].clear(update=True)
  5170. obj_active.mark_shapes[el].enabled = False
  5171. # obj_active.mark_shapes[el] = None
  5172. del el
  5173. elif isinstance(obj_active, CNCJobObject):
  5174. try:
  5175. obj_active.text_col.enabled = False
  5176. del obj_active.text_col
  5177. obj_active.annotation.clear(update=True)
  5178. del obj_active.annotation
  5179. except AttributeError as e:
  5180. log.debug(
  5181. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  5182. )
  5183. while self.collection.get_selected():
  5184. self.delete_first_selected()
  5185. self.inform.emit('%s...' % _("Object(s) deleted"))
  5186. # make sure that the selection shape is deleted, too
  5187. self.delete_selection_shape()
  5188. else:
  5189. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  5190. else:
  5191. self.inform.emit(_("Save the work in Editor and try again ..."))
  5192. def delete_first_selected(self):
  5193. # Keep this for later
  5194. try:
  5195. sel_obj = self.collection.get_active()
  5196. name = sel_obj.options["name"]
  5197. isPlotted = sel_obj.options["plot"]
  5198. except AttributeError:
  5199. self.log.debug("Nothing selected for deletion")
  5200. return
  5201. if self.is_legacy is True:
  5202. # Remove plot only if the object was plotted otherwise delaxes will fail
  5203. if isPlotted:
  5204. try:
  5205. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5206. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5207. except Exception as e:
  5208. log.debug("App.delete_first_selected() --> %s" % str(e))
  5209. self.plotcanvas.auto_adjust_axes()
  5210. # Remove from dictionary
  5211. self.collection.delete_active()
  5212. # Clear form
  5213. self.setup_component_editor()
  5214. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  5215. def on_set_origin(self):
  5216. """
  5217. Set the origin to the left mouse click position
  5218. :return: None
  5219. """
  5220. # display the message for the user
  5221. # and ask him to click on the desired position
  5222. self.report_usage("on_set_origin()")
  5223. def origin_replot():
  5224. def worker_task():
  5225. with self.proc_container.new('%s...' % _("Plotting")):
  5226. for obj in self.collection.get_list():
  5227. obj.plot()
  5228. self.plotcanvas.fit_view()
  5229. if self.is_legacy:
  5230. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5231. else:
  5232. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5233. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5234. self.inform.emit(_('Click to set the origin ...'))
  5235. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5236. # first disconnect it as it may have been used by something else
  5237. try:
  5238. self.replot_signal.disconnect()
  5239. except TypeError:
  5240. pass
  5241. self.replot_signal[list].connect(origin_replot)
  5242. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5243. """
  5244. :param event:
  5245. :param location:
  5246. :param noplot:
  5247. :param use_thread:
  5248. :return:
  5249. """
  5250. noplot_sig = noplot
  5251. def worker_task():
  5252. with self.proc_container.new(_("Setting Origin...")):
  5253. obj_list = self.collection.get_list()
  5254. for obj in obj_list:
  5255. obj.offset((x, y))
  5256. self.object_changed.emit(obj)
  5257. # Update the object bounding box options
  5258. a, b, c, d = obj.bounds()
  5259. obj.options['xmin'] = a
  5260. obj.options['ymin'] = b
  5261. obj.options['xmax'] = c
  5262. obj.options['ymax'] = d
  5263. self.inform.emit('[success] %s...' % _('Origin set'))
  5264. for obj in obj_list:
  5265. out_name = obj.options["name"]
  5266. if obj.kind == 'gerber':
  5267. obj.source_file = self.export_gerber(
  5268. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  5269. elif obj.kind == 'excellon':
  5270. obj.source_file = self.export_excellon(
  5271. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  5272. if noplot_sig is False:
  5273. self.replot_signal.emit([])
  5274. if location is not None:
  5275. if len(location) != 2:
  5276. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  5277. return 'fail'
  5278. x, y = location
  5279. if use_thread is True:
  5280. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5281. else:
  5282. worker_task()
  5283. self.should_we_save = True
  5284. return
  5285. if event.button == 1:
  5286. if self.is_legacy is False:
  5287. event_pos = event.pos
  5288. else:
  5289. event_pos = (event.xdata, event.ydata)
  5290. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5291. if self.grid_status():
  5292. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5293. else:
  5294. pos = pos_canvas
  5295. x = 0 - pos[0]
  5296. y = 0 - pos[1]
  5297. if use_thread is True:
  5298. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5299. else:
  5300. worker_task()
  5301. self.should_we_save = True
  5302. def on_move2origin(self, use_thread=True):
  5303. """
  5304. Move selected objects to origin.
  5305. :param use_thread: Control if to use threaded operation. Boolean.
  5306. :return:
  5307. """
  5308. def worker_task():
  5309. with self.proc_container.new(_("Moving to Origin...")):
  5310. obj_list = self.collection.get_selected()
  5311. if not obj_list:
  5312. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  5313. return
  5314. xminlist = []
  5315. yminlist = []
  5316. # first get a bounding box to fit all
  5317. for obj in obj_list:
  5318. xmin, ymin, xmax, ymax = obj.bounds()
  5319. xminlist.append(xmin)
  5320. yminlist.append(ymin)
  5321. # get the minimum x,y for all objects selected
  5322. x = min(xminlist)
  5323. y = min(yminlist)
  5324. for obj in obj_list:
  5325. obj.offset((-x, -y))
  5326. self.object_changed.emit(obj)
  5327. # Update the object bounding box options
  5328. a, b, c, d = obj.bounds()
  5329. obj.options['xmin'] = a
  5330. obj.options['ymin'] = b
  5331. obj.options['xmax'] = c
  5332. obj.options['ymax'] = d
  5333. for obj in obj_list:
  5334. obj.plot()
  5335. for obj in obj_list:
  5336. out_name = obj.options["name"]
  5337. if obj.kind == 'gerber':
  5338. obj.source_file = self.export_gerber(
  5339. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  5340. elif obj.kind == 'excellon':
  5341. obj.source_file = self.export_excellon(
  5342. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  5343. self.inform.emit('[success] %s...' % _('Origin set'))
  5344. if use_thread is True:
  5345. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5346. else:
  5347. worker_task()
  5348. self.should_we_save = True
  5349. def on_jump_to(self, custom_location=None, fit_center=True):
  5350. """
  5351. Jump to a location by setting the mouse cursor location.
  5352. :param custom_location: Jump to a specified point. (x, y) tuple.
  5353. :param fit_center: If to fit view. Boolean.
  5354. :return:
  5355. """
  5356. self.report_usage("on_jump_to()")
  5357. if not custom_location:
  5358. dia_box_location = None
  5359. try:
  5360. dia_box_location = eval(self.clipboard.text())
  5361. except Exception:
  5362. pass
  5363. if type(dia_box_location) == tuple:
  5364. dia_box_location = str(dia_box_location)
  5365. else:
  5366. dia_box_location = None
  5367. # dia_box = Dialog_box(title=_("Jump to ..."),
  5368. # label=_("Enter the coordinates in format X,Y:"),
  5369. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5370. # initial_text=dia_box_location)
  5371. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  5372. label=_("Enter the coordinates in format X,Y:"),
  5373. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5374. initial_text=dia_box_location,
  5375. reference=self.defaults['global_jump_ref'])
  5376. if dia_box.ok is True:
  5377. try:
  5378. location = eval(dia_box.location)
  5379. if not isinstance(location, tuple):
  5380. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5381. return
  5382. if dia_box.reference == 'rel':
  5383. rel_x = self.mouse[0] + location[0]
  5384. rel_y = self.mouse[1] + location[1]
  5385. location = (rel_x, rel_y)
  5386. self.defaults['global_jump_ref'] = dia_box.reference
  5387. except Exception:
  5388. return
  5389. else:
  5390. return
  5391. else:
  5392. location = custom_location
  5393. self.jump_signal.emit(location)
  5394. if fit_center:
  5395. self.plotcanvas.fit_center(loc=location)
  5396. cursor = QtGui.QCursor()
  5397. if self.is_legacy is False:
  5398. # I don't know where those differences come from but they are constant for the current
  5399. # execution of the application and they are multiples of a value around 0.0263mm.
  5400. # In a random way sometimes they are more sometimes they are less
  5401. # if units == 'MM':
  5402. # cal_factor = 0.0263
  5403. # else:
  5404. # cal_factor = 0.0263 / 25.4
  5405. cal_location = (location[0], location[1])
  5406. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5407. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  5408. j_pos = (
  5409. int(canvas_origin.x() + round(jump_loc[0])),
  5410. int(canvas_origin.y() + round(jump_loc[1]))
  5411. )
  5412. cursor.setPos(j_pos[0], j_pos[1])
  5413. else:
  5414. # find the canvas origin which is in the top left corner
  5415. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5416. # determine the coordinates for the lowest left point of the canvas
  5417. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5418. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  5419. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  5420. # canvas) and the point (width, height) is in the top-right location
  5421. loc = self.plotcanvas.axes.transData.transform_point(location)
  5422. j_pos = (
  5423. int(x0 + loc[0]),
  5424. int(y0 - loc[1])
  5425. )
  5426. cursor.setPos(j_pos[0], j_pos[1])
  5427. self.plotcanvas.mouse = [location[0], location[1]]
  5428. if self.defaults["global_cursor_color_enabled"] is True:
  5429. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  5430. else:
  5431. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  5432. if self.grid_status():
  5433. # Update cursor
  5434. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  5435. symbol='++', edge_color=self.cursor_color_3D,
  5436. edge_width=self.defaults["global_cursor_width"],
  5437. size=self.defaults["global_cursor_size"])
  5438. # Set the position label
  5439. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5440. "<b>Y</b>: %.4f" % (location[0], location[1]))
  5441. # Set the relative position label
  5442. dx = location[0] - float(self.rel_point1[0])
  5443. dy = location[1] - float(self.rel_point1[1])
  5444. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5445. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5446. self.inform.emit('[success] %s' % _("Done."))
  5447. return location
  5448. def on_locate(self, obj, fit_center=True):
  5449. """
  5450. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  5451. :param obj: The object on which to locate certain points
  5452. :param fit_center: If to fit view. Boolean.
  5453. :return: A point location. (x, y) tuple.
  5454. """
  5455. self.report_usage("on_locate()")
  5456. if obj is None:
  5457. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5458. return 'fail'
  5459. class DialogBoxChoice(QtWidgets.QDialog):
  5460. def __init__(self, title=None, icon=None, choice='bl'):
  5461. """
  5462. :param title: string with the window title
  5463. """
  5464. super(DialogBoxChoice, self).__init__()
  5465. self.ok = False
  5466. self.setWindowIcon(icon)
  5467. self.setWindowTitle(str(title))
  5468. self.form = QtWidgets.QFormLayout(self)
  5469. self.ref_radio = RadioSet([
  5470. {"label": _("Bottom-Left"), "value": "bl"},
  5471. {"label": _("Top-Left"), "value": "tl"},
  5472. {"label": _("Bottom-Right"), "value": "br"},
  5473. {"label": _("Top-Right"), "value": "tr"},
  5474. {"label": _("Center"), "value": "c"}
  5475. ], orientation='vertical', stretch=False)
  5476. self.ref_radio.set_value(choice)
  5477. self.form.addRow(self.ref_radio)
  5478. self.button_box = QtWidgets.QDialogButtonBox(
  5479. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  5480. Qt.Horizontal, parent=self)
  5481. self.form.addRow(self.button_box)
  5482. self.button_box.accepted.connect(self.accept)
  5483. self.button_box.rejected.connect(self.reject)
  5484. if self.exec_() == QtWidgets.QDialog.Accepted:
  5485. self.ok = True
  5486. self.location_point = self.ref_radio.get_value()
  5487. else:
  5488. self.ok = False
  5489. self.location_point = None
  5490. dia_box = DialogBoxChoice(title=_("Locate ..."),
  5491. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  5492. choice=self.defaults['global_locate_pt'])
  5493. if dia_box.ok is True:
  5494. try:
  5495. location_point = dia_box.location_point
  5496. self.defaults['global_locate_pt'] = dia_box.location_point
  5497. except Exception:
  5498. return
  5499. else:
  5500. return
  5501. loc_b = obj.bounds()
  5502. if location_point == 'bl':
  5503. location = (loc_b[0], loc_b[1])
  5504. elif location_point == 'tl':
  5505. location = (loc_b[0], loc_b[3])
  5506. elif location_point == 'br':
  5507. location = (loc_b[2], loc_b[1])
  5508. elif location_point == 'tr':
  5509. location = (loc_b[2], loc_b[3])
  5510. else:
  5511. # center
  5512. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  5513. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  5514. location = (cx, cy)
  5515. self.locate_signal.emit(location, location_point)
  5516. if fit_center:
  5517. self.plotcanvas.fit_center(loc=location)
  5518. cursor = QtGui.QCursor()
  5519. if self.is_legacy is False:
  5520. # I don't know where those differences come from but they are constant for the current
  5521. # execution of the application and they are multiples of a value around 0.0263mm.
  5522. # In a random way sometimes they are more sometimes they are less
  5523. # if units == 'MM':
  5524. # cal_factor = 0.0263
  5525. # else:
  5526. # cal_factor = 0.0263 / 25.4
  5527. cal_location = (location[0], location[1])
  5528. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5529. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  5530. j_pos = (
  5531. int(canvas_origin.x() + round(jump_loc[0])),
  5532. int(canvas_origin.y() + round(jump_loc[1]))
  5533. )
  5534. cursor.setPos(j_pos[0], j_pos[1])
  5535. else:
  5536. # find the canvas origin which is in the top left corner
  5537. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5538. # determine the coordinates for the lowest left point of the canvas
  5539. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5540. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  5541. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  5542. # canvas) and the point (width, height) is in the top-right location
  5543. loc = self.plotcanvas.axes.transData.transform_point(location)
  5544. j_pos = (
  5545. int(x0 + loc[0]),
  5546. int(y0 - loc[1])
  5547. )
  5548. cursor.setPos(j_pos[0], j_pos[1])
  5549. self.plotcanvas.mouse = [location[0], location[1]]
  5550. if self.defaults["global_cursor_color_enabled"] is True:
  5551. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  5552. else:
  5553. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  5554. if self.grid_status():
  5555. # Update cursor
  5556. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  5557. symbol='++', edge_color=self.cursor_color_3D,
  5558. edge_width=self.defaults["global_cursor_width"],
  5559. size=self.defaults["global_cursor_size"])
  5560. # Set the position label
  5561. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5562. "<b>Y</b>: %.4f" % (location[0], location[1]))
  5563. # Set the relative position label
  5564. self.dx = location[0] - float(self.rel_point1[0])
  5565. self.dy = location[1] - float(self.rel_point1[1])
  5566. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5567. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5568. self.inform.emit('[success] %s' % _("Done."))
  5569. return location
  5570. def on_copy_command(self):
  5571. """
  5572. Will copy a selection of objects, creating new objects.
  5573. :return:
  5574. """
  5575. self.report_usage("on_copy_command()")
  5576. def initialize(obj_init, app):
  5577. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5578. try:
  5579. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5580. except AttributeError:
  5581. pass
  5582. try:
  5583. obj_init.apertures = deepcopy(obj.apertures)
  5584. except AttributeError:
  5585. pass
  5586. try:
  5587. if obj.tools:
  5588. obj_init.tools = deepcopy(obj.tools)
  5589. except Exception as err:
  5590. log.debug("App.on_copy_command() --> %s" % str(err))
  5591. try:
  5592. obj_init.source_file = deepcopy(obj.source_file)
  5593. except (AttributeError, TypeError):
  5594. pass
  5595. def initialize_excellon(obj_init, app):
  5596. obj_init.source_file = deepcopy(obj.source_file)
  5597. obj_init.tools = deepcopy(obj.tools)
  5598. # drills are offset, so they need to be deep copied
  5599. obj_init.drills = deepcopy(obj.drills)
  5600. # slots are offset, so they need to be deep copied
  5601. obj_init.slots = deepcopy(obj.slots)
  5602. obj_init.create_geometry()
  5603. def initialize_script(obj_init, app_obj):
  5604. obj_init.source_file = deepcopy(obj.source_file)
  5605. def initialize_document(obj_init, app_obj):
  5606. obj_init.source_file = deepcopy(obj.source_file)
  5607. for obj in self.collection.get_selected():
  5608. obj_name = obj.options["name"]
  5609. try:
  5610. if isinstance(obj, ExcellonObject):
  5611. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5612. elif isinstance(obj, GerberObject):
  5613. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5614. elif isinstance(obj, GeometryObject):
  5615. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5616. elif isinstance(obj, ScriptObject):
  5617. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  5618. elif isinstance(obj, DocumentObject):
  5619. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  5620. except Exception as e:
  5621. return "Operation failed: %s" % str(e)
  5622. def on_copy_object2(self, custom_name):
  5623. def initialize_geometry(obj_init, app):
  5624. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5625. try:
  5626. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5627. except AttributeError:
  5628. pass
  5629. try:
  5630. obj_init.apertures = deepcopy(obj.apertures)
  5631. except AttributeError:
  5632. pass
  5633. try:
  5634. if obj.tools:
  5635. obj_init.tools = deepcopy(obj.tools)
  5636. except Exception as ee:
  5637. log.debug("on_copy_object2() --> %s" % str(ee))
  5638. def initialize_gerber(obj_init, app):
  5639. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5640. obj_init.apertures = deepcopy(obj.apertures)
  5641. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5642. def initialize_excellon(obj_init, app):
  5643. obj_init.tools = deepcopy(obj.tools)
  5644. # drills are offset, so they need to be deep copied
  5645. obj_init.drills = deepcopy(obj.drills)
  5646. # slots are offset, so they need to be deep copied
  5647. obj_init.slots = deepcopy(obj.slots)
  5648. obj_init.create_geometry()
  5649. for obj in self.collection.get_selected():
  5650. obj_name = obj.options["name"]
  5651. try:
  5652. if isinstance(obj, ExcellonObject):
  5653. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5654. elif isinstance(obj, GerberObject):
  5655. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5656. elif isinstance(obj, GeometryObject):
  5657. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5658. except Exception as er:
  5659. return "Operation failed: %s" % str(er)
  5660. def on_rename_object(self, text):
  5661. """
  5662. Will rename an object.
  5663. :param text: New name for the object.
  5664. :return:
  5665. """
  5666. self.report_usage("on_rename_object()")
  5667. named_obj = self.collection.get_active()
  5668. for obj in named_obj:
  5669. if obj is list:
  5670. self.on_rename_object(text)
  5671. else:
  5672. try:
  5673. obj.options['name'] = text
  5674. except Exception as e:
  5675. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5676. def convert_any2geo(self):
  5677. """
  5678. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  5679. :return:
  5680. """
  5681. self.report_usage("convert_any2geo()")
  5682. def initialize(obj_init, app):
  5683. obj_init.solid_geometry = obj.solid_geometry
  5684. try:
  5685. obj_init.follow_geometry = obj.follow_geometry
  5686. except AttributeError:
  5687. pass
  5688. try:
  5689. obj_init.apertures = obj.apertures
  5690. except AttributeError:
  5691. pass
  5692. try:
  5693. if obj.tools:
  5694. obj_init.tools = obj.tools
  5695. except AttributeError:
  5696. pass
  5697. def initialize_excellon(obj_init, app):
  5698. # objs = self.collection.get_selected()
  5699. # GeometryObject.merge(objs, obj)
  5700. solid_geo = []
  5701. for tool in obj.tools:
  5702. for geo in obj.tools[tool]['solid_geometry']:
  5703. solid_geo.append(geo)
  5704. obj_init.solid_geometry = deepcopy(solid_geo)
  5705. if not self.collection.get_selected():
  5706. log.warning("App.convert_any2geo --> No object selected")
  5707. self.inform.emit('[WARNING_NOTCL] %s' %
  5708. _("No object is selected. Select an object and try again."))
  5709. return
  5710. for obj in self.collection.get_selected():
  5711. obj_name = obj.options["name"]
  5712. try:
  5713. if isinstance(obj, ExcellonObject):
  5714. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5715. else:
  5716. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5717. except Exception as e:
  5718. return "Operation failed: %s" % str(e)
  5719. def convert_any2gerber(self):
  5720. """
  5721. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  5722. :return:
  5723. """
  5724. self.report_usage("convert_any2gerber()")
  5725. def initialize_geometry(obj_init, app):
  5726. apertures = {}
  5727. apid = 0
  5728. apertures[str(apid)] = {}
  5729. apertures[str(apid)]['geometry'] = []
  5730. for obj_orig in obj.solid_geometry:
  5731. new_elem = {}
  5732. new_elem['solid'] = obj_orig
  5733. try:
  5734. new_elem['follow'] = obj_orig.exterior
  5735. except AttributeError:
  5736. pass
  5737. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5738. apertures[str(apid)]['size'] = 0.0
  5739. apertures[str(apid)]['type'] = 'C'
  5740. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5741. obj_init.apertures = deepcopy(apertures)
  5742. def initialize_excellon(obj_init, app):
  5743. apertures = {}
  5744. apid = 10
  5745. for tool in obj.tools:
  5746. apertures[str(apid)] = {}
  5747. apertures[str(apid)]['geometry'] = []
  5748. for geo in obj.tools[tool]['solid_geometry']:
  5749. new_el = {}
  5750. new_el['solid'] = geo
  5751. new_el['follow'] = geo.exterior
  5752. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5753. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5754. apertures[str(apid)]['type'] = 'C'
  5755. apid += 1
  5756. # create solid_geometry
  5757. solid_geometry = []
  5758. for apid in apertures:
  5759. for geo_el in apertures[apid]['geometry']:
  5760. solid_geometry.append(geo_el['solid'])
  5761. solid_geometry = MultiPolygon(solid_geometry)
  5762. solid_geometry = solid_geometry.buffer(0.0000001)
  5763. obj_init.solid_geometry = deepcopy(solid_geometry)
  5764. obj_init.apertures = deepcopy(apertures)
  5765. # clear the working objects (perhaps not necessary due of Python GC)
  5766. apertures.clear()
  5767. if not self.collection.get_selected():
  5768. log.warning("App.convert_any2gerber --> No object selected")
  5769. self.inform.emit('[WARNING_NOTCL] %s' %
  5770. _("No object is selected. Select an object and try again."))
  5771. return
  5772. for obj in self.collection.get_selected():
  5773. obj_name = obj.options["name"]
  5774. try:
  5775. if isinstance(obj, ExcellonObject):
  5776. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5777. elif isinstance(obj, GeometryObject):
  5778. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5779. else:
  5780. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5781. except Exception as e:
  5782. return "Operation failed: %s" % str(e)
  5783. def abort_all_tasks(self):
  5784. """
  5785. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  5786. on the first possible occasion.
  5787. :return:
  5788. """
  5789. if self.abort_flag is False:
  5790. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5791. self.abort_flag = True
  5792. self.cleanup.emit()
  5793. def app_is_idle(self):
  5794. if self.abort_flag:
  5795. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  5796. self.abort_flag = False
  5797. def on_selectall(self):
  5798. """
  5799. Will draw a selection box shape around the selected objects.
  5800. :return:
  5801. """
  5802. self.report_usage("on_selectall()")
  5803. # delete the possible selection box around a possible selected object
  5804. self.delete_selection_shape()
  5805. for name in self.collection.get_names():
  5806. self.collection.set_active(name)
  5807. curr_sel_obj = self.collection.get_by_name(name)
  5808. # create the selection box around the selected object
  5809. if self.defaults['global_selection_shape'] is True:
  5810. self.draw_selection_shape(curr_sel_obj)
  5811. def on_preferences(self):
  5812. """
  5813. Adds the Preferences in a Tab in Plot Area
  5814. :return:
  5815. """
  5816. # add the tab if it was closed
  5817. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5818. # delete the absolute and relative position and messages in the infobar
  5819. self.ui.position_label.setText("")
  5820. self.ui.rel_position_label.setText("")
  5821. # Switch plot_area to preferences page
  5822. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5823. # self.ui.show()
  5824. # detect changes in the preferences
  5825. for idx in range(self.ui.pref_tab_area.count()):
  5826. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5827. try:
  5828. try:
  5829. tb.textEdited.disconnect(self.on_preferences_edited)
  5830. except (TypeError, AttributeError):
  5831. pass
  5832. tb.textEdited.connect(self.on_preferences_edited)
  5833. except AttributeError:
  5834. pass
  5835. try:
  5836. try:
  5837. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5838. except (TypeError, AttributeError):
  5839. pass
  5840. tb.modificationChanged.connect(self.on_preferences_edited)
  5841. except AttributeError:
  5842. pass
  5843. try:
  5844. try:
  5845. tb.toggled.disconnect(self.on_preferences_edited)
  5846. except (TypeError, AttributeError):
  5847. pass
  5848. tb.toggled.connect(self.on_preferences_edited)
  5849. except AttributeError:
  5850. pass
  5851. try:
  5852. try:
  5853. tb.valueChanged.disconnect(self.on_preferences_edited)
  5854. except (TypeError, AttributeError):
  5855. pass
  5856. tb.valueChanged.connect(self.on_preferences_edited)
  5857. except AttributeError:
  5858. pass
  5859. try:
  5860. try:
  5861. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5862. except (TypeError, AttributeError):
  5863. pass
  5864. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5865. except AttributeError:
  5866. pass
  5867. def on_preferences_edited(self):
  5868. """
  5869. Executed when a preference was changed in the Edit -> Preferences tab.
  5870. Will color the Preferences tab text to Red color.
  5871. :return:
  5872. """
  5873. if self.preferences_changed_flag is False:
  5874. self.inform.emit('[WARNING_NOTCL] %s' % _("Preferences edited but not saved."))
  5875. for idx in range(self.ui.plot_tab_area.count()):
  5876. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5877. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  5878. self.ui.pref_apply_button.setStyleSheet("QPushButton {color: red;}")
  5879. self.preferences_changed_flag = True
  5880. def on_tools_database(self, source='app'):
  5881. """
  5882. Adds the Tools Database in a Tab in Plot Area.
  5883. :return:
  5884. """
  5885. for idx in range(self.ui.plot_tab_area.count()):
  5886. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  5887. # there can be only one instance of Tools Database at one time
  5888. return
  5889. if source == 'app':
  5890. self.tools_db_tab = ToolsDB2(
  5891. app=self,
  5892. parent=self.ui,
  5893. callback_on_edited=self.on_tools_db_edited,
  5894. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  5895. )
  5896. elif source == 'ncc':
  5897. self.tools_db_tab = ToolsDB2(
  5898. app=self,
  5899. parent=self.ui,
  5900. callback_on_edited=self.on_tools_db_edited,
  5901. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  5902. )
  5903. elif source == 'paint':
  5904. self.tools_db_tab = ToolsDB2(
  5905. app=self,
  5906. parent=self.ui,
  5907. callback_on_edited=self.on_tools_db_edited,
  5908. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  5909. )
  5910. # add the tab if it was closed
  5911. try:
  5912. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  5913. self.tools_db_tab.setObjectName("database_tab")
  5914. except Exception as e:
  5915. log.debug("App.on_tools_database() --> %s" % str(e))
  5916. return
  5917. # delete the absolute and relative position and messages in the infobar
  5918. self.ui.position_label.setText("")
  5919. self.ui.rel_position_label.setText("")
  5920. # Switch plot_area to preferences page
  5921. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  5922. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  5923. self.tools_db_tab.ui_connect()
  5924. def on_tools_db_edited(self):
  5925. """
  5926. Executed whenever a tool is edited in Tools Database.
  5927. Will color the text of the Tools Database tab to Red color.
  5928. :return:
  5929. """
  5930. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  5931. for idx in range(self.ui.plot_tab_area.count()):
  5932. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  5933. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  5934. self.tools_db_changed_flag = True
  5935. def on_geometry_tool_add_from_db_executed(self, tool):
  5936. """
  5937. Here add the tool from DB in the selected geometry object.
  5938. :return:
  5939. """
  5940. tool_from_db = deepcopy(tool)
  5941. obj = self.collection.get_active()
  5942. if isinstance(obj, GeometryObject):
  5943. obj.on_tool_from_db_inserted(tool=tool_from_db)
  5944. # close the tab and delete it
  5945. for idx in range(self.ui.plot_tab_area.count()):
  5946. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  5947. wdg = self.ui.plot_tab_area.widget(idx)
  5948. wdg.deleteLater()
  5949. self.ui.plot_tab_area.removeTab(idx)
  5950. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  5951. else:
  5952. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  5953. def on_plot_area_tab_closed(self, title):
  5954. """
  5955. Executed whenever a tab is closed in the Plot Area.
  5956. :param title: The name of the tab that was closed.
  5957. :return:
  5958. """
  5959. if title == _("Preferences"):
  5960. # disconnect
  5961. for idx in range(self.ui.pref_tab_area.count()):
  5962. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5963. try:
  5964. tb.textEdited.disconnect(self.on_preferences_edited)
  5965. except (TypeError, AttributeError):
  5966. pass
  5967. try:
  5968. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5969. except (TypeError, AttributeError):
  5970. pass
  5971. try:
  5972. tb.toggled.disconnect(self.on_preferences_edited)
  5973. except (TypeError, AttributeError):
  5974. pass
  5975. try:
  5976. tb.valueChanged.disconnect(self.on_preferences_edited)
  5977. except (TypeError, AttributeError):
  5978. pass
  5979. try:
  5980. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5981. except (TypeError, AttributeError):
  5982. pass
  5983. if self.preferences_changed_flag is True:
  5984. msgbox = QtWidgets.QMessageBox()
  5985. msgbox.setText(_("One or more values are changed.\n"
  5986. "Do you want to save the Preferences?"))
  5987. msgbox.setWindowTitle(_("Save Preferences"))
  5988. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5989. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5990. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5991. msgbox.setDefaultButton(bt_yes)
  5992. msgbox.exec_()
  5993. response = msgbox.clickedButton()
  5994. if response == bt_yes:
  5995. self.on_save_button(save_to_file=True)
  5996. self.inform.emit('[success] %s' % _("Preferences saved."))
  5997. else:
  5998. self.preferences_changed_flag = False
  5999. self.inform.emit('')
  6000. return
  6001. if title == _("Tools Database"):
  6002. # disconnect the signals from the table widget in tab
  6003. self.tools_db_tab.ui_disconnect()
  6004. if self.tools_db_changed_flag is True:
  6005. msgbox = QtWidgets.QMessageBox()
  6006. msgbox.setText(_("One or more Tools are edited.\n"
  6007. "Do you want to update the Tools Database?"))
  6008. msgbox.setWindowTitle(_("Save Tools Database"))
  6009. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6010. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6011. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6012. msgbox.setDefaultButton(bt_yes)
  6013. msgbox.exec_()
  6014. response = msgbox.clickedButton()
  6015. if response == bt_yes:
  6016. self.tools_db_tab.on_save_tools_db()
  6017. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6018. else:
  6019. self.tools_db_changed_flag = False
  6020. self.inform.emit('')
  6021. return
  6022. self.tools_db_tab.deleteLater()
  6023. if title == _("Code Editor"):
  6024. self.toggle_codeeditor = False
  6025. if title == _("Bookmarks Manager"):
  6026. self.book_dialog_tab.rebuild_actions()
  6027. self.book_dialog_tab.deleteLater()
  6028. def on_flipy(self):
  6029. """
  6030. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  6031. :return:
  6032. """
  6033. self.report_usage("on_flipy()")
  6034. obj_list = self.collection.get_selected()
  6035. xminlist = []
  6036. yminlist = []
  6037. xmaxlist = []
  6038. ymaxlist = []
  6039. if not obj_list:
  6040. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  6041. else:
  6042. try:
  6043. # first get a bounding box to fit all
  6044. for obj in obj_list:
  6045. xmin, ymin, xmax, ymax = obj.bounds()
  6046. xminlist.append(xmin)
  6047. yminlist.append(ymin)
  6048. xmaxlist.append(xmax)
  6049. ymaxlist.append(ymax)
  6050. # get the minimum x,y and maximum x,y for all objects selected
  6051. xminimal = min(xminlist)
  6052. yminimal = min(yminlist)
  6053. xmaximal = max(xmaxlist)
  6054. ymaximal = max(ymaxlist)
  6055. px = 0.5 * (xminimal + xmaximal)
  6056. py = 0.5 * (yminimal + ymaximal)
  6057. # execute mirroring
  6058. for obj in obj_list:
  6059. obj.mirror('X', [px, py])
  6060. obj.plot()
  6061. self.object_changed.emit(obj)
  6062. self.inform.emit('[success] %s' %
  6063. _("Flip on Y axis done."))
  6064. except Exception as e:
  6065. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6066. return
  6067. def on_flipx(self):
  6068. """
  6069. Executed when the menu entry in Options -> Flip on X axis is clicked.
  6070. :return:
  6071. """
  6072. self.report_usage("on_flipx()")
  6073. obj_list = self.collection.get_selected()
  6074. xminlist = []
  6075. yminlist = []
  6076. xmaxlist = []
  6077. ymaxlist = []
  6078. if not obj_list:
  6079. self.inform.emit('[WARNING_NOTCL] %s' %
  6080. _("No object selected to Flip on X axis."))
  6081. else:
  6082. try:
  6083. # first get a bounding box to fit all
  6084. for obj in obj_list:
  6085. xmin, ymin, xmax, ymax = obj.bounds()
  6086. xminlist.append(xmin)
  6087. yminlist.append(ymin)
  6088. xmaxlist.append(xmax)
  6089. ymaxlist.append(ymax)
  6090. # get the minimum x,y and maximum x,y for all objects selected
  6091. xminimal = min(xminlist)
  6092. yminimal = min(yminlist)
  6093. xmaximal = max(xmaxlist)
  6094. ymaximal = max(ymaxlist)
  6095. px = 0.5 * (xminimal + xmaximal)
  6096. py = 0.5 * (yminimal + ymaximal)
  6097. # execute mirroring
  6098. for obj in obj_list:
  6099. obj.mirror('Y', [px, py])
  6100. obj.plot()
  6101. self.object_changed.emit(obj)
  6102. self.inform.emit('[success] %s' %
  6103. _("Flip on X axis done."))
  6104. except Exception as e:
  6105. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6106. return
  6107. def on_rotate(self, silent=False, preset=None):
  6108. """
  6109. Executed when Options -> Rotate Selection menu entry is clicked.
  6110. :param silent: If silent is True then use the preset value for the angle of the rotation.
  6111. :param preset: A value to be used as predefined angle for rotation.
  6112. :return:
  6113. """
  6114. self.report_usage("on_rotate()")
  6115. obj_list = self.collection.get_selected()
  6116. xminlist = []
  6117. yminlist = []
  6118. xmaxlist = []
  6119. ymaxlist = []
  6120. if not obj_list:
  6121. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  6122. else:
  6123. if silent is False:
  6124. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6125. min=-360, max=360, decimals=4,
  6126. init_val=float(self.defaults['tools_transform_rotate']))
  6127. num, ok = rotatebox.get_value()
  6128. else:
  6129. num = preset
  6130. ok = True
  6131. if ok:
  6132. try:
  6133. # first get a bounding box to fit all
  6134. for obj in obj_list:
  6135. xmin, ymin, xmax, ymax = obj.bounds()
  6136. xminlist.append(xmin)
  6137. yminlist.append(ymin)
  6138. xmaxlist.append(xmax)
  6139. ymaxlist.append(ymax)
  6140. # get the minimum x,y and maximum x,y for all objects selected
  6141. xminimal = min(xminlist)
  6142. yminimal = min(yminlist)
  6143. xmaximal = max(xmaxlist)
  6144. ymaximal = max(ymaxlist)
  6145. px = 0.5 * (xminimal + xmaximal)
  6146. py = 0.5 * (yminimal + ymaximal)
  6147. for sel_obj in obj_list:
  6148. sel_obj.rotate(-float(num), point=(px, py))
  6149. sel_obj.plot()
  6150. self.object_changed.emit(sel_obj)
  6151. self.inform.emit('[success] %s' %
  6152. _("Rotation done."))
  6153. except Exception as e:
  6154. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6155. return
  6156. def on_skewx(self):
  6157. """
  6158. Executed when the menu entry in Options -> Skew on X axis is clicked.
  6159. :return:
  6160. """
  6161. self.report_usage("on_skewx()")
  6162. obj_list = self.collection.get_selected()
  6163. xminlist = []
  6164. yminlist = []
  6165. if not obj_list:
  6166. self.inform.emit('[WARNING_NOTCL] %s' %
  6167. _("No object selected to Skew/Shear on X axis."))
  6168. else:
  6169. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6170. min=-360, max=360, decimals=4,
  6171. init_val=float(self.defaults['tools_transform_skew_x']))
  6172. num, ok = skewxbox.get_value()
  6173. if ok:
  6174. # first get a bounding box to fit all
  6175. for obj in obj_list:
  6176. xmin, ymin, xmax, ymax = obj.bounds()
  6177. xminlist.append(xmin)
  6178. yminlist.append(ymin)
  6179. # get the minimum x,y and maximum x,y for all objects selected
  6180. xminimal = min(xminlist)
  6181. yminimal = min(yminlist)
  6182. for obj in obj_list:
  6183. obj.skew(num, 0, point=(xminimal, yminimal))
  6184. obj.plot()
  6185. self.object_changed.emit(obj)
  6186. self.inform.emit('[success] %s' %
  6187. _("Skew on X axis done."))
  6188. def on_skewy(self):
  6189. """
  6190. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  6191. :return:
  6192. """
  6193. self.report_usage("on_skewy()")
  6194. obj_list = self.collection.get_selected()
  6195. xminlist = []
  6196. yminlist = []
  6197. if not obj_list:
  6198. self.inform.emit('[WARNING_NOTCL] %s' %
  6199. _("No object selected to Skew/Shear on Y axis."))
  6200. else:
  6201. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6202. min=-360, max=360, decimals=4,
  6203. init_val=float(self.defaults['tools_transform_skew_y']))
  6204. num, ok = skewybox.get_value()
  6205. if ok:
  6206. # first get a bounding box to fit all
  6207. for obj in obj_list:
  6208. xmin, ymin, xmax, ymax = obj.bounds()
  6209. xminlist.append(xmin)
  6210. yminlist.append(ymin)
  6211. # get the minimum x,y and maximum x,y for all objects selected
  6212. xminimal = min(xminlist)
  6213. yminimal = min(yminlist)
  6214. for obj in obj_list:
  6215. obj.skew(0, num, point=(xminimal, yminimal))
  6216. obj.plot()
  6217. self.object_changed.emit(obj)
  6218. self.inform.emit('[success] %s' %
  6219. _("Skew on Y axis done."))
  6220. def on_plots_updated(self):
  6221. """
  6222. Callback used to report when the plots have changed.
  6223. Adjust axes and zooms to fit.
  6224. :return: None
  6225. """
  6226. if self.is_legacy is False:
  6227. self.plotcanvas.update()
  6228. else:
  6229. self.plotcanvas.auto_adjust_axes()
  6230. self.on_zoom_fit(None)
  6231. self.collection.update_view()
  6232. # self.inform.emit(_("Plots updated ..."))
  6233. def on_toolbar_replot(self):
  6234. """
  6235. Callback for toolbar button. Re-plots all objects.
  6236. :return: None
  6237. """
  6238. self.report_usage("on_toolbar_replot")
  6239. self.log.debug("on_toolbar_replot()")
  6240. try:
  6241. self.collection.get_active().read_form()
  6242. except AttributeError:
  6243. self.log.debug("on_toolbar_replot(): AttributeError")
  6244. pass
  6245. self.plot_all()
  6246. def on_row_activated(self, index):
  6247. if index.isValid():
  6248. if index.internalPointer().parent_item != self.collection.root_item:
  6249. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6250. self.collection.on_item_activated(index)
  6251. def on_row_selected(self, obj_name):
  6252. """
  6253. This is a special string; when received it will make all Menu -> Objects entries unchecked
  6254. It mean we clicked outside of the items and deselected all
  6255. :param obj_name:
  6256. :return:
  6257. """
  6258. if obj_name == 'none':
  6259. for act in self.ui.menuobjects.actions():
  6260. act.setChecked(False)
  6261. return
  6262. # get the name of the selected objects and add them to a list
  6263. name_list = []
  6264. for obj in self.collection.get_selected():
  6265. name_list.append(obj.options['name'])
  6266. # set all actions as unchecked but the ones selected make them checked
  6267. for act in self.ui.menuobjects.actions():
  6268. act.setChecked(False)
  6269. if act.text() in name_list:
  6270. act.setChecked(True)
  6271. def on_collection_updated(self, obj, state, old_name):
  6272. """
  6273. Create a menu from the object loaded in the collection.
  6274. :param obj: object that was changed (added, deleted, renamed)
  6275. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  6276. :param old_name: the old name of the object before the action that triggered this slot happened
  6277. :return: None
  6278. """
  6279. icon_files = {
  6280. "gerber": self.resource_location + "/flatcam_icon16.png",
  6281. "excellon": self.resource_location + "/drill16.png",
  6282. "cncjob": self.resource_location + "/cnc16.png",
  6283. "geometry": self.resource_location + "/geometry16.png",
  6284. "script": self.resource_location + "/script_new16.png",
  6285. "document": self.resource_location + "/notes16_1.png"
  6286. }
  6287. if state == 'append':
  6288. for act in self.ui.menuobjects.actions():
  6289. try:
  6290. act.triggered.disconnect()
  6291. except TypeError:
  6292. pass
  6293. self.ui.menuobjects.clear()
  6294. gerber_list = []
  6295. exc_list = []
  6296. cncjob_list = []
  6297. geo_list = []
  6298. script_list = []
  6299. doc_list = []
  6300. for name in self.collection.get_names():
  6301. obj_named = self.collection.get_by_name(name)
  6302. if obj_named.kind == 'gerber':
  6303. gerber_list.append(name)
  6304. elif obj_named.kind == 'excellon':
  6305. exc_list.append(name)
  6306. elif obj_named.kind == 'cncjob':
  6307. cncjob_list.append(name)
  6308. elif obj_named.kind == 'geometry':
  6309. geo_list.append(name)
  6310. elif obj_named.kind == 'script':
  6311. script_list.append(name)
  6312. elif obj_named.kind == 'document':
  6313. doc_list.append(name)
  6314. def add_act(o_name):
  6315. obj_for_icon = self.collection.get_by_name(o_name)
  6316. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6317. add_action.setCheckable(True)
  6318. add_action.setText(o_name)
  6319. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6320. add_action.triggered.connect(
  6321. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  6322. self.collection.set_inactive(o_name))
  6323. self.ui.menuobjects.addAction(add_action)
  6324. for name in gerber_list:
  6325. add_act(name)
  6326. self.ui.menuobjects.addSeparator()
  6327. for name in exc_list:
  6328. add_act(name)
  6329. self.ui.menuobjects.addSeparator()
  6330. for name in cncjob_list:
  6331. add_act(name)
  6332. self.ui.menuobjects.addSeparator()
  6333. for name in geo_list:
  6334. add_act(name)
  6335. self.ui.menuobjects.addSeparator()
  6336. for name in script_list:
  6337. add_act(name)
  6338. self.ui.menuobjects.addSeparator()
  6339. for name in doc_list:
  6340. add_act(name)
  6341. self.ui.menuobjects.addSeparator()
  6342. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6343. QtGui.QIcon(self.resource_location + '/select_all.png'),
  6344. _('Select All')
  6345. )
  6346. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6347. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  6348. _('Deselect All')
  6349. )
  6350. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6351. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6352. elif state == 'delete':
  6353. for act in self.ui.menuobjects.actions():
  6354. if act.text() == obj.options['name']:
  6355. try:
  6356. act.triggered.disconnect()
  6357. except TypeError:
  6358. pass
  6359. self.ui.menuobjects.removeAction(act)
  6360. break
  6361. elif state == 'rename':
  6362. for act in self.ui.menuobjects.actions():
  6363. if act.text() == old_name:
  6364. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6365. add_action.setText(obj.options['name'])
  6366. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6367. add_action.triggered.connect(
  6368. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  6369. self.collection.set_inactive(obj.options['name']))
  6370. self.ui.menuobjects.insertAction(act, add_action)
  6371. try:
  6372. act.triggered.disconnect()
  6373. except TypeError:
  6374. pass
  6375. self.ui.menuobjects.removeAction(act)
  6376. break
  6377. elif state == 'delete_all':
  6378. for act in self.ui.menuobjects.actions():
  6379. try:
  6380. act.triggered.disconnect()
  6381. except TypeError:
  6382. pass
  6383. self.ui.menuobjects.clear()
  6384. self.ui.menuobjects.addSeparator()
  6385. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6386. QtGui.QIcon(self.resource_location + '/select_all.png'),
  6387. _('Select All')
  6388. )
  6389. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6390. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  6391. _('Deselect All')
  6392. )
  6393. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6394. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6395. def on_objects_selection(self, on_off):
  6396. obj_list = self.collection.get_names()
  6397. if on_off is True:
  6398. self.collection.set_all_active()
  6399. for act in self.ui.menuobjects.actions():
  6400. try:
  6401. act.setChecked(True)
  6402. except Exception:
  6403. pass
  6404. if obj_list:
  6405. self.inform.emit('[selected] %s' % _("All objects are selected."))
  6406. else:
  6407. self.collection.set_all_inactive()
  6408. for act in self.ui.menuobjects.actions():
  6409. try:
  6410. act.setChecked(False)
  6411. except Exception:
  6412. pass
  6413. if obj_list:
  6414. self.inform.emit('%s' % _("Objects selection is cleared."))
  6415. else:
  6416. self.inform.emit('')
  6417. def grid_status(self):
  6418. if self.ui.grid_snap_btn.isChecked():
  6419. return True
  6420. else:
  6421. return False
  6422. def populate_cmenu_grids(self):
  6423. units = self.defaults['units'].lower()
  6424. # for act in self.ui.cmenu_gridmenu.actions():
  6425. # act.triggered.disconnect()
  6426. self.ui.cmenu_gridmenu.clear()
  6427. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6428. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  6429. _("Grid On/Off"))
  6430. grid_toggle.setCheckable(True)
  6431. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  6432. self.ui.cmenu_gridmenu.addSeparator()
  6433. for grid in sorted_list:
  6434. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  6435. "%s" % str(grid))
  6436. action.triggered.connect(self.set_grid)
  6437. self.ui.cmenu_gridmenu.addSeparator()
  6438. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  6439. _("Add"))
  6440. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  6441. _("Delete"))
  6442. grid_add.triggered.connect(self.on_grid_add)
  6443. grid_delete.triggered.connect(self.on_grid_delete)
  6444. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6445. def set_grid(self):
  6446. menu_action = self.sender()
  6447. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  6448. self.ui.grid_gap_x_entry.setText(menu_action.text())
  6449. self.ui.grid_gap_y_entry.setText(menu_action.text())
  6450. def on_grid_add(self):
  6451. # ## Current application units in lower Case
  6452. units = self.defaults['units'].lower()
  6453. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6454. text=_('Enter a Grid Value:'),
  6455. min=0.0000, max=99.9999, decimals=4)
  6456. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  6457. val, ok = grid_add_popup.get_value()
  6458. if ok:
  6459. if float(val) == 0:
  6460. self.inform.emit('[WARNING_NOTCL] %s' %
  6461. _("Please enter a grid value with non-zero value, in Float format."))
  6462. return
  6463. else:
  6464. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6465. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6466. self.inform.emit('[success] %s...' %
  6467. _("New Grid added"))
  6468. else:
  6469. self.inform.emit('[WARNING_NOTCL] %s...' %
  6470. _("Grid already exists"))
  6471. else:
  6472. self.inform.emit('[WARNING_NOTCL] %s...' %
  6473. _("Adding New Grid cancelled"))
  6474. def on_grid_delete(self):
  6475. # ## Current application units in lower Case
  6476. units = self.defaults['units'].lower()
  6477. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6478. text='Enter a Grid Value:',
  6479. min=0.0000, max=99.9999, decimals=4)
  6480. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  6481. val, ok = grid_del_popup.get_value()
  6482. if ok:
  6483. if float(val) == 0:
  6484. self.inform.emit('[WARNING_NOTCL] %s' %
  6485. _("Please enter a grid value with non-zero value, in Float format."))
  6486. return
  6487. else:
  6488. try:
  6489. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6490. except ValueError:
  6491. self.inform.emit('[ERROR_NOTCL]%s...' %
  6492. _(" Grid Value does not exist"))
  6493. return
  6494. self.inform.emit('[success] %s...' %
  6495. _("Grid Value deleted"))
  6496. else:
  6497. self.inform.emit('[WARNING_NOTCL] %s...' %
  6498. _("Delete Grid value cancelled"))
  6499. def on_shortcut_list(self):
  6500. self.report_usage("on_shortcut_list()")
  6501. # add the tab if it was closed
  6502. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6503. # delete the absolute and relative position and messages in the infobar
  6504. self.ui.position_label.setText("")
  6505. self.ui.rel_position_label.setText("")
  6506. # Switch plot_area to preferences page
  6507. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6508. # self.ui.show()
  6509. def on_select_tab(self, name):
  6510. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6511. if self.ui.splitter.sizes()[0] == 0:
  6512. self.ui.splitter.setSizes([1, 1])
  6513. else:
  6514. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6515. self.ui.splitter.setSizes([0, 1])
  6516. if name == 'project':
  6517. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6518. elif name == 'selected':
  6519. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6520. elif name == 'tool':
  6521. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6522. def on_copy_name(self):
  6523. self.report_usage("on_copy_name()")
  6524. obj = self.collection.get_active()
  6525. try:
  6526. name = obj.options["name"]
  6527. except AttributeError:
  6528. log.debug("on_copy_name() --> No object selected to copy it's name")
  6529. self.inform.emit('[WARNING_NOTCL]%s' %
  6530. _(" No object selected to copy it's name"))
  6531. return
  6532. self.clipboard.setText(name)
  6533. self.inform.emit(_("Name copied on clipboard ..."))
  6534. def on_mouse_click_over_plot(self, event):
  6535. """
  6536. Default actions are:
  6537. :param event: Contains information about the event, like which button
  6538. was clicked, the pixel coordinates and the axes coordinates.
  6539. :return: None
  6540. """
  6541. self.pos = []
  6542. if self.is_legacy is False:
  6543. event_pos = event.pos
  6544. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  6545. # # Set the mouse button for panning
  6546. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  6547. else:
  6548. event_pos = (event.xdata, event.ydata)
  6549. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6550. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  6551. # So it can receive key presses
  6552. self.plotcanvas.native.setFocus()
  6553. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6554. if self.grid_status():
  6555. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6556. else:
  6557. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6558. try:
  6559. if event.button == 1:
  6560. # Reset here the relative coordinates so there is a new reference on the click position
  6561. if self.rel_point1 is None:
  6562. self.rel_point1 = self.pos
  6563. else:
  6564. self.rel_point2 = copy(self.rel_point1)
  6565. self.rel_point1 = self.pos
  6566. self.on_mouse_move_over_plot(event, origin_click=True)
  6567. except Exception as e:
  6568. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6569. def on_mouse_double_click_over_plot(self, event):
  6570. if event.button == 1:
  6571. self.doubleclick = True
  6572. def on_mouse_move_over_plot(self, event, origin_click=None):
  6573. """
  6574. Callback for the mouse motion event over the plot.
  6575. :param event: Contains information about the event.
  6576. :param origin_click
  6577. :return: None
  6578. """
  6579. if self.is_legacy is False:
  6580. event_pos = event.pos
  6581. if self.defaults["global_pan_button"] == '2':
  6582. pan_button = 2
  6583. else:
  6584. pan_button = 3
  6585. self.event_is_dragging = event.is_dragging
  6586. else:
  6587. event_pos = (event.xdata, event.ydata)
  6588. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6589. if self.defaults["global_pan_button"] == '2':
  6590. pan_button = 3
  6591. else:
  6592. pan_button = 2
  6593. self.event_is_dragging = self.plotcanvas.is_dragging
  6594. # So it can receive key presses but not when the Tcl Shell is active
  6595. if not self.ui.shell_dock.isVisible():
  6596. if not self.plotcanvas.native.hasFocus():
  6597. self.plotcanvas.native.setFocus()
  6598. self.pos_jump = event_pos
  6599. self.ui.popMenu.mouse_is_panning = False
  6600. if origin_click is None:
  6601. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6602. if event.button == pan_button and self.event_is_dragging == 1:
  6603. # if a popup menu is active don't change mouse_is_panning variable because is not True
  6604. if self.ui.popMenu.popup_active:
  6605. self.ui.popMenu.popup_active = False
  6606. return
  6607. self.ui.popMenu.mouse_is_panning = True
  6608. return
  6609. if self.rel_point1 is not None:
  6610. try: # May fail in case mouse not within axes
  6611. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6612. if self.grid_status():
  6613. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6614. # Update cursor
  6615. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6616. symbol='++', edge_color=self.cursor_color_3D,
  6617. edge_width=self.defaults["global_cursor_width"],
  6618. size=self.defaults["global_cursor_size"])
  6619. else:
  6620. pos = (pos_canvas[0], pos_canvas[1])
  6621. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6622. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6623. self.dx = pos[0] - float(self.rel_point1[0])
  6624. self.dy = pos[1] - float(self.rel_point1[1])
  6625. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6626. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  6627. self.mouse = [pos[0], pos[1]]
  6628. # if the mouse is moved and the LMB is clicked then the action is a selection
  6629. if self.event_is_dragging == 1 and event.button == 1:
  6630. self.delete_selection_shape()
  6631. if self.dx < 0:
  6632. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6633. face_color=self.defaults['global_alt_sel_fill'])
  6634. self.selection_type = False
  6635. elif self.dx >= 0:
  6636. self.draw_moving_selection_shape(self.pos, pos)
  6637. self.selection_type = True
  6638. else:
  6639. self.selection_type = None
  6640. else:
  6641. self.selection_type = None
  6642. # hover effect - enabled in Preferences -> General -> GUI Settings
  6643. if self.defaults['global_hover']:
  6644. for obj in self.collection.get_list():
  6645. try:
  6646. # select the object(s) only if it is enabled (plotted)
  6647. if obj.options['plot']:
  6648. if obj not in self.collection.get_selected():
  6649. poly_obj = Polygon(
  6650. [(obj.options['xmin'], obj.options['ymin']),
  6651. (obj.options['xmax'], obj.options['ymin']),
  6652. (obj.options['xmax'], obj.options['ymax']),
  6653. (obj.options['xmin'], obj.options['ymax'])]
  6654. )
  6655. if Point(pos).within(poly_obj):
  6656. if obj.isHovering is False:
  6657. obj.isHovering = True
  6658. obj.notHovering = True
  6659. # create the selection box around the selected object
  6660. self.draw_hover_shape(obj, color='#d1e0e0FF')
  6661. else:
  6662. if obj.notHovering is True:
  6663. obj.notHovering = False
  6664. obj.isHovering = False
  6665. self.delete_hover_shape()
  6666. except Exception:
  6667. # the Exception here will happen if we try to select on screen and we have an
  6668. # newly (and empty) just created Geometry or Excellon object that do not have the
  6669. # xmin, xmax, ymin, ymax options.
  6670. # In this case poly_obj creation (see above) will fail
  6671. pass
  6672. except Exception:
  6673. self.ui.position_label.setText("")
  6674. self.ui.rel_position_label.setText("")
  6675. self.mouse = None
  6676. def on_mouse_click_release_over_plot(self, event):
  6677. """
  6678. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6679. and has been registered in ''self.__init__()''.
  6680. :param event: contains information about the event.
  6681. :return:
  6682. """
  6683. if self.is_legacy is False:
  6684. event_pos = event.pos
  6685. right_button = 2
  6686. else:
  6687. event_pos = (event.xdata, event.ydata)
  6688. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6689. right_button = 3
  6690. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6691. if self.grid_status():
  6692. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6693. else:
  6694. pos = (pos_canvas[0], pos_canvas[1])
  6695. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6696. # canvas menu
  6697. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  6698. self.ui.popMenu.mouse_is_panning = False
  6699. self.cursor = QtGui.QCursor()
  6700. self.populate_cmenu_grids()
  6701. self.ui.popMenu.popup(self.cursor.pos())
  6702. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6703. # selection and then select a type of selection ("enclosing" or "touching")
  6704. if event.button == 1: # left click
  6705. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6706. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6707. if modifiers == QtCore.Qt.ShiftModifier:
  6708. # do not auto open the Project Tab
  6709. self.click_noproject = True
  6710. self.clipboard.setText(
  6711. self.defaults["global_point_clipboard_format"] %
  6712. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  6713. )
  6714. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  6715. return
  6716. if self.doubleclick is True:
  6717. self.doubleclick = False
  6718. if self.collection.get_selected():
  6719. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6720. if self.ui.splitter.sizes()[0] == 0:
  6721. self.ui.splitter.setSizes([1, 1])
  6722. try:
  6723. # delete the selection shape(S) as it may be in the way
  6724. self.delete_selection_shape()
  6725. self.delete_hover_shape()
  6726. except Exception as e:
  6727. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  6728. return
  6729. else:
  6730. # WORKAROUND for LEGACY MODE
  6731. if self.is_legacy is True:
  6732. # if there is no move on canvas then we have no dragging selection
  6733. if self.dx == 0 or self.dy == 0:
  6734. self.selection_type = None
  6735. if self.selection_type is not None:
  6736. try:
  6737. self.selection_area_handler(self.pos, pos, self.selection_type)
  6738. self.selection_type = None
  6739. except Exception as e:
  6740. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  6741. return
  6742. else:
  6743. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6744. if key_modifier == QtCore.Qt.ShiftModifier:
  6745. mod_key = 'Shift'
  6746. elif key_modifier == QtCore.Qt.ControlModifier:
  6747. mod_key = 'Control'
  6748. else:
  6749. mod_key = None
  6750. try:
  6751. if mod_key == self.defaults["global_mselect_key"]:
  6752. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6753. # deselect, and if it's not selected then it will be selected
  6754. # If there is no active command (self.command_active is None) then we check if we clicked
  6755. # on a object by checking the bounding limits against mouse click position
  6756. if self.command_active is None:
  6757. self.select_objects(key='multisel')
  6758. self.delete_hover_shape()
  6759. else:
  6760. # If there is no active command (self.command_active is None) then we check if we clicked
  6761. # on a object by checking the bounding limits against mouse click position
  6762. if self.command_active is None:
  6763. self.select_objects()
  6764. self.delete_hover_shape()
  6765. except Exception as e:
  6766. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  6767. return
  6768. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6769. """
  6770. :param start_pos: mouse position when the selection LMB click was done
  6771. :param end_pos: mouse position when the left mouse button is released
  6772. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6773. :return:
  6774. """
  6775. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6776. # delete previous selection shape
  6777. self.delete_selection_shape()
  6778. # make all objects inactive
  6779. self.collection.set_all_inactive()
  6780. for obj in self.collection.get_list():
  6781. try:
  6782. # select the object(s) only if it is enabled (plotted)
  6783. if obj.options['plot']:
  6784. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6785. (obj.options['xmax'], obj.options['ymin']),
  6786. (obj.options['xmax'], obj.options['ymax']),
  6787. (obj.options['xmin'], obj.options['ymax'])])
  6788. if sel_type is True:
  6789. if poly_obj.within(poly_selection):
  6790. # create the selection box around the selected object
  6791. if self.defaults['global_selection_shape'] is True:
  6792. self.draw_selection_shape(obj)
  6793. self.collection.set_active(obj.options['name'])
  6794. else:
  6795. if poly_selection.intersects(poly_obj):
  6796. # create the selection box around the selected object
  6797. if self.defaults['global_selection_shape'] is True:
  6798. self.draw_selection_shape(obj)
  6799. self.collection.set_active(obj.options['name'])
  6800. obj.selection_shape_drawn = True
  6801. except Exception as e:
  6802. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6803. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6804. # In this case poly_obj creation (see above) will fail
  6805. log.debug("App.selection_area_handler() --> %s" % str(e))
  6806. def select_objects(self, key=None):
  6807. """
  6808. Will select objects clicked on canvas
  6809. :param key: for future use in cumulative selection
  6810. :return:
  6811. """
  6812. # list where we store the overlapped objects under our mouse left click position
  6813. if key is None:
  6814. self.objects_under_the_click_list = []
  6815. # Populate the list with the overlapped objects on the click position
  6816. curr_x, curr_y = self.pos
  6817. for obj in self.all_objects_list:
  6818. # ScriptObject and DocumentObject objects can't be selected
  6819. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  6820. continue
  6821. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  6822. continue
  6823. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6824. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6825. if obj.options['name'] not in self.objects_under_the_click_list:
  6826. if obj.options['plot']:
  6827. # add objects to the objects_under_the_click list only if the object is plotted
  6828. # (active and not disabled)
  6829. self.objects_under_the_click_list.append(obj.options['name'])
  6830. try:
  6831. if self.objects_under_the_click_list:
  6832. curr_sel_obj = self.collection.get_active()
  6833. # case when there is only an object under the click and we toggle it
  6834. if len(self.objects_under_the_click_list) == 1:
  6835. if curr_sel_obj is None:
  6836. self.collection.set_active(self.objects_under_the_click_list[0])
  6837. curr_sel_obj = self.collection.get_active()
  6838. # create the selection box around the selected object
  6839. if self.defaults['global_selection_shape'] is True:
  6840. self.draw_selection_shape(curr_sel_obj)
  6841. curr_sel_obj.selection_shape_drawn = True
  6842. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  6843. self.on_objects_selection(False)
  6844. self.delete_selection_shape()
  6845. curr_sel_obj.selection_shape_drawn = False
  6846. self.collection.set_active(self.objects_under_the_click_list[0])
  6847. curr_sel_obj = self.collection.get_active()
  6848. # create the selection box around the selected object
  6849. if self.defaults['global_selection_shape'] is True:
  6850. self.draw_selection_shape(curr_sel_obj)
  6851. curr_sel_obj.selection_shape_drawn = True
  6852. self.selected_message(curr_sel_obj=curr_sel_obj)
  6853. elif curr_sel_obj.selection_shape_drawn is False:
  6854. if self.defaults['global_selection_shape'] is True:
  6855. self.draw_selection_shape(curr_sel_obj)
  6856. curr_sel_obj.selection_shape_drawn = True
  6857. else:
  6858. self.on_objects_selection(False)
  6859. self.delete_selection_shape()
  6860. if self.call_source != 'app':
  6861. self.call_source = 'app'
  6862. self.selected_message(curr_sel_obj=curr_sel_obj)
  6863. else:
  6864. # If there is no selected object
  6865. # make active the first element of the overlapped objects list
  6866. if self.collection.get_active() is None:
  6867. self.collection.set_active(self.objects_under_the_click_list[0])
  6868. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  6869. name_sel_obj = self.collection.get_active().options['name']
  6870. # In case that there is a selected object but it is not in the overlapped object list
  6871. # make that object inactive and activate the first element in the overlapped object list
  6872. if name_sel_obj not in self.objects_under_the_click_list:
  6873. self.collection.set_inactive(name_sel_obj)
  6874. name_sel_obj = self.objects_under_the_click_list[0]
  6875. self.collection.set_active(name_sel_obj)
  6876. else:
  6877. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  6878. self.collection.set_all_inactive()
  6879. self.collection.set_active(
  6880. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  6881. curr_sel_obj = self.collection.get_active()
  6882. # delete the possible selection box around a possible selected object
  6883. self.delete_selection_shape()
  6884. curr_sel_obj.selection_shape_drawn = False
  6885. # create the selection box around the selected object
  6886. if self.defaults['global_selection_shape'] is True:
  6887. self.draw_selection_shape(curr_sel_obj)
  6888. curr_sel_obj.selection_shape_drawn = True
  6889. self.selected_message(curr_sel_obj=curr_sel_obj)
  6890. else:
  6891. # deselect everything
  6892. self.on_objects_selection(False)
  6893. # delete the possible selection box around a possible selected object
  6894. self.delete_selection_shape()
  6895. for o in self.collection.get_list():
  6896. o.selection_shape_drawn = False
  6897. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6898. # only when working on App
  6899. if self.call_source == 'app':
  6900. if self.click_noproject is False:
  6901. # if the Tool Tab is in focus don't change focus to Project Tab
  6902. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  6903. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6904. else:
  6905. # restore auto open the Project Tab
  6906. self.click_noproject = False
  6907. # delete any text in the status bar, implicitly the last object name that was selected
  6908. # self.inform.emit("")
  6909. else:
  6910. self.call_source = 'app'
  6911. except Exception as e:
  6912. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  6913. def selected_message(self, curr_sel_obj):
  6914. if curr_sel_obj:
  6915. if curr_sel_obj.kind == 'gerber':
  6916. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  6917. color='green',
  6918. name=str(curr_sel_obj.options['name']),
  6919. tx=_("selected"))
  6920. )
  6921. elif curr_sel_obj.kind == 'excellon':
  6922. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  6923. color='brown',
  6924. name=str(curr_sel_obj.options['name']),
  6925. tx=_("selected"))
  6926. )
  6927. elif curr_sel_obj.kind == 'cncjob':
  6928. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  6929. color='blue',
  6930. name=str(curr_sel_obj.options['name']),
  6931. tx=_("selected"))
  6932. )
  6933. elif curr_sel_obj.kind == 'geometry':
  6934. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  6935. color='red',
  6936. name=str(curr_sel_obj.options['name']),
  6937. tx=_("selected"))
  6938. )
  6939. def delete_hover_shape(self):
  6940. self.hover_shapes.clear()
  6941. self.hover_shapes.redraw()
  6942. def draw_hover_shape(self, sel_obj, color=None):
  6943. """
  6944. :param sel_obj: The object for which the hover shape must be drawn
  6945. :param color: The color of the hover shape
  6946. :return: None
  6947. """
  6948. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6949. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6950. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6951. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6952. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6953. if self.defaults['units'].upper() == 'MM':
  6954. hover_rect = hover_rect.buffer(-0.1)
  6955. hover_rect = hover_rect.buffer(0.2)
  6956. else:
  6957. hover_rect = hover_rect.buffer(-0.00393)
  6958. hover_rect = hover_rect.buffer(0.00787)
  6959. # if color:
  6960. # face = Color(color)
  6961. # face.alpha = 0.2
  6962. # outline = Color(color, alpha=0.8)
  6963. # else:
  6964. # face = Color(self.defaults['global_sel_fill'])
  6965. # face.alpha = 0.2
  6966. # outline = self.defaults['global_sel_line']
  6967. if color:
  6968. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6969. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6970. else:
  6971. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6972. outline = self.defaults['global_sel_line']
  6973. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6974. if self.is_legacy is True:
  6975. self.hover_shapes.redraw()
  6976. def delete_selection_shape(self):
  6977. self.move_tool.sel_shapes.clear()
  6978. self.move_tool.sel_shapes.redraw()
  6979. def draw_selection_shape(self, sel_obj, color=None):
  6980. """
  6981. Will draw a selection shape around the selected object.
  6982. :param sel_obj: The object for which the selection shape must be drawn
  6983. :param color: The color for the selection shape.
  6984. :return: None
  6985. """
  6986. if sel_obj is None:
  6987. return
  6988. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6989. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6990. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6991. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6992. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6993. if self.defaults['units'].upper() == 'MM':
  6994. sel_rect = sel_rect.buffer(-0.1)
  6995. sel_rect = sel_rect.buffer(0.2)
  6996. else:
  6997. sel_rect = sel_rect.buffer(-0.00393)
  6998. sel_rect = sel_rect.buffer(0.00787)
  6999. if color:
  7000. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7001. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7002. else:
  7003. if self.is_legacy is False:
  7004. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7005. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7006. else:
  7007. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7008. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7009. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7010. color=outline,
  7011. face_color=face,
  7012. update=True,
  7013. layer=0,
  7014. tolerance=None))
  7015. if self.is_legacy is True:
  7016. self.move_tool.sel_shapes.redraw()
  7017. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7018. """
  7019. Will draw a selection shape when dragging mouse on canvas.
  7020. :param old_coords: Old coordinates
  7021. :param coords: New coordinates
  7022. :param kwargs: Keyword arguments
  7023. :return:
  7024. """
  7025. if 'color' in kwargs:
  7026. color = kwargs['color']
  7027. else:
  7028. color = self.defaults['global_sel_line']
  7029. if 'face_color' in kwargs:
  7030. face_color = kwargs['face_color']
  7031. else:
  7032. face_color = self.defaults['global_sel_fill']
  7033. if 'face_alpha' in kwargs:
  7034. face_alpha = kwargs['face_alpha']
  7035. else:
  7036. face_alpha = 0.3
  7037. x0, y0 = old_coords
  7038. x1, y1 = coords
  7039. pt1 = (x0, y0)
  7040. pt2 = (x1, y0)
  7041. pt3 = (x1, y1)
  7042. pt4 = (x0, y1)
  7043. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7044. # color_t = Color(face_color)
  7045. # color_t.alpha = face_alpha
  7046. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7047. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7048. layer=0, tolerance=None)
  7049. if self.is_legacy is True:
  7050. self.move_tool.sel_shapes.redraw()
  7051. def on_file_new_click(self):
  7052. """
  7053. Callback for menu item File -> New.
  7054. Executed on clicking the Menu -> File -> New Project
  7055. :return:
  7056. """
  7057. if self.collection.get_list() and self.should_we_save:
  7058. msgbox = QtWidgets.QMessageBox()
  7059. # msgbox.setText("<B>Save changes ...</B>")
  7060. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7061. "Creating a New project will delete them.\n"
  7062. "Do you want to Save the project?"))
  7063. msgbox.setWindowTitle(_("Save changes"))
  7064. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  7065. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7066. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7067. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7068. msgbox.setDefaultButton(bt_yes)
  7069. msgbox.exec_()
  7070. response = msgbox.clickedButton()
  7071. if response == bt_yes:
  7072. self.on_file_saveprojectas()
  7073. elif response == bt_cancel:
  7074. return
  7075. elif response == bt_no:
  7076. self.on_file_new()
  7077. else:
  7078. self.on_file_new()
  7079. self.inform.emit('[success] %s...' % _("New Project created"))
  7080. def on_file_new(self, cli=None):
  7081. """
  7082. Returns the application to its startup state. This method is thread-safe.
  7083. :param cli: Boolean. If True this method was run from command line
  7084. :return: None
  7085. """
  7086. self.report_usage("on_file_new")
  7087. # Remove everything from memory
  7088. App.log.debug("on_file_new()")
  7089. if self.call_source != 'app':
  7090. self.editor2object(cleanup=True)
  7091. # ## EDITOR section
  7092. self.geo_editor = FlatCAMGeoEditor(self)
  7093. self.exc_editor = FlatCAMExcEditor(self)
  7094. self.grb_editor = FlatCAMGrbEditor(self)
  7095. # Clear pool
  7096. self.clear_pool()
  7097. for obj in self.collection.get_list():
  7098. # delete shapes left drawn from mark shape_collections, if any
  7099. if isinstance(obj, GerberObject):
  7100. try:
  7101. for el in obj.mark_shapes:
  7102. obj.mark_shapes[el].clear(update=True)
  7103. obj.mark_shapes[el].enabled = False
  7104. del el
  7105. except AttributeError:
  7106. pass
  7107. # also delete annotation shapes, if any
  7108. elif isinstance(obj, CNCJobObject):
  7109. try:
  7110. obj.text_col.enabled = False
  7111. del obj.text_col
  7112. obj.annotation.clear(update=True)
  7113. del obj.annotation
  7114. except AttributeError:
  7115. pass
  7116. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7117. self.init_tcl()
  7118. self.delete_selection_shape()
  7119. self.collection.delete_all()
  7120. self.setup_component_editor()
  7121. # Clear project filename
  7122. self.project_filename = None
  7123. # Load the application defaults
  7124. self.load_defaults(filename='current_defaults')
  7125. # Re-fresh project options
  7126. self.on_options_app2project()
  7127. # Init Tools
  7128. self.init_tools()
  7129. if cli is None:
  7130. # Close any Tabs opened in the Plot Tab Area section
  7131. for index in range(self.ui.plot_tab_area.count()):
  7132. self.ui.plot_tab_area.closeTab(index)
  7133. # for whatever reason previous command does not close the last tab so I do it manually
  7134. self.ui.plot_tab_area.closeTab(0)
  7135. # # And then add again the Plot Area
  7136. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7137. self.ui.plot_tab_area.protectTab(0)
  7138. # take the focus of the Notebook on Project Tab.
  7139. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7140. self.set_ui_title(name=_("New Project - Not saved"))
  7141. def obj_properties(self):
  7142. """
  7143. Will launch the object Properties Tool
  7144. :return:
  7145. """
  7146. self.report_usage("obj_properties()")
  7147. self.properties_tool.run(toggle=False)
  7148. def on_project_context_save(self):
  7149. """
  7150. Wrapper, will save the object function of it's type
  7151. :return:
  7152. """
  7153. obj = self.collection.get_active()
  7154. if type(obj) == GeometryObject:
  7155. self.on_file_exportdxf()
  7156. elif type(obj) == ExcellonObject:
  7157. self.on_file_saveexcellon()
  7158. elif type(obj) == CNCJobObject:
  7159. obj.on_exportgcode_button_click()
  7160. elif type(obj) == GerberObject:
  7161. self.on_file_savegerber()
  7162. elif type(obj) == ScriptObject:
  7163. self.on_file_savescript()
  7164. elif type(obj) == DocumentObject:
  7165. self.on_file_savedocument()
  7166. def obj_move(self):
  7167. """
  7168. Callback for the Move menu entry in various Context Menu's.
  7169. :return:
  7170. """
  7171. self.report_usage("obj_move()")
  7172. self.move_tool.run(toggle=False)
  7173. def on_fileopengerber(self, signal, name=None):
  7174. """
  7175. File menu callback for opening a Gerber.
  7176. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7177. :param name:
  7178. :return: None
  7179. """
  7180. self.report_usage("on_fileopengerber")
  7181. App.log.debug("on_fileopengerber()")
  7182. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7183. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7184. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  7185. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7186. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7187. "*.mil);;" \
  7188. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7189. "Allegro Files (*.art);;" \
  7190. "Mentor Files (*.pho *.gdo);;" \
  7191. "All Files (*.*)"
  7192. if name is None:
  7193. try:
  7194. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7195. directory=self.get_last_folder(),
  7196. filter=_filter_)
  7197. except TypeError:
  7198. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7199. filenames = [str(filename) for filename in filenames]
  7200. else:
  7201. filenames = [name]
  7202. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7203. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7204. _("Opening Gerber file.")),
  7205. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7206. color=QtGui.QColor("gray"))
  7207. if len(filenames) == 0:
  7208. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7209. else:
  7210. for filename in filenames:
  7211. if filename != '':
  7212. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7213. def on_fileopenexcellon(self, signal, name=None):
  7214. """
  7215. File menu callback for opening an Excellon file.
  7216. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7217. :param name:
  7218. :return: None
  7219. """
  7220. self.report_usage("on_fileopenexcellon")
  7221. App.log.debug("on_fileopenexcellon()")
  7222. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7223. "All Files (*.*)"
  7224. if name is None:
  7225. try:
  7226. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7227. directory=self.get_last_folder(),
  7228. filter=_filter_)
  7229. except TypeError:
  7230. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7231. filenames = [str(filename) for filename in filenames]
  7232. else:
  7233. filenames = [str(name)]
  7234. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7235. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7236. _("Opening Excellon file.")),
  7237. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7238. color=QtGui.QColor("gray"))
  7239. if len(filenames) == 0:
  7240. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  7241. else:
  7242. for filename in filenames:
  7243. if filename != '':
  7244. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7245. def on_fileopengcode(self, signal, name=None):
  7246. """
  7247. File menu call back for opening gcode.
  7248. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7249. :param name:
  7250. :return:
  7251. """
  7252. self.report_usage("on_fileopengcode")
  7253. App.log.debug("on_fileopengcode()")
  7254. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7255. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7256. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  7257. "All Files (*.*)"
  7258. if name is None:
  7259. try:
  7260. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7261. directory=self.get_last_folder(),
  7262. filter=_filter_)
  7263. except TypeError:
  7264. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7265. filenames = [str(filename) for filename in filenames]
  7266. else:
  7267. filenames = [name]
  7268. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7269. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7270. _("Opening G-Code file.")),
  7271. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7272. color=QtGui.QColor("gray"))
  7273. if len(filenames) == 0:
  7274. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7275. else:
  7276. for filename in filenames:
  7277. if filename != '':
  7278. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7279. def on_file_openproject(self, signal):
  7280. """
  7281. File menu callback for opening a project.
  7282. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7283. :return: None
  7284. """
  7285. self.report_usage("on_file_openproject")
  7286. App.log.debug("on_file_openproject()")
  7287. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7288. try:
  7289. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7290. directory=self.get_last_folder(), filter=_filter_)
  7291. except TypeError:
  7292. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7293. # The Qt methods above will return a QString which can cause problems later.
  7294. # So far json.dump() will fail to serialize it.
  7295. # TODO: Improve the serialization methods and remove this fix.
  7296. filename = str(filename)
  7297. if filename == "":
  7298. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7299. else:
  7300. # self.worker_task.emit({'fcn': self.open_project,
  7301. # 'params': [filename]})
  7302. # The above was failing because open_project() is not
  7303. # thread safe. The new_project()
  7304. self.open_project(filename)
  7305. def on_fileopenhpgl2(self, signal, name=None):
  7306. """
  7307. File menu callback for opening a HPGL2.
  7308. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7309. :param name:
  7310. :return: None
  7311. """
  7312. self.report_usage("on_fileopenhpgl2")
  7313. App.log.debug("on_fileopenhpgl2()")
  7314. _filter_ = "HPGL2 Files (*.plt);;" \
  7315. "All Files (*.*)"
  7316. if name is None:
  7317. try:
  7318. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  7319. directory=self.get_last_folder(),
  7320. filter=_filter_)
  7321. except TypeError:
  7322. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  7323. filenames = [str(filename) for filename in filenames]
  7324. else:
  7325. filenames = [name]
  7326. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7327. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7328. _("Opening HPGL2 file.")),
  7329. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7330. color=QtGui.QColor("gray"))
  7331. if len(filenames) == 0:
  7332. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7333. else:
  7334. for filename in filenames:
  7335. if filename != '':
  7336. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  7337. def on_file_openconfig(self, signal):
  7338. """
  7339. File menu callback for opening a config file.
  7340. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7341. :return: None
  7342. """
  7343. self.report_usage("on_file_openconfig")
  7344. App.log.debug("on_file_openconfig()")
  7345. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7346. try:
  7347. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7348. directory=self.data_path, filter=_filter_)
  7349. except TypeError:
  7350. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7351. filter=_filter_)
  7352. if filename == "":
  7353. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7354. else:
  7355. self.open_config_file(filename)
  7356. def on_file_exportsvg(self):
  7357. """
  7358. Callback for menu item File->Export SVG.
  7359. :return: None
  7360. """
  7361. self.report_usage("on_file_exportsvg")
  7362. App.log.debug("on_file_exportsvg()")
  7363. obj = self.collection.get_active()
  7364. if obj is None:
  7365. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7366. msg = _("Please Select a Geometry object to export")
  7367. msgbox = QtWidgets.QMessageBox()
  7368. msgbox.setInformativeText(msg)
  7369. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7370. msgbox.setDefaultButton(bt_ok)
  7371. msgbox.exec_()
  7372. return
  7373. # Check for more compatible types and add as required
  7374. if (not isinstance(obj, GeometryObject)
  7375. and not isinstance(obj, GerberObject)
  7376. and not isinstance(obj, CNCJobObject)
  7377. and not isinstance(obj, ExcellonObject)):
  7378. msg = '[ERROR_NOTCL] %s' % \
  7379. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7380. msgbox = QtWidgets.QMessageBox()
  7381. msgbox.setInformativeText(msg)
  7382. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7383. msgbox.setDefaultButton(bt_ok)
  7384. msgbox.exec_()
  7385. return
  7386. name = obj.options["name"]
  7387. _filter = "SVG File (*.svg);;All Files (*.*)"
  7388. try:
  7389. filename, _f = FCFileSaveDialog.get_saved_filename(
  7390. caption=_("Export SVG"),
  7391. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7392. filter=_filter)
  7393. except TypeError:
  7394. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  7395. filename = str(filename)
  7396. if filename == "":
  7397. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  7398. return
  7399. else:
  7400. self.export_svg(name, filename)
  7401. if self.defaults["global_open_style"] is False:
  7402. self.file_opened.emit("SVG", filename)
  7403. self.file_saved.emit("SVG", filename)
  7404. def on_file_exportpng(self):
  7405. self.report_usage("on_file_exportpng")
  7406. App.log.debug("on_file_exportpng()")
  7407. self.date = str(datetime.today()).rpartition('.')[0]
  7408. self.date = ''.join(c for c in self.date if c not in ':-')
  7409. self.date = self.date.replace(' ', '_')
  7410. if self.is_legacy is False:
  7411. image = _screenshot()
  7412. data = np.asarray(image)
  7413. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7414. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  7415. return
  7416. filter_ = "PNG File (*.png);;All Files (*.*)"
  7417. try:
  7418. filename, _f = FCFileSaveDialog.get_saved_filename(
  7419. caption=_("Export PNG Image"),
  7420. directory=self.get_last_save_folder() + '/png_' + self.date,
  7421. filter=filter_)
  7422. except TypeError:
  7423. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  7424. filename = str(filename)
  7425. if filename == "":
  7426. self.inform.emit(_("Cancelled."))
  7427. return
  7428. else:
  7429. if self.is_legacy is False:
  7430. write_png(filename, data)
  7431. else:
  7432. self.plotcanvas.figure.savefig(filename)
  7433. if self.defaults["global_open_style"] is False:
  7434. self.file_opened.emit("png", filename)
  7435. self.file_saved.emit("png", filename)
  7436. def on_file_savegerber(self):
  7437. """
  7438. Callback for menu item in Project context menu.
  7439. :return: None
  7440. """
  7441. self.report_usage("on_file_savegerber")
  7442. App.log.debug("on_file_savegerber()")
  7443. obj = self.collection.get_active()
  7444. if obj is None:
  7445. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7446. return
  7447. # Check for more compatible types and add as required
  7448. if not isinstance(obj, GerberObject):
  7449. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7450. return
  7451. name = self.collection.get_active().options["name"]
  7452. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7453. try:
  7454. filename, _f = FCFileSaveDialog.get_saved_filename(
  7455. caption="Save Gerber source file",
  7456. directory=self.get_last_save_folder() + '/' + name,
  7457. filter=_filter)
  7458. except TypeError:
  7459. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  7460. filename = str(filename)
  7461. if filename == "":
  7462. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7463. return
  7464. else:
  7465. self.save_source_file(name, filename)
  7466. if self.defaults["global_open_style"] is False:
  7467. self.file_opened.emit("Gerber", filename)
  7468. self.file_saved.emit("Gerber", filename)
  7469. def on_file_savescript(self):
  7470. """
  7471. Callback for menu item in Project context menu.
  7472. :return: None
  7473. """
  7474. self.report_usage("on_file_savescript")
  7475. App.log.debug("on_file_savescript()")
  7476. obj = self.collection.get_active()
  7477. if obj is None:
  7478. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7479. return
  7480. # Check for more compatible types and add as required
  7481. if not isinstance(obj, ScriptObject):
  7482. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  7483. return
  7484. name = self.collection.get_active().options["name"]
  7485. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7486. try:
  7487. filename, _f = FCFileSaveDialog.get_saved_filename(
  7488. caption="Save Script source file",
  7489. directory=self.get_last_save_folder() + '/' + name,
  7490. filter=_filter)
  7491. except TypeError:
  7492. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  7493. filename = str(filename)
  7494. if filename == "":
  7495. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7496. return
  7497. else:
  7498. self.save_source_file(name, filename)
  7499. if self.defaults["global_open_style"] is False:
  7500. self.file_opened.emit("Script", filename)
  7501. self.file_saved.emit("Script", filename)
  7502. def on_file_savedocument(self):
  7503. """
  7504. Callback for menu item in Project context menu.
  7505. :return: None
  7506. """
  7507. self.report_usage("on_file_savedocument")
  7508. App.log.debug("on_file_savedocument()")
  7509. obj = self.collection.get_active()
  7510. if obj is None:
  7511. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7512. return
  7513. # Check for more compatible types and add as required
  7514. if not isinstance(obj, ScriptObject):
  7515. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  7516. return
  7517. name = self.collection.get_active().options["name"]
  7518. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7519. try:
  7520. filename, _f = FCFileSaveDialog.get_saved_filename(
  7521. caption="Save Document source file",
  7522. directory=self.get_last_save_folder() + '/' + name,
  7523. filter=_filter)
  7524. except TypeError:
  7525. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  7526. filename = str(filename)
  7527. if filename == "":
  7528. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7529. return
  7530. else:
  7531. self.save_source_file(name, filename)
  7532. if self.defaults["global_open_style"] is False:
  7533. self.file_opened.emit("Document", filename)
  7534. self.file_saved.emit("Document", filename)
  7535. def on_file_saveexcellon(self):
  7536. """
  7537. Callback for menu item in project context menu.
  7538. :return: None
  7539. """
  7540. self.report_usage("on_file_saveexcellon")
  7541. App.log.debug("on_file_saveexcellon()")
  7542. obj = self.collection.get_active()
  7543. if obj is None:
  7544. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7545. return
  7546. # Check for more compatible types and add as required
  7547. if not isinstance(obj, ExcellonObject):
  7548. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7549. return
  7550. name = self.collection.get_active().options["name"]
  7551. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7552. try:
  7553. filename, _f = FCFileSaveDialog.get_saved_filename(
  7554. caption=_("Save Excellon source file"),
  7555. directory=self.get_last_save_folder() + '/' + name,
  7556. filter=_filter)
  7557. except TypeError:
  7558. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  7559. filename = str(filename)
  7560. if filename == "":
  7561. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7562. return
  7563. else:
  7564. self.save_source_file(name, filename)
  7565. if self.defaults["global_open_style"] is False:
  7566. self.file_opened.emit("Excellon", filename)
  7567. self.file_saved.emit("Excellon", filename)
  7568. def on_file_exportexcellon(self):
  7569. """
  7570. Callback for menu item File->Export->Excellon.
  7571. :return: None
  7572. """
  7573. self.report_usage("on_file_exportexcellon")
  7574. App.log.debug("on_file_exportexcellon()")
  7575. obj = self.collection.get_active()
  7576. if obj is None:
  7577. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7578. return
  7579. # Check for more compatible types and add as required
  7580. if not isinstance(obj, ExcellonObject):
  7581. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7582. return
  7583. name = self.collection.get_active().options["name"]
  7584. _filter = self.defaults["excellon_save_filters"]
  7585. try:
  7586. filename, _f = FCFileSaveDialog.get_saved_filename(
  7587. caption=_("Export Excellon"),
  7588. directory=self.get_last_save_folder() + '/' + name,
  7589. filter=_filter)
  7590. except TypeError:
  7591. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  7592. filename = str(filename)
  7593. if filename == "":
  7594. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7595. return
  7596. else:
  7597. used_extension = filename.rpartition('.')[2]
  7598. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7599. self.export_excellon(name, filename)
  7600. if self.defaults["global_open_style"] is False:
  7601. self.file_opened.emit("Excellon", filename)
  7602. self.file_saved.emit("Excellon", filename)
  7603. def on_file_exportgerber(self):
  7604. """
  7605. Callback for menu item File->Export->Gerber.
  7606. :return: None
  7607. """
  7608. self.report_usage("on_file_exportgerber")
  7609. App.log.debug("on_file_exportgerber()")
  7610. obj = self.collection.get_active()
  7611. if obj is None:
  7612. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7613. return
  7614. # Check for more compatible types and add as required
  7615. if not isinstance(obj, GerberObject):
  7616. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7617. return
  7618. name = self.collection.get_active().options["name"]
  7619. _filter_ = self.defaults['gerber_save_filters']
  7620. try:
  7621. filename, _f = FCFileSaveDialog.get_saved_filename(
  7622. caption=_("Export Gerber"),
  7623. directory=self.get_last_save_folder() + '/' + name,
  7624. filter=_filter_)
  7625. except TypeError:
  7626. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  7627. filename = str(filename)
  7628. if filename == "":
  7629. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7630. return
  7631. else:
  7632. used_extension = filename.rpartition('.')[2]
  7633. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  7634. self.export_gerber(name, filename)
  7635. if self.defaults["global_open_style"] is False:
  7636. self.file_opened.emit("Gerber", filename)
  7637. self.file_saved.emit("Gerber", filename)
  7638. def on_file_exportdxf(self):
  7639. """
  7640. Callback for menu item File->Export DXF.
  7641. :return: None
  7642. """
  7643. self.report_usage("on_file_exportdxf")
  7644. App.log.debug("on_file_exportdxf()")
  7645. obj = self.collection.get_active()
  7646. if obj is None:
  7647. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7648. msg = _("Please Select a Geometry object to export")
  7649. msgbox = QtWidgets.QMessageBox()
  7650. msgbox.setInformativeText(msg)
  7651. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7652. msgbox.setDefaultButton(bt_ok)
  7653. msgbox.exec_()
  7654. return
  7655. # Check for more compatible types and add as required
  7656. if not isinstance(obj, GeometryObject):
  7657. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  7658. msgbox = QtWidgets.QMessageBox()
  7659. msgbox.setInformativeText(msg)
  7660. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7661. msgbox.setDefaultButton(bt_ok)
  7662. msgbox.exec_()
  7663. return
  7664. name = self.collection.get_active().options["name"]
  7665. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7666. try:
  7667. filename, _f = FCFileSaveDialog.get_saved_filename(
  7668. caption=_("Export DXF"),
  7669. directory=self.get_last_save_folder() + '/' + name,
  7670. filter=_filter_)
  7671. except TypeError:
  7672. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  7673. filename = str(filename)
  7674. if filename == "":
  7675. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7676. return
  7677. else:
  7678. self.export_dxf(name, filename)
  7679. if self.defaults["global_open_style"] is False:
  7680. self.file_opened.emit("DXF", filename)
  7681. self.file_saved.emit("DXF", filename)
  7682. def on_file_importsvg(self, type_of_obj):
  7683. """
  7684. Callback for menu item File->Import SVG.
  7685. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7686. :type type_of_obj: str
  7687. :return: None
  7688. """
  7689. self.report_usage("on_file_importsvg")
  7690. App.log.debug("on_file_importsvg()")
  7691. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  7692. try:
  7693. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7694. directory=self.get_last_folder(), filter=_filter_)
  7695. except TypeError:
  7696. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7697. filter=_filter_)
  7698. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7699. type_of_obj = "geometry"
  7700. filenames = [str(filename) for filename in filenames]
  7701. if len(filenames) == 0:
  7702. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7703. else:
  7704. for filename in filenames:
  7705. if filename != '':
  7706. self.worker_task.emit({'fcn': self.import_svg,
  7707. 'params': [filename, type_of_obj]})
  7708. def on_file_importdxf(self, type_of_obj):
  7709. """
  7710. Callback for menu item File->Import DXF.
  7711. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7712. :type type_of_obj: str
  7713. :return: None
  7714. """
  7715. self.report_usage("on_file_importdxf")
  7716. App.log.debug("on_file_importdxf()")
  7717. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7718. try:
  7719. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7720. directory=self.get_last_folder(),
  7721. filter=_filter_)
  7722. except TypeError:
  7723. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7724. filter=_filter_)
  7725. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7726. type_of_obj = "geometry"
  7727. filenames = [str(filename) for filename in filenames]
  7728. if len(filenames) == 0:
  7729. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7730. else:
  7731. for filename in filenames:
  7732. if filename != '':
  7733. self.worker_task.emit({'fcn': self.import_dxf,
  7734. 'params': [filename, type_of_obj]})
  7735. # ###############################################################################################################
  7736. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7737. # ###############################################################################################################
  7738. def init_code_editor(self, name):
  7739. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  7740. # add the tab if it was closed
  7741. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  7742. self.text_editor_tab.setObjectName('text_editor_tab')
  7743. # delete the absolute and relative position and messages in the infobar
  7744. self.ui.position_label.setText("")
  7745. self.ui.rel_position_label.setText("")
  7746. # first clear previous text in text editor (if any)
  7747. self.text_editor_tab.code_editor.clear()
  7748. self.text_editor_tab.code_editor.setReadOnly(False)
  7749. self.toggle_codeeditor = True
  7750. self.text_editor_tab.code_editor.completer_enable = False
  7751. self.text_editor_tab.buttonRun.hide()
  7752. # make sure to keep a reference to the code editor
  7753. self.reference_code_editor = self.text_editor_tab.code_editor
  7754. # Switch plot_area to CNCJob tab
  7755. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  7756. def on_view_source(self):
  7757. """
  7758. Called when the user wants to see the source file of the selected object
  7759. :return:
  7760. """
  7761. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  7762. self.proc_container.view.set_busy(_("Loading..."))
  7763. try:
  7764. obj = self.collection.get_active()
  7765. except Exception as e:
  7766. log.debug("App.on_view_source() --> %s" % str(e))
  7767. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  7768. return 'fail'
  7769. if obj is None:
  7770. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  7771. return 'fail'
  7772. flt = "All Files (*.*)"
  7773. if obj.kind == 'gerber':
  7774. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  7775. elif obj.kind == 'excellon':
  7776. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  7777. elif obj.kind == 'cncjob':
  7778. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  7779. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  7780. # add the tab if it was closed
  7781. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  7782. self.source_editor_tab.setObjectName('source_editor_tab')
  7783. # delete the absolute and relative position and messages in the infobar
  7784. self.ui.position_label.setText("")
  7785. self.ui.rel_position_label.setText("")
  7786. # first clear previous text in text editor (if any)
  7787. self.source_editor_tab.code_editor.clear()
  7788. self.source_editor_tab.code_editor.setReadOnly(False)
  7789. self.source_editor_tab.code_editor.completer_enable = False
  7790. self.source_editor_tab.buttonRun.hide()
  7791. # Switch plot_area to CNCJob tab
  7792. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  7793. try:
  7794. self.source_editor_tab.buttonOpen.clicked.disconnect()
  7795. except TypeError:
  7796. pass
  7797. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  7798. try:
  7799. self.source_editor_tab.buttonSave.clicked.disconnect()
  7800. except TypeError:
  7801. pass
  7802. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  7803. # then append the text from GCode to the text editor
  7804. if obj.kind == 'cncjob':
  7805. try:
  7806. file = obj.export_gcode(
  7807. preamble=self.defaults["cncjob_prepend"],
  7808. postamble=self.defaults["cncjob_append"],
  7809. to_file=True)
  7810. if file == 'fail':
  7811. return 'fail'
  7812. except AttributeError:
  7813. self.inform.emit('[WARNING_NOTCL] %s' %
  7814. _("There is no selected object for which to see it's source file code."))
  7815. return 'fail'
  7816. else:
  7817. try:
  7818. file = StringIO(obj.source_file)
  7819. except (AttributeError, TypeError):
  7820. self.inform.emit('[WARNING_NOTCL] %s' %
  7821. _("There is no selected object for which to see it's source file code."))
  7822. return 'fail'
  7823. self.source_editor_tab.t_frame.hide()
  7824. try:
  7825. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  7826. # for line in file:
  7827. # QtWidgets.QApplication.processEvents()
  7828. # proc_line = str(line).strip('\n')
  7829. # self.source_editor_tab.code_editor.append(proc_line)
  7830. except Exception as e:
  7831. log.debug('App.on_view_source() -->%s' % str(e))
  7832. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  7833. return
  7834. self.source_editor_tab.handleTextChanged()
  7835. self.source_editor_tab.t_frame.show()
  7836. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7837. self.proc_container.view.set_idle()
  7838. # self.ui.show()
  7839. def on_toggle_code_editor(self):
  7840. self.report_usage("on_toggle_code_editor()")
  7841. if self.toggle_codeeditor is False:
  7842. self.init_code_editor(name=_("Code Editor"))
  7843. self.text_editor_tab.buttonOpen.clicked.disconnect()
  7844. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  7845. self.text_editor_tab.buttonSave.clicked.disconnect()
  7846. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  7847. else:
  7848. for idx in range(self.ui.plot_tab_area.count()):
  7849. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  7850. self.ui.plot_tab_area.closeTab(idx)
  7851. break
  7852. self.toggle_codeeditor = False
  7853. def on_code_editor_close(self):
  7854. self.toggle_codeeditor = False
  7855. def goto_text_line(self):
  7856. """
  7857. Will scroll a text to the specified text line.
  7858. :return: None
  7859. """
  7860. dia_box = Dialog_box(title=_("Go to Line ..."),
  7861. label=_("Line:"),
  7862. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  7863. initial_text='')
  7864. try:
  7865. line = int(dia_box.location) - 1
  7866. except (ValueError, TypeError):
  7867. line = 0
  7868. if dia_box.ok:
  7869. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  7870. # at the top of the window
  7871. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  7872. # get the document() of the TextEditor
  7873. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  7874. # create a Text Cursor based on the searched line
  7875. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  7876. # set cursor of the code editor with the cursor at the searcehd line
  7877. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  7878. def on_filenewscript(self, silent=False, name=None, text=None):
  7879. """
  7880. Will create a new script file and open it in the Code Editor
  7881. :param silent: if True will not display status messages
  7882. :param name: if specified will be the name of the new script
  7883. :param text: pass a source file to the newly created script to be loaded in it
  7884. :return: None
  7885. """
  7886. if silent is False:
  7887. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  7888. # delete the absolute and relative position and messages in the infobar
  7889. self.ui.position_label.setText("")
  7890. self.ui.rel_position_label.setText("")
  7891. if name is not None:
  7892. self.new_script_object(name=name, text=text)
  7893. else:
  7894. self.new_script_object(text=text)
  7895. # script_text = script_obj.source_file
  7896. #
  7897. # self.proc_container.view.set_busy(_("Loading..."))
  7898. # script_obj.script_editor_tab.t_frame.hide()
  7899. #
  7900. # script_obj.script_editor_tab.t_frame.show()
  7901. # self.proc_container.view.set_idle()
  7902. def on_fileopenscript(self, name=None, silent=False):
  7903. """
  7904. Will open a Tcl script file into the Code Editor
  7905. :param silent: if True will not display status messages
  7906. :param name: name of a Tcl script file to open
  7907. :return:
  7908. """
  7909. self.report_usage("on_fileopenscript")
  7910. App.log.debug("on_fileopenscript()")
  7911. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7912. "All Files (*.*)"
  7913. if name:
  7914. filenames = [name]
  7915. else:
  7916. try:
  7917. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7918. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  7919. except TypeError:
  7920. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7921. if len(filenames) == 0:
  7922. if silent is False:
  7923. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7924. else:
  7925. for filename in filenames:
  7926. if filename != '':
  7927. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7928. def on_filerunscript(self, name=None, silent=False):
  7929. """
  7930. File menu callback for loading and running a TCL script.
  7931. :param silent: if True will not display status messages
  7932. :param name: name of a Tcl script file to be run by FlatCAM
  7933. :return: None
  7934. """
  7935. self.report_usage("on_filerunscript")
  7936. App.log.debug("on_file_runscript()")
  7937. if name:
  7938. filename = name
  7939. if self.cmd_line_headless != 1:
  7940. self.splash.showMessage('%s: %ssec\n%s' %
  7941. (_("Canvas initialization started.\n"
  7942. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7943. _("Executing ScriptObject file.")
  7944. ),
  7945. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7946. color=QtGui.QColor("gray"))
  7947. else:
  7948. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7949. "All Files (*.*)"
  7950. try:
  7951. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7952. directory=self.get_last_folder(), filter=_filter_)
  7953. except TypeError:
  7954. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7955. # The Qt methods above will return a QString which can cause problems later.
  7956. # So far json.dump() will fail to serialize it.
  7957. filename = str(filename)
  7958. if filename == "":
  7959. if silent is False:
  7960. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7961. else:
  7962. if self.cmd_line_headless != 1:
  7963. if self.ui.shell_dock.isHidden():
  7964. self.ui.shell_dock.show()
  7965. try:
  7966. with open(filename, "r") as tcl_script:
  7967. cmd_line_shellfile_content = tcl_script.read()
  7968. if self.cmd_line_headless != 1:
  7969. self.shell.exec_command(cmd_line_shellfile_content)
  7970. else:
  7971. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7972. if silent is False:
  7973. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7974. except Exception as e:
  7975. log.debug("App.on_filerunscript() -> %s" % str(e))
  7976. sys.exit(2)
  7977. def on_file_saveproject(self, silent=False):
  7978. """
  7979. Callback for menu item File->Save Project. Saves the project to
  7980. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7981. if set to None. The project is saved by calling ``self.save_project()``.
  7982. :param silent: if True will not display status messages
  7983. :return: None
  7984. """
  7985. self.report_usage("on_file_saveproject")
  7986. if self.project_filename is None:
  7987. self.on_file_saveprojectas()
  7988. else:
  7989. self.worker_task.emit({'fcn': self.save_project,
  7990. 'params': [self.project_filename, silent]})
  7991. if self.defaults["global_open_style"] is False:
  7992. self.file_opened.emit("project", self.project_filename)
  7993. self.file_saved.emit("project", self.project_filename)
  7994. self.set_ui_title(name=self.project_filename)
  7995. self.should_we_save = False
  7996. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7997. """
  7998. Callback for menu item File->Save Project As... Opens a file
  7999. chooser and saves the project to the given file via
  8000. ``self.save_project()``.
  8001. :param make_copy if to be create a copy of the project; boolean
  8002. :param use_thread: if to be run in a separate thread; boolean
  8003. :param quit_action: if to be followed by quiting the application; boolean
  8004. :return: None
  8005. """
  8006. self.report_usage("on_file_saveprojectas")
  8007. self.date = str(datetime.today()).rpartition('.')[0]
  8008. self.date = ''.join(c for c in self.date if c not in ':-')
  8009. self.date = self.date.replace(' ', '_')
  8010. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  8011. try:
  8012. filename, _f = FCFileSaveDialog.get_saved_filename(
  8013. caption=_("Save Project As ..."),
  8014. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  8015. proj=_("Project")),
  8016. filter=filter_
  8017. )
  8018. except TypeError:
  8019. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  8020. filename = str(filename)
  8021. if filename == '':
  8022. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8023. return
  8024. if use_thread is True:
  8025. self.worker_task.emit({'fcn': self.save_project,
  8026. 'params': [filename, quit_action]})
  8027. else:
  8028. self.save_project(filename, quit_action)
  8029. # self.save_project(filename)
  8030. if self.defaults["global_open_style"] is False:
  8031. self.file_opened.emit("project", filename)
  8032. self.file_saved.emit("project", filename)
  8033. if not make_copy:
  8034. self.project_filename = filename
  8035. self.set_ui_title(name=self.project_filename)
  8036. self.should_we_save = False
  8037. def on_file_save_objects_pdf(self, use_thread=True):
  8038. self.date = str(datetime.today()).rpartition('.')[0]
  8039. self.date = ''.join(c for c in self.date if c not in ':-')
  8040. self.date = self.date.replace(' ', '_')
  8041. try:
  8042. obj_selection = self.collection.get_selected()
  8043. if len(obj_selection) == 1:
  8044. obj_name = str(obj_selection[0].options['name'])
  8045. else:
  8046. obj_name = _("FlatCAM objects print")
  8047. except AttributeError as err:
  8048. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  8049. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  8050. return
  8051. if not obj_selection:
  8052. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  8053. return
  8054. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  8055. try:
  8056. filename, _f = FCFileSaveDialog.get_saved_filename(
  8057. caption=_("Save Object as PDF ..."),
  8058. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  8059. obj_name=obj_name,
  8060. date=self.date),
  8061. filter=filter_
  8062. )
  8063. except TypeError:
  8064. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  8065. filename = str(filename)
  8066. if filename == '':
  8067. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8068. return
  8069. if use_thread is True:
  8070. proc = self.proc_container.new(_("Printing PDF ... Please wait."))
  8071. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  8072. else:
  8073. self.save_pdf(filename, obj_selection)
  8074. # self.save_project(filename)
  8075. if self.defaults["global_open_style"] is False:
  8076. self.file_opened.emit("pdf", filename)
  8077. self.file_saved.emit("pdf", filename)
  8078. def save_pdf(self, file_name, obj_selection):
  8079. p_size = self.defaults['global_workspaceT']
  8080. orientation = self.defaults['global_workspace_orientation']
  8081. color = 'black'
  8082. transparency_level = 1.0
  8083. self.pagesize = {}
  8084. self.pagesize.update(
  8085. {
  8086. 'Bounds': None,
  8087. 'A0': (841 * mm, 1189 * mm),
  8088. 'A1': (594 * mm, 841 * mm),
  8089. 'A2': (420 * mm, 594 * mm),
  8090. 'A3': (297 * mm, 420 * mm),
  8091. 'A4': (210 * mm, 297 * mm),
  8092. 'A5': (148 * mm, 210 * mm),
  8093. 'A6': (105 * mm, 148 * mm),
  8094. 'A7': (74 * mm, 105 * mm),
  8095. 'A8': (52 * mm, 74 * mm),
  8096. 'A9': (37 * mm, 52 * mm),
  8097. 'A10': (26 * mm, 37 * mm),
  8098. 'B0': (1000 * mm, 1414 * mm),
  8099. 'B1': (707 * mm, 1000 * mm),
  8100. 'B2': (500 * mm, 707 * mm),
  8101. 'B3': (353 * mm, 500 * mm),
  8102. 'B4': (250 * mm, 353 * mm),
  8103. 'B5': (176 * mm, 250 * mm),
  8104. 'B6': (125 * mm, 176 * mm),
  8105. 'B7': (88 * mm, 125 * mm),
  8106. 'B8': (62 * mm, 88 * mm),
  8107. 'B9': (44 * mm, 62 * mm),
  8108. 'B10': (31 * mm, 44 * mm),
  8109. 'C0': (917 * mm, 1297 * mm),
  8110. 'C1': (648 * mm, 917 * mm),
  8111. 'C2': (458 * mm, 648 * mm),
  8112. 'C3': (324 * mm, 458 * mm),
  8113. 'C4': (229 * mm, 324 * mm),
  8114. 'C5': (162 * mm, 229 * mm),
  8115. 'C6': (114 * mm, 162 * mm),
  8116. 'C7': (81 * mm, 114 * mm),
  8117. 'C8': (57 * mm, 81 * mm),
  8118. 'C9': (40 * mm, 57 * mm),
  8119. 'C10': (28 * mm, 40 * mm),
  8120. # American paper sizes
  8121. 'LETTER': (8.5 * inch, 11 * inch),
  8122. 'LEGAL': (8.5 * inch, 14 * inch),
  8123. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  8124. # From https://en.wikipedia.org/wiki/Paper_size
  8125. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  8126. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  8127. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  8128. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  8129. 'LEDGER': (17 * inch, 11 * inch),
  8130. }
  8131. )
  8132. exported_svg = []
  8133. for obj in obj_selection:
  8134. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  8135. scale_factor_x=None, scale_factor_y=None,
  8136. skew_factor_x=None, skew_factor_y=None,
  8137. mirror=None)
  8138. if obj.kind.lower() == 'gerber':
  8139. # color = self.defaults["gerber_plot_fill"][:-2]
  8140. color = obj.fill_color[:-2]
  8141. elif obj.kind.lower() == 'excellon':
  8142. color = '#C40000'
  8143. elif obj.kind.lower() == 'geometry':
  8144. color = self.defaults["global_draw_color"]
  8145. # Change the attributes of the exported SVG
  8146. # We don't need stroke-width
  8147. # We set opacity to maximum
  8148. # We set the colour to WHITE
  8149. root = ET.fromstring(svg_obj)
  8150. for child in root:
  8151. child.set('fill', str(color))
  8152. child.set('opacity', str(transparency_level))
  8153. child.set('stroke', str(color))
  8154. exported_svg.append(ET.tostring(root))
  8155. xmin = Inf
  8156. ymin = Inf
  8157. xmax = -Inf
  8158. ymax = -Inf
  8159. for obj in obj_selection:
  8160. try:
  8161. gxmin, gymin, gxmax, gymax = obj.bounds()
  8162. xmin = min([xmin, gxmin])
  8163. ymin = min([ymin, gymin])
  8164. xmax = max([xmax, gxmax])
  8165. ymax = max([ymax, gymax])
  8166. except Exception as e:
  8167. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  8168. # Determine bounding area for svg export
  8169. bounds = [xmin, ymin, xmax, ymax]
  8170. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  8171. # This contain the measure units
  8172. uom = obj_selection[0].units.lower()
  8173. # Define a boundary around SVG of about 1.0mm (~39mils)
  8174. if uom in "mm":
  8175. boundary = 1.0
  8176. else:
  8177. boundary = 0.0393701
  8178. # Convert everything to strings for use in the xml doc
  8179. svgwidth = str(size[0] + (2 * boundary))
  8180. svgheight = str(size[1] + (2 * boundary))
  8181. minx = str(bounds[0] - boundary)
  8182. miny = str(bounds[1] + boundary + size[1])
  8183. # Add a SVG Header and footer to the svg output from shapely
  8184. # The transform flips the Y Axis so that everything renders
  8185. # properly within svg apps such as inkscape
  8186. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8187. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8188. svg_header += 'width="' + svgwidth + uom + '" '
  8189. svg_header += 'height="' + svgheight + uom + '" '
  8190. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8191. svg_header += '>'
  8192. svg_header += '<g transform="scale(1,-1)">'
  8193. svg_footer = '</g> </svg>'
  8194. svg_elem = str(svg_header)
  8195. for svg_item in exported_svg:
  8196. svg_elem += str(svg_item)
  8197. svg_elem += str(svg_footer)
  8198. # Parse the xml through a xml parser just to add line feeds
  8199. # and to make it look more pretty for the output
  8200. doc = parse_xml_string(svg_elem)
  8201. doc_final = doc.toprettyxml()
  8202. try:
  8203. if self.defaults['units'].upper() == 'IN':
  8204. unit = inch
  8205. else:
  8206. unit = mm
  8207. doc_final = StringIO(doc_final)
  8208. drawing = svg2rlg(doc_final)
  8209. if p_size == 'Bounds':
  8210. renderPDF.drawToFile(drawing, file_name)
  8211. else:
  8212. if orientation == 'p':
  8213. page_size = portrait(self.pagesize[p_size])
  8214. else:
  8215. page_size = landscape(self.pagesize[p_size])
  8216. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  8217. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  8218. renderPDF.draw(drawing, my_canvas, 0, 0)
  8219. my_canvas.save()
  8220. except Exception as e:
  8221. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  8222. return 'fail'
  8223. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  8224. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8225. """
  8226. Exports a Geometry Object to an SVG file.
  8227. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8228. :param filename: Path to the SVG file to save to.
  8229. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8230. :return:
  8231. """
  8232. self.report_usage("export_svg()")
  8233. if filename is None:
  8234. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8235. is not None else self.defaults["global_last_folder"]
  8236. self.log.debug("export_svg()")
  8237. try:
  8238. obj = self.collection.get_by_name(str(obj_name))
  8239. except Exception:
  8240. # TODO: The return behavior has not been established... should raise exception?
  8241. return "Could not retrieve object: %s" % obj_name
  8242. with self.proc_container.new(_("Exporting SVG")) as proc:
  8243. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8244. # Determine bounding area for svg export
  8245. bounds = obj.bounds()
  8246. size = obj.size()
  8247. # Convert everything to strings for use in the xml doc
  8248. svgwidth = str(size[0])
  8249. svgheight = str(size[1])
  8250. minx = str(bounds[0])
  8251. miny = str(bounds[1] - size[1])
  8252. uom = obj.units.lower()
  8253. # Add a SVG Header and footer to the svg output from shapely
  8254. # The transform flips the Y Axis so that everything renders
  8255. # properly within svg apps such as inkscape
  8256. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8257. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8258. svg_header += 'width="' + svgwidth + uom + '" '
  8259. svg_header += 'height="' + svgheight + uom + '" '
  8260. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8261. svg_header += '<g transform="scale(1,-1)">'
  8262. svg_footer = '</g> </svg>'
  8263. svg_elem = svg_header + exported_svg + svg_footer
  8264. # Parse the xml through a xml parser just to add line feeds
  8265. # and to make it look more pretty for the output
  8266. svgcode = parse_xml_string(svg_elem)
  8267. svgcode = svgcode.toprettyxml()
  8268. try:
  8269. with open(filename, 'w') as fp:
  8270. fp.write(svgcode)
  8271. except PermissionError:
  8272. self.inform.emit('[WARNING] %s' %
  8273. _("Permission denied, saving not possible.\n"
  8274. "Most likely another app is holding the file open and not accessible."))
  8275. return 'fail'
  8276. if self.defaults["global_open_style"] is False:
  8277. self.file_opened.emit("SVG", filename)
  8278. self.file_saved.emit("SVG", filename)
  8279. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  8280. def save_source_file(self, obj_name, filename, use_thread=True):
  8281. """
  8282. Exports a FlatCAM Object to an Gerber/Excellon file.
  8283. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8284. :param filename: Path to the Gerber file to save to.
  8285. :param use_thread: if to be run in a separate thread
  8286. :return:
  8287. """
  8288. self.report_usage("save source file()")
  8289. if filename is None:
  8290. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8291. is not None else self.defaults["global_last_folder"]
  8292. self.log.debug("save source file()")
  8293. obj = self.collection.get_by_name(obj_name)
  8294. file_string = StringIO(obj.source_file)
  8295. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8296. if file_string.getvalue() == '':
  8297. self.inform.emit('[ERROR_NOTCL] %s' %
  8298. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  8299. return 'fail'
  8300. try:
  8301. with open(filename, 'w') as file:
  8302. file.writelines('G04*\n')
  8303. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8304. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8305. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8306. file.writelines('G04 Created on : %s*\n' % time_string)
  8307. for line in file_string:
  8308. file.writelines(line)
  8309. except PermissionError:
  8310. self.inform.emit('[WARNING] %s' %
  8311. _("Permission denied, saving not possible.\n"
  8312. "Most likely another app is holding the file open and not accessible."))
  8313. return 'fail'
  8314. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8315. """
  8316. Exports a Excellon Object to an Excellon file.
  8317. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8318. :param filename: Path to the Excellon file to save to.
  8319. :param local_use:
  8320. :param use_thread: if to be run in a separate thread
  8321. :return:
  8322. """
  8323. self.report_usage("export_excellon()")
  8324. if filename is None:
  8325. if self.defaults["global_last_save_folder"]:
  8326. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  8327. else:
  8328. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  8329. self.log.debug("export_excellon()")
  8330. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8331. self.defaults["excellon_exp_decimals"]
  8332. )
  8333. if local_use is None:
  8334. try:
  8335. obj = self.collection.get_by_name(str(obj_name))
  8336. except Exception:
  8337. return "Could not retrieve object: %s" % obj_name
  8338. else:
  8339. obj = local_use
  8340. if not isinstance(obj, ExcellonObject):
  8341. self.inform.emit('[ERROR_NOTCL] %s' %
  8342. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8343. return
  8344. # updated units
  8345. eunits = self.defaults["excellon_exp_units"]
  8346. ewhole = self.defaults["excellon_exp_integer"]
  8347. efract = self.defaults["excellon_exp_decimals"]
  8348. ezeros = self.defaults["excellon_exp_zeros"]
  8349. eformat = self.defaults["excellon_exp_format"]
  8350. slot_type = self.defaults["excellon_exp_slot_type"]
  8351. fc_units = self.defaults['units'].upper()
  8352. if fc_units == 'MM':
  8353. factor = 1 if eunits == 'METRIC' else 0.03937
  8354. else:
  8355. factor = 25.4 if eunits == 'METRIC' else 1
  8356. def make_excellon():
  8357. try:
  8358. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8359. header = 'M48\n'
  8360. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8361. (str(self.version), str(self.version_date))
  8362. header += ';Filename: %s' % str(obj_name) + '\n'
  8363. header += ';Created on : %s' % time_str + '\n'
  8364. if eformat == 'dec':
  8365. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8366. header += eunits + '\n'
  8367. for tool in obj.tools:
  8368. if eunits == 'METRIC':
  8369. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8370. tool=str(tool),
  8371. dec=2)
  8372. else:
  8373. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8374. tool=str(tool),
  8375. dec=4)
  8376. else:
  8377. if ezeros == 'LZ':
  8378. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8379. form='ndec', e_zeros='LZ', factor=factor,
  8380. slot_type=slot_type)
  8381. header += '%s,%s\n' % (eunits, 'LZ')
  8382. header += format_exc
  8383. for tool in obj.tools:
  8384. if eunits == 'METRIC':
  8385. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8386. tool=str(tool),
  8387. dec=2)
  8388. else:
  8389. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8390. tool=str(tool),
  8391. dec=4)
  8392. else:
  8393. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8394. form='ndec', e_zeros='TZ', factor=factor,
  8395. slot_type=slot_type)
  8396. header += '%s,%s\n' % (eunits, 'TZ')
  8397. header += format_exc
  8398. for tool in obj.tools:
  8399. if eunits == 'METRIC':
  8400. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8401. tool=str(tool),
  8402. dec=2)
  8403. else:
  8404. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8405. tool=str(tool),
  8406. dec=4)
  8407. header += '%\n'
  8408. footer = 'M30\n'
  8409. exported_excellon = header
  8410. exported_excellon += excellon_code
  8411. exported_excellon += footer
  8412. if local_use is None:
  8413. try:
  8414. with open(filename, 'w') as fp:
  8415. fp.write(exported_excellon)
  8416. except PermissionError:
  8417. self.inform.emit('[WARNING] %s' %
  8418. _("Permission denied, saving not possible.\n"
  8419. "Most likely another app is holding the file open and not accessible."))
  8420. return 'fail'
  8421. if self.defaults["global_open_style"] is False:
  8422. self.file_opened.emit("Excellon", filename)
  8423. self.file_saved.emit("Excellon", filename)
  8424. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  8425. else:
  8426. return exported_excellon
  8427. except Exception as e:
  8428. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8429. return 'fail'
  8430. if use_thread is True:
  8431. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8432. def job_thread_exc(app_obj):
  8433. ret = make_excellon()
  8434. if ret == 'fail':
  8435. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  8436. return
  8437. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8438. else:
  8439. eret = make_excellon()
  8440. if eret == 'fail':
  8441. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  8442. return 'fail'
  8443. if local_use is not None:
  8444. return eret
  8445. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8446. """
  8447. Exports a Gerber Object to an Gerber file.
  8448. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8449. :param filename: Path to the Gerber file to save to.
  8450. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8451. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8452. :param use_thread: if to be run in a separate thread
  8453. :return:
  8454. """
  8455. self.report_usage("export_gerber()")
  8456. if filename is None:
  8457. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8458. is not None else self.defaults["global_last_folder"]
  8459. self.log.debug("export_gerber()")
  8460. if local_use is None:
  8461. try:
  8462. obj = self.collection.get_by_name(str(obj_name))
  8463. except Exception:
  8464. return "Could not retrieve object: %s" % obj_name
  8465. else:
  8466. obj = local_use
  8467. # updated units
  8468. gunits = self.defaults["gerber_exp_units"]
  8469. gwhole = self.defaults["gerber_exp_integer"]
  8470. gfract = self.defaults["gerber_exp_decimals"]
  8471. gzeros = self.defaults["gerber_exp_zeros"]
  8472. fc_units = self.defaults['units'].upper()
  8473. if fc_units == 'MM':
  8474. factor = 1 if gunits == 'MM' else 0.03937
  8475. else:
  8476. factor = 25.4 if gunits == 'MM' else 1
  8477. def make_gerber():
  8478. try:
  8479. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8480. header = 'G04*\n'
  8481. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8482. (str(self.version), str(self.version_date))
  8483. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8484. header += 'G04 Created on : %s*' % time_str + '\n'
  8485. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8486. header += "%MO{units}*%\n".format(units=gunits)
  8487. for apid in obj.apertures:
  8488. if obj.apertures[apid]['type'] == 'C':
  8489. header += "%ADD{apid}{type},{size}*%\n".format(
  8490. apid=str(apid),
  8491. type='C',
  8492. size=(factor * obj.apertures[apid]['size'])
  8493. )
  8494. elif obj.apertures[apid]['type'] == 'R':
  8495. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8496. apid=str(apid),
  8497. type='R',
  8498. width=(factor * obj.apertures[apid]['width']),
  8499. height=(factor * obj.apertures[apid]['height'])
  8500. )
  8501. elif obj.apertures[apid]['type'] == 'O':
  8502. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8503. apid=str(apid),
  8504. type='O',
  8505. width=(factor * obj.apertures[apid]['width']),
  8506. height=(factor * obj.apertures[apid]['height'])
  8507. )
  8508. header += '\n'
  8509. # obsolete units but some software may need it
  8510. if gunits == 'IN':
  8511. header += 'G70*\n'
  8512. else:
  8513. header += 'G71*\n'
  8514. # Absolute Mode
  8515. header += 'G90*\n'
  8516. header += 'G01*\n'
  8517. # positive polarity
  8518. header += '%LPD*%\n'
  8519. footer = 'M02*\n'
  8520. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8521. exported_gerber = header
  8522. exported_gerber += gerber_code
  8523. exported_gerber += footer
  8524. if local_use is None:
  8525. try:
  8526. with open(filename, 'w') as fp:
  8527. fp.write(exported_gerber)
  8528. except PermissionError:
  8529. self.inform.emit('[WARNING] %s' %
  8530. _("Permission denied, saving not possible.\n"
  8531. "Most likely another app is holding the file open and not accessible."))
  8532. return 'fail'
  8533. if self.defaults["global_open_style"] is False:
  8534. self.file_opened.emit("Gerber", filename)
  8535. self.file_saved.emit("Gerber", filename)
  8536. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  8537. else:
  8538. return exported_gerber
  8539. except Exception as e:
  8540. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8541. return 'fail'
  8542. if use_thread is True:
  8543. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8544. def job_thread_grb(app_obj):
  8545. ret = make_gerber()
  8546. if ret == 'fail':
  8547. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  8548. return
  8549. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8550. else:
  8551. gret = make_gerber()
  8552. if gret == 'fail':
  8553. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  8554. return 'fail'
  8555. if local_use is not None:
  8556. return gret
  8557. def export_dxf(self, obj_name, filename, use_thread=True):
  8558. """
  8559. Exports a Geometry Object to an DXF file.
  8560. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8561. :param filename: Path to the DXF file to save to.
  8562. :param use_thread: if to be run in a separate thread
  8563. :return:
  8564. """
  8565. self.report_usage("export_dxf()")
  8566. if filename is None:
  8567. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8568. is not None else self.defaults["global_last_folder"]
  8569. self.log.debug("export_dxf()")
  8570. try:
  8571. obj = self.collection.get_by_name(str(obj_name))
  8572. except Exception:
  8573. # TODO: The return behavior has not been established... should raise exception?
  8574. return "Could not retrieve object: %s" % obj_name
  8575. def make_dxf():
  8576. try:
  8577. dxf_code = obj.export_dxf()
  8578. dxf_code.saveas(filename)
  8579. if self.defaults["global_open_style"] is False:
  8580. self.file_opened.emit("DXF", filename)
  8581. self.file_saved.emit("DXF", filename)
  8582. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8583. except Exception:
  8584. return 'fail'
  8585. if use_thread is True:
  8586. with self.proc_container.new(_("Exporting DXF")) as proc:
  8587. def job_thread_exc(app_obj):
  8588. ret_dxf_val = make_dxf()
  8589. if ret_dxf_val == 'fail':
  8590. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8591. return
  8592. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8593. else:
  8594. ret = make_dxf()
  8595. if ret == 'fail':
  8596. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8597. return
  8598. def import_svg(self, filename, geo_type='geometry', outname=None):
  8599. """
  8600. Adds a new Geometry Object to the projects and populates
  8601. it with shapes extracted from the SVG file.
  8602. :param filename: Path to the SVG file.
  8603. :param geo_type: Type of FlatCAM object that will be created from SVG
  8604. :param outname:
  8605. :return:
  8606. """
  8607. self.report_usage("import_svg()")
  8608. log.debug("App.import_svg()")
  8609. obj_type = ""
  8610. if geo_type is None or geo_type == "geometry":
  8611. obj_type = "geometry"
  8612. elif geo_type == "gerber":
  8613. obj_type = "gerber"
  8614. else:
  8615. self.inform.emit('[ERROR_NOTCL] %s' %
  8616. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8617. return
  8618. units = self.defaults['units'].upper()
  8619. def obj_init(geo_obj, app_obj):
  8620. geo_obj.import_svg(filename, obj_type, units=units)
  8621. geo_obj.multigeo = False
  8622. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  8623. with self.proc_container.new(_("Importing SVG")) as proc:
  8624. # Object name
  8625. name = outname or filename.split('/')[-1].split('\\')[-1]
  8626. self.new_object(obj_type, name, obj_init, autoselected=False)
  8627. # Register recent file
  8628. self.file_opened.emit("svg", filename)
  8629. # GUI feedback
  8630. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8631. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8632. """
  8633. Adds a new Geometry Object to the projects and populates
  8634. it with shapes extracted from the DXF file.
  8635. :param filename: Path to the DXF file.
  8636. :param geo_type: Type of FlatCAM object that will be created from DXF
  8637. :param outname: Name for the imported Geometry
  8638. :return:
  8639. """
  8640. self.report_usage("import_dxf()")
  8641. obj_type = ""
  8642. if geo_type is None or geo_type == "geometry":
  8643. obj_type = "geometry"
  8644. elif geo_type == "gerber":
  8645. obj_type = geo_type
  8646. else:
  8647. self.inform.emit('[ERROR_NOTCL] %s' %
  8648. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8649. return
  8650. units = self.defaults['units'].upper()
  8651. def obj_init(geo_obj, app_obj):
  8652. geo_obj.import_dxf(filename, obj_type, units=units)
  8653. geo_obj.multigeo = False
  8654. with self.proc_container.new(_("Importing DXF")) as proc:
  8655. # Object name
  8656. name = outname or filename.split('/')[-1].split('\\')[-1]
  8657. self.new_object(obj_type, name, obj_init, autoselected=False)
  8658. # Register recent file
  8659. self.file_opened.emit("dxf", filename)
  8660. # GUI feedback
  8661. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8662. def open_gerber(self, filename, outname=None):
  8663. """
  8664. Opens a Gerber file, parses it and creates a new object for
  8665. it in the program. Thread-safe.
  8666. :param outname: Name of the resulting object. None causes the
  8667. name to be that of the file. Str.
  8668. :param filename: Gerber file filename
  8669. :type filename: str
  8670. :return: None
  8671. """
  8672. # How the object should be initialized
  8673. def obj_init(gerber_obj, app_obj):
  8674. assert isinstance(gerber_obj, GerberObject), \
  8675. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  8676. # Opening the file happens here
  8677. try:
  8678. gerber_obj.parse_file(filename)
  8679. except IOError:
  8680. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8681. return "fail"
  8682. except ParseError as err:
  8683. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8684. app_obj.log.error(str(err))
  8685. return "fail"
  8686. except Exception as e:
  8687. log.debug("App.open_gerber() --> %s" % str(e))
  8688. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8689. msg += traceback.format_exc()
  8690. app_obj.inform.emit(msg)
  8691. return "fail"
  8692. if gerber_obj.is_empty():
  8693. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8694. _("Object is not Gerber file or empty. Aborting object creation."))
  8695. return "fail"
  8696. App.log.debug("open_gerber()")
  8697. with self.proc_container.new(_("Opening Gerber")) as proc:
  8698. # Object name
  8699. name = outname or filename.split('/')[-1].split('\\')[-1]
  8700. # # ## Object creation # ##
  8701. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8702. if ret == 'fail':
  8703. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  8704. return 'fail'
  8705. # Register recent file
  8706. self.file_opened.emit("gerber", filename)
  8707. # GUI feedback
  8708. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8709. def open_excellon(self, filename, outname=None, plot=True):
  8710. """
  8711. Opens an Excellon file, parses it and creates a new object for
  8712. it in the program. Thread-safe.
  8713. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8714. :param filename: Excellon file filename
  8715. :type filename: str
  8716. :param plot: boolean, to plot or not the resulting object
  8717. :return: None
  8718. """
  8719. App.log.debug("open_excellon()")
  8720. # How the object should be initialized
  8721. def obj_init(excellon_obj, app_obj):
  8722. try:
  8723. ret = excellon_obj.parse_file(filename=filename)
  8724. if ret == "fail":
  8725. log.debug("Excellon parsing failed.")
  8726. self.inform.emit('[ERROR_NOTCL] %s' %
  8727. _("This is not Excellon file."))
  8728. return "fail"
  8729. except IOError:
  8730. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8731. (_("Cannot open file"), filename))
  8732. log.debug("Could not open Excellon object.")
  8733. return "fail"
  8734. except Exception:
  8735. msg = '[ERROR_NOTCL] %s' % \
  8736. _("An internal error has occurred. See shell.\n")
  8737. msg += traceback.format_exc()
  8738. app_obj.inform.emit(msg)
  8739. return "fail"
  8740. ret = excellon_obj.create_geometry()
  8741. if ret == 'fail':
  8742. log.debug("Could not create geometry for Excellon object.")
  8743. return "fail"
  8744. for tool in excellon_obj.tools:
  8745. if excellon_obj.tools[tool]['solid_geometry']:
  8746. return
  8747. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8748. (_("No geometry found in file"), filename))
  8749. return "fail"
  8750. with self.proc_container.new(_("Opening Excellon.")):
  8751. # Object name
  8752. name = outname or filename.split('/')[-1].split('\\')[-1]
  8753. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8754. if ret_val == 'fail':
  8755. self.inform.emit('[ERROR_NOTCL] %s' %
  8756. _('Open Excellon file failed. Probable not an Excellon file.'))
  8757. return
  8758. # Register recent file
  8759. self.file_opened.emit("excellon", filename)
  8760. # GUI feedback
  8761. self.inform.emit('[success] %s: %s' %
  8762. (_("Opened"), filename))
  8763. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  8764. """
  8765. Opens a G-gcode file, parses it and creates a new object for
  8766. it in the program. Thread-safe.
  8767. :param filename: G-code file filename
  8768. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8769. :param force_parsing:
  8770. :param plot:
  8771. :return: None
  8772. """
  8773. App.log.debug("open_gcode()")
  8774. # How the object should be initialized
  8775. def obj_init(job_obj, app_obj_):
  8776. """
  8777. :param job_obj: the resulting object
  8778. :type app_obj_: App
  8779. """
  8780. assert isinstance(app_obj_, App), \
  8781. "Initializer expected App, got %s" % type(app_obj_)
  8782. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8783. try:
  8784. f = open(filename)
  8785. gcode = f.read()
  8786. f.close()
  8787. except IOError:
  8788. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8789. (_("Failed to open"), filename))
  8790. return "fail"
  8791. job_obj.gcode = gcode
  8792. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  8793. if gcode_ret == "fail":
  8794. self.inform.emit('[ERROR_NOTCL] %s' %
  8795. _("This is not GCODE"))
  8796. return "fail"
  8797. job_obj.create_geometry()
  8798. with self.proc_container.new(_("Opening G-Code.")):
  8799. # Object name
  8800. name = outname or filename.split('/')[-1].split('\\')[-1]
  8801. # New object creation and file processing
  8802. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8803. if obj_ret == 'fail':
  8804. self.inform.emit('[ERROR_NOTCL] %s' %
  8805. _("Failed to create CNCJob Object. Probable not a GCode file. "
  8806. "Try to load it from File menu.\n "
  8807. "Attempting to create a FlatCAM CNCJob Object from "
  8808. "G-Code file failed during processing"))
  8809. return "fail"
  8810. # Register recent file
  8811. self.file_opened.emit("cncjob", filename)
  8812. # GUI feedback
  8813. self.inform.emit('[success] %s: %s' %
  8814. (_("Opened"), filename))
  8815. def open_hpgl2(self, filename, outname=None):
  8816. """
  8817. Opens a HPGL2 file, parses it and creates a new object for
  8818. it in the program. Thread-safe.
  8819. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8820. :param filename: HPGL2 file filename
  8821. :return: None
  8822. """
  8823. filename = filename
  8824. # How the object should be initialized
  8825. def obj_init(geo_obj, app_obj):
  8826. assert isinstance(geo_obj, GeometryObject), \
  8827. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  8828. # Opening the file happens here
  8829. obj = HPGL2(self)
  8830. try:
  8831. HPGL2.parse_file(obj, filename)
  8832. except IOError:
  8833. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8834. return "fail"
  8835. except ParseError as err:
  8836. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8837. app_obj.log.error(str(err))
  8838. return "fail"
  8839. except Exception as e:
  8840. log.debug("App.open_hpgl2() --> %s" % str(e))
  8841. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8842. msg += traceback.format_exc()
  8843. app_obj.inform.emit(msg)
  8844. return "fail"
  8845. geo_obj.multigeo = True
  8846. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  8847. geo_obj.tools = deepcopy(obj.tools)
  8848. geo_obj.source_file = deepcopy(obj.source_file)
  8849. del obj
  8850. if not geo_obj.solid_geometry:
  8851. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8852. _("Object is not HPGL2 file or empty. Aborting object creation."))
  8853. return "fail"
  8854. App.log.debug("open_hpgl2()")
  8855. with self.proc_container.new(_("Opening HPGL2")) as proc:
  8856. # Object name
  8857. name = outname or filename.split('/')[-1].split('\\')[-1]
  8858. # # ## Object creation # ##
  8859. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  8860. if ret == 'fail':
  8861. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  8862. return 'fail'
  8863. # Register recent file
  8864. self.file_opened.emit("geometry", filename)
  8865. # GUI feedback
  8866. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8867. def open_script(self, filename, outname=None, silent=False):
  8868. """
  8869. Opens a Script file, parses it and creates a new object for
  8870. it in the program. Thread-safe.
  8871. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8872. :param filename: Script file filename
  8873. :return: None
  8874. """
  8875. App.log.debug("open_script()")
  8876. with self.proc_container.new(_("Opening TCL Script...")):
  8877. try:
  8878. with open(filename, "r") as opened_script:
  8879. script_content = opened_script.readlines()
  8880. script_content = ''.join(script_content)
  8881. if silent is False:
  8882. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8883. except Exception as e:
  8884. log.debug("App.open_script() -> %s" % str(e))
  8885. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  8886. return
  8887. # Object name
  8888. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8889. # New object creation and file processing
  8890. self.on_filenewscript(name=script_name, text=script_content)
  8891. # Register recent file
  8892. self.file_opened.emit("script", filename)
  8893. # GUI feedback
  8894. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8895. def open_config_file(self, filename, run_from_arg=None):
  8896. """
  8897. Loads a config file from the specified file.
  8898. :param filename: Name of the file from which to load.
  8899. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  8900. :return: None
  8901. """
  8902. App.log.debug("Opening config file: " + filename)
  8903. if run_from_arg:
  8904. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8905. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8906. _("Opening FlatCAM Config file.")),
  8907. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8908. color=QtGui.QColor("gray"))
  8909. # # add the tab if it was closed
  8910. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8911. # # first clear previous text in text editor (if any)
  8912. # self.ui.text_editor_tab.code_editor.clear()
  8913. #
  8914. # # Switch plot_area to CNCJob tab
  8915. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8916. # close the Code editor if already open
  8917. if self.toggle_codeeditor:
  8918. self.on_toggle_code_editor()
  8919. self.on_toggle_code_editor()
  8920. try:
  8921. if filename:
  8922. f = QtCore.QFile(filename)
  8923. if f.open(QtCore.QIODevice.ReadOnly):
  8924. stream = QtCore.QTextStream(f)
  8925. code_edited = stream.readAll()
  8926. self.text_editor_tab.code_editor.setPlainText(code_edited)
  8927. f.close()
  8928. except IOError:
  8929. App.log.error("Failed to open config file: %s" % filename)
  8930. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8931. (_("Failed to open config file"), filename))
  8932. return
  8933. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8934. """
  8935. Loads a project from the specified file.
  8936. 1) Loads and parses file
  8937. 2) Registers the file as recently opened.
  8938. 3) Calls on_file_new()
  8939. 4) Updates options
  8940. 5) Calls new_object() with the object's from_dict() as init method.
  8941. 6) Calls plot_all() if plot=True
  8942. :param filename: Name of the file from which to load.
  8943. :param run_from_arg: True if run for arguments
  8944. :param plot: If True plot all objects in the project
  8945. :param cli: Run from command line
  8946. :return: None
  8947. """
  8948. App.log.debug("Opening project: " + filename)
  8949. # block autosaving while a project is loaded
  8950. self.block_autosave = True
  8951. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8952. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8953. if cli is None:
  8954. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8955. if run_from_arg:
  8956. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8957. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8958. _("Opening FlatCAM Project file.")),
  8959. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8960. color=QtGui.QColor("gray"))
  8961. # Open and parse an uncompressed Project file
  8962. try:
  8963. f = open(filename, 'r')
  8964. except IOError:
  8965. App.log.error("Failed to open project file: %s" % filename)
  8966. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8967. (_("Failed to open project file"), filename))
  8968. return
  8969. try:
  8970. d = json.load(f, object_hook=dict2obj)
  8971. except Exception as e:
  8972. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8973. (filename, str(e)))
  8974. f.close()
  8975. # Open and parse a compressed Project file
  8976. try:
  8977. with lzma.open(filename) as f:
  8978. file_content = f.read().decode('utf-8')
  8979. d = json.loads(file_content, object_hook=dict2obj)
  8980. except Exception as e:
  8981. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8982. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8983. (_("Failed to open project file"), filename))
  8984. return
  8985. # Clear the current project
  8986. # # NOT THREAD SAFE # ##
  8987. if run_from_arg is True:
  8988. pass
  8989. elif cli is True:
  8990. self.delete_selection_shape()
  8991. else:
  8992. self.on_file_new()
  8993. # Project options
  8994. self.options.update(d['options'])
  8995. self.project_filename = filename
  8996. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8997. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8998. if cli is None:
  8999. self.set_screen_units(self.options["units"])
  9000. # Re create objects
  9001. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9002. for obj in d['objs']:
  9003. try:
  9004. def obj_init(obj_inst, app_inst):
  9005. obj_inst.from_dict(obj)
  9006. App.log.debug("Recreating from opened project an %s object: %s" %
  9007. (obj['kind'].capitalize(), obj['options']['name']))
  9008. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9009. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9010. if cli is None:
  9011. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9012. obj['kind'].upper(),
  9013. obj['options']['name']
  9014. )
  9015. )
  9016. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9017. except Exception as e:
  9018. print('App.open_project() --> ' + str(e))
  9019. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  9020. self.should_we_save = False
  9021. self.file_opened.emit("project", filename)
  9022. # restore autosaving after a project was loaded
  9023. self.block_autosave = False
  9024. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9025. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9026. if cli is None:
  9027. self.set_ui_title(name=self.project_filename)
  9028. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9029. def propagate_defaults(self, silent=False):
  9030. """
  9031. This method is used to set default values in classes. It's
  9032. an alternative to project options but allows the use
  9033. of values invisible to the user.
  9034. :param silent: No messages
  9035. :return: None
  9036. """
  9037. if silent is False:
  9038. self.log.debug("propagate_defaults()")
  9039. # Which objects to update the given parameters.
  9040. routes = {
  9041. "global_zdownrate": CNCjob,
  9042. "excellon_zeros": Excellon,
  9043. "excellon_format_upper_in": Excellon,
  9044. "excellon_format_lower_in": Excellon,
  9045. "excellon_format_upper_mm": Excellon,
  9046. "excellon_format_lower_mm": Excellon,
  9047. "excellon_units": Excellon,
  9048. "gerber_use_buffer_for_union": Gerber,
  9049. "geometry_multidepth": Geometry
  9050. }
  9051. for param in routes:
  9052. if param in routes[param].defaults:
  9053. try:
  9054. routes[param].defaults[param] = self.defaults[param]
  9055. if silent is False:
  9056. self.log.debug(" " + param + " OK")
  9057. except KeyError:
  9058. if silent is False:
  9059. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9060. else:
  9061. # Try extracting the name:
  9062. # classname_param here is param in the object
  9063. if param.find(routes[param].__name__.lower() + "_") == 0:
  9064. p = param[len(routes[param].__name__) + 1:]
  9065. if p in routes[param].defaults:
  9066. routes[param].defaults[p] = self.defaults[param]
  9067. if silent is False:
  9068. self.log.debug(" " + param + " OK!")
  9069. def plot_all(self, fit_view=True, use_thread=True):
  9070. """
  9071. Re-generates all plots from all objects.
  9072. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  9073. :param use_thread: if True will use threading for plotting the objects
  9074. :return: None
  9075. """
  9076. self.log.debug("Plot_all()")
  9077. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9078. for plot_obj in self.collection.get_list():
  9079. def worker_task(obj):
  9080. with self.proc_container.new("Plotting"):
  9081. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9082. if fit_view is True:
  9083. self.object_plotted.emit(obj)
  9084. if use_thread is True:
  9085. # Send to worker
  9086. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  9087. else:
  9088. worker_task(plot_obj)
  9089. def register_folder(self, filename):
  9090. """
  9091. Register the last folder used by the app to open something
  9092. :param filename: the last folder is extracted from the filename
  9093. :return: None
  9094. """
  9095. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9096. def register_save_folder(self, filename):
  9097. """
  9098. Register the last folder used by the app to save something
  9099. :param filename: the last folder is extracted from the filename
  9100. :return: None
  9101. """
  9102. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9103. # def set_progress_bar(self, percentage, text=""):
  9104. # """
  9105. # Set a progress bar to a value (percentage)
  9106. #
  9107. # :param percentage: Value set to the progressbar
  9108. # :param text: Not used
  9109. # :return: None
  9110. # """
  9111. # self.ui.progress_bar.setValue(int(percentage))
  9112. def setup_recent_items(self):
  9113. """
  9114. Setup a dictionary with the recent files accessed, organized by type
  9115. :return:
  9116. """
  9117. icons = {
  9118. "gerber": self.resource_location + "/flatcam_icon16.png",
  9119. "excellon": self.resource_location + "/drill16.png",
  9120. 'geometry': self.resource_location + "/geometry16.png",
  9121. "cncjob": self.resource_location + "/cnc16.png",
  9122. "script": self.resource_location + "/script_new24.png",
  9123. "document": self.resource_location + "/notes16_1.png",
  9124. "project": self.resource_location + "/project16.png",
  9125. "svg": self.resource_location + "/geometry16.png",
  9126. "dxf": self.resource_location + "/dxf16.png",
  9127. "pdf": self.resource_location + "/pdf32.png",
  9128. "image": self.resource_location + "/image16.png"
  9129. }
  9130. try:
  9131. image_opener = self.image_tool.import_image
  9132. except AttributeError:
  9133. image_opener = None
  9134. openers = {
  9135. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9136. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9137. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9138. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9139. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9140. "document": None,
  9141. 'project': self.open_project,
  9142. 'svg': self.import_svg,
  9143. 'dxf': self.import_dxf,
  9144. 'image': image_opener,
  9145. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9146. }
  9147. # Open recent file for files
  9148. try:
  9149. f = open(self.data_path + '/recent.json')
  9150. except IOError:
  9151. App.log.error("Failed to load recent item list.")
  9152. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  9153. return
  9154. try:
  9155. self.recent = json.load(f)
  9156. except json.errors.JSONDecodeError:
  9157. App.log.error("Failed to parse recent item list.")
  9158. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  9159. f.close()
  9160. return
  9161. f.close()
  9162. # Open recent file for projects
  9163. try:
  9164. fp = open(self.data_path + '/recent_projects.json')
  9165. except IOError:
  9166. App.log.error("Failed to load recent project item list.")
  9167. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  9168. return
  9169. try:
  9170. self.recent_projects = json.load(fp)
  9171. except json.errors.JSONDecodeError:
  9172. App.log.error("Failed to parse recent project item list.")
  9173. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  9174. fp.close()
  9175. return
  9176. fp.close()
  9177. # Closure needed to create callbacks in a loop.
  9178. # Otherwise late binding occurs.
  9179. def make_callback(func, fname):
  9180. def opener():
  9181. func(fname)
  9182. return opener
  9183. def reset_recent_files():
  9184. # Reset menu
  9185. self.ui.recent.clear()
  9186. self.recent = []
  9187. try:
  9188. ff = open(self.data_path + '/recent.json', 'w')
  9189. except IOError:
  9190. App.log.error("Failed to open recent items file for writing.")
  9191. return
  9192. json.dump(self.recent, ff)
  9193. def reset_recent_projects():
  9194. # Reset menu
  9195. self.ui.recent_projects.clear()
  9196. self.recent_projects = []
  9197. try:
  9198. frp = open(self.data_path + '/recent_projects.json', 'w')
  9199. except IOError:
  9200. App.log.error("Failed to open recent projects items file for writing.")
  9201. return
  9202. json.dump(self.recent, frp)
  9203. # Reset menu
  9204. self.ui.recent.clear()
  9205. self.ui.recent_projects.clear()
  9206. # Create menu items for projects
  9207. for recent in self.recent_projects:
  9208. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9209. if recent['kind'] == 'project':
  9210. try:
  9211. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9212. # Attach callback
  9213. o = make_callback(openers[recent["kind"]], recent['filename'])
  9214. action.triggered.connect(o)
  9215. self.ui.recent_projects.addAction(action)
  9216. except KeyError:
  9217. App.log.error("Unsupported file type: %s" % recent["kind"])
  9218. # Last action in Recent Files menu is one that Clear the content
  9219. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  9220. (_("Clear Recent projects")), self)
  9221. clear_action_proj.triggered.connect(reset_recent_projects)
  9222. self.ui.recent_projects.addSeparator()
  9223. self.ui.recent_projects.addAction(clear_action_proj)
  9224. # Create menu items for files
  9225. for recent in self.recent:
  9226. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9227. if recent['kind'] != 'project':
  9228. try:
  9229. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9230. # Attach callback
  9231. o = make_callback(openers[recent["kind"]], recent['filename'])
  9232. action.triggered.connect(o)
  9233. self.ui.recent.addAction(action)
  9234. except KeyError:
  9235. App.log.error("Unsupported file type: %s" % recent["kind"])
  9236. # Last action in Recent Files menu is one that Clear the content
  9237. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  9238. (_("Clear Recent files")), self)
  9239. clear_action.triggered.connect(reset_recent_files)
  9240. self.ui.recent.addSeparator()
  9241. self.ui.recent.addAction(clear_action)
  9242. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9243. # self.ui.menufilerecent.set_submenu(recent_menu)
  9244. # recent_menu.show_all()
  9245. # self.ui.recent.show()
  9246. self.log.debug("Recent items list has been populated.")
  9247. def setup_component_editor(self):
  9248. """
  9249. Default text for the Selected tab when is not taken by the Object UI.
  9250. :return:
  9251. """
  9252. # label = QtWidgets.QLabel("Choose an item from Project")
  9253. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9254. sel_title = QtWidgets.QTextEdit(
  9255. _('<b>Shortcut Key List</b>'))
  9256. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9257. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9258. f_settings = QSettings("Open Source", "FlatCAM")
  9259. if f_settings.contains("notebook_font_size"):
  9260. fsize = f_settings.value('notebook_font_size', type=int)
  9261. else:
  9262. fsize = 12
  9263. tsize = fsize + int(fsize / 2)
  9264. # selected_text = (_('''
  9265. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  9266. # </p>
  9267. #
  9268. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9269. # The normal flow when working in FlatCAM is the following:</span></p>
  9270. #
  9271. # <ol>
  9272. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  9273. # file into
  9274. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9275. # even dragging and dropping the files on the GUI.<br />
  9276. # <br />
  9277. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  9278. # drop of the
  9279. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9280. # &nbsp;</li>
  9281. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  9282. # and then
  9283. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9284. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9285. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9286. # <br />
  9287. # If the selection of the object is done on the canvas by single click instead, and the
  9288. # <strong>SELECTED TAB</strong>
  9289. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9290. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9291. # it even if it was out of focus.<br />
  9292. # <br />
  9293. # You can change the parameters in this screen and the flow direction is like this:<br />
  9294. # <br />
  9295. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  9296. # <strong> Geometry Object
  9297. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9298. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9299. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9300. # </ol>
  9301. #
  9302. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9303. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9304. # <strong>F3</strong>.</span></p>
  9305. #
  9306. # ''').format(fsize=fsize, tsize=tsize))
  9307. selected_text = '''
  9308. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9309. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9310. {s1}</span></p>
  9311. <ol>
  9312. <li><span style="font-size:{fsize}px">{s2}<br />
  9313. <br />
  9314. {s3}</span><br />
  9315. &nbsp;</li>
  9316. <li><span style="font-size:{fsize}px">{s4}<br />
  9317. &nbsp;</li>
  9318. <br />
  9319. <li><span style="font-size:{fsize}px">{s5}<br />
  9320. &nbsp;</li>
  9321. <br />
  9322. <li><span style="font-size:{fsize}px">{s6}<br />
  9323. <br />
  9324. {s7}</span></li>
  9325. </ol>
  9326. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9327. '''.format(
  9328. title=_("Selected Tab - Choose an Item from Project Tab"),
  9329. subtitle=_("Details"),
  9330. s1=_("The normal flow when working in FlatCAM is the following:"),
  9331. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9332. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9333. "files on the GUI."),
  9334. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9335. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9336. "actions offered within the app."),
  9337. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9338. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9339. "SELECTED TAB will be updated with the object properties according to its kind: "
  9340. "Gerber, Excellon, Geometry or CNCJob object."),
  9341. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9342. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9343. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9344. "the SELECTED TAB and populate it even if it was out of focus."),
  9345. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9346. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9347. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9348. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9349. "(again, done in SELECTED TAB) --> Save GCode."),
  9350. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9351. "or through its own key shortcut: <b>F3</b>."),
  9352. tsize=tsize,
  9353. fsize=fsize
  9354. )
  9355. sel_title.setText(selected_text)
  9356. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9357. self.ui.selected_scroll_area.setWidget(sel_title)
  9358. def setup_obj_classes(self):
  9359. """
  9360. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  9361. class.
  9362. :return: None
  9363. """
  9364. FlatCAMObj.app = self
  9365. ObjectCollection.app = self
  9366. Gerber.app = self
  9367. Excellon.app = self
  9368. Geometry.app = self
  9369. CNCjob.app = self
  9370. FCProcess.app = self
  9371. FCProcessContainer.app = self
  9372. OptionsGroupUI.app = self
  9373. def version_check(self):
  9374. """
  9375. Checks for the latest version of the program. Alerts the
  9376. user if theirs is outdated. This method is meant to be run
  9377. in a separate thread.
  9378. :return: None
  9379. """
  9380. self.log.debug("version_check()")
  9381. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9382. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  9383. App.version_url,
  9384. str(self.defaults['global_serial']),
  9385. str(self.version),
  9386. str(self.os),
  9387. urllib.parse.urlencode(self.defaults["global_stats"])
  9388. )
  9389. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  9390. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  9391. # urllib.parse.urlencode(self.defaults["global_stats"])
  9392. else:
  9393. # no_stats dict; just so it won't break things on website
  9394. no_ststs_dict = {}
  9395. no_ststs_dict["global_ststs"] = {}
  9396. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) +\
  9397. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9398. App.log.debug("Checking for updates @ %s" % full_url)
  9399. # ## Get the data
  9400. try:
  9401. f = urllib.request.urlopen(full_url)
  9402. except Exception:
  9403. # App.log.warning("Failed checking for latest version. Could not connect.")
  9404. self.log.warning("Failed checking for latest version. Could not connect.")
  9405. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  9406. return
  9407. try:
  9408. data = json.load(f)
  9409. except Exception as e:
  9410. App.log.error("Could not parse information about latest version.")
  9411. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  9412. App.log.debug("json.load(): %s" % str(e))
  9413. f.close()
  9414. return
  9415. f.close()
  9416. # ## Latest version?
  9417. if self.version >= data["version"]:
  9418. App.log.debug("FlatCAM is up to date!")
  9419. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  9420. return
  9421. App.log.debug("Newer version available.")
  9422. self.message.emit(
  9423. _("Newer Version Available"),
  9424. '%s<br><br>><b>%s</b><br>%s' % (
  9425. _("There is a newer version of FlatCAM available for download:"),
  9426. str(data["name"]),
  9427. str(data["message"])
  9428. ),
  9429. _("info")
  9430. )
  9431. def on_plotcanvas_setup(self, container=None):
  9432. """
  9433. This is doing the setup for the plot area (canvas).
  9434. :param container: QT Widget where to install the canvas
  9435. :return: None
  9436. """
  9437. if container:
  9438. plot_container = container
  9439. else:
  9440. plot_container = self.ui.right_layout
  9441. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  9442. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  9443. self.is_legacy = True
  9444. self.defaults["global_graphic_engine"] = "2D"
  9445. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9446. else:
  9447. try:
  9448. self.plotcanvas = PlotCanvas(plot_container, self)
  9449. except Exception as er:
  9450. msg_txt = traceback.format_exc()
  9451. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  9452. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  9453. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  9454. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  9455. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  9456. msg += msg_txt
  9457. self.inform.emit(msg)
  9458. return 'fail'
  9459. # So it can receive key presses
  9460. self.plotcanvas.native.setFocus()
  9461. if self.is_legacy is False:
  9462. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  9463. # Set the mouse button for panning
  9464. self.plotcanvas.view.camera.pan_button_setting = pan_button
  9465. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9466. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9467. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9468. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  9469. # Keys over plot enabled
  9470. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9471. if self.defaults['global_cursor_type'] == 'small':
  9472. self.app_cursor = self.plotcanvas.new_cursor()
  9473. else:
  9474. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9475. if self.ui.grid_snap_btn.isChecked():
  9476. self.app_cursor.enabled = True
  9477. else:
  9478. self.app_cursor.enabled = False
  9479. if self.is_legacy is False:
  9480. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9481. else:
  9482. # will use the default Matplotlib axes
  9483. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9484. def on_zoom_fit(self, event):
  9485. """
  9486. Callback for zoom-fit request. This can be either from the corresponding
  9487. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9488. with axes limits from the geometry bounds of all objects.
  9489. :param event: Ignored.
  9490. :return: None
  9491. """
  9492. if self.is_legacy is False:
  9493. self.plotcanvas.fit_view()
  9494. else:
  9495. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9496. width = xmax - xmin
  9497. height = ymax - ymin
  9498. xmin -= 0.05 * width
  9499. xmax += 0.05 * width
  9500. ymin -= 0.05 * height
  9501. ymax += 0.05 * height
  9502. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9503. def on_zoom_in(self):
  9504. """
  9505. Callback for zoom-in request.
  9506. :return:
  9507. """
  9508. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9509. def on_zoom_out(self):
  9510. """
  9511. Callback for zoom-out request.
  9512. :return:
  9513. """
  9514. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9515. def disable_all_plots(self):
  9516. self.report_usage("disable_all_plots()")
  9517. self.disable_plots(self.collection.get_list())
  9518. self.inform.emit('[success] %s' %
  9519. _("All plots disabled."))
  9520. def disable_other_plots(self):
  9521. self.report_usage("disable_other_plots()")
  9522. self.disable_plots(self.collection.get_non_selected())
  9523. self.inform.emit('[success] %s' %
  9524. _("All non selected plots disabled."))
  9525. def enable_all_plots(self):
  9526. self.report_usage("enable_all_plots()")
  9527. self.enable_plots(self.collection.get_list())
  9528. self.inform.emit('[success] %s' %
  9529. _("All plots enabled."))
  9530. def on_enable_sel_plots(self):
  9531. log.debug("App.on_enable_sel_plot()")
  9532. object_list = self.collection.get_selected()
  9533. self.enable_plots(objects=object_list)
  9534. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  9535. def on_disable_sel_plots(self):
  9536. log.debug("App.on_disable_sel_plot()")
  9537. # self.inform.emit(_("Disabling plots ..."))
  9538. object_list = self.collection.get_selected()
  9539. self.disable_plots(objects=object_list)
  9540. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  9541. def enable_plots(self, objects):
  9542. """
  9543. Enable plots
  9544. :param objects: list of Objects to be enabled
  9545. :return:
  9546. """
  9547. log.debug("Enabling plots ...")
  9548. # self.inform.emit(_("Working ..."))
  9549. for obj in objects:
  9550. if obj.options['plot'] is False:
  9551. obj.options.set_change_callback(lambda x: None)
  9552. obj.options['plot'] = True
  9553. try:
  9554. # only the Gerber obj has on_plot_cb_click() method
  9555. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  9556. # disable this cb while disconnected,
  9557. # in case the operation takes time the user is not allowed to change it
  9558. obj.ui.plot_cb.setDisabled(True)
  9559. except AttributeError:
  9560. pass
  9561. obj.set_form_item("plot")
  9562. try:
  9563. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  9564. obj.ui.plot_cb.setDisabled(False)
  9565. except AttributeError:
  9566. pass
  9567. obj.options.set_change_callback(obj.on_options_change)
  9568. def worker_task(objs):
  9569. with self.proc_container.new(_("Enabling plots ...")):
  9570. for plot_obj in objs:
  9571. # obj.options['plot'] = True
  9572. if isinstance(plot_obj, CNCJobObject):
  9573. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9574. else:
  9575. plot_obj.plot(visible=True)
  9576. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9577. # self.plots_updated.emit()
  9578. def disable_plots(self, objects):
  9579. """
  9580. Disables plots
  9581. :param objects: list of Objects to be disabled
  9582. :return:
  9583. """
  9584. # if no objects selected then do nothing
  9585. if not self.collection.get_selected():
  9586. return
  9587. log.debug("Disabling plots ...")
  9588. # self.inform.emit(_("Working ..."))
  9589. for obj in objects:
  9590. if obj.options['plot'] is True:
  9591. obj.options.set_change_callback(lambda x: None)
  9592. obj.options['plot'] = False
  9593. try:
  9594. # only the Gerber obj has on_plot_cb_click() method
  9595. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  9596. obj.ui.plot_cb.setDisabled(True)
  9597. except AttributeError:
  9598. pass
  9599. obj.set_form_item("plot")
  9600. try:
  9601. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  9602. obj.ui.plot_cb.setDisabled(False)
  9603. except AttributeError:
  9604. pass
  9605. obj.options.set_change_callback(obj.on_options_change)
  9606. try:
  9607. self.delete_selection_shape()
  9608. except Exception as e:
  9609. log.debug("App.disable_plots() --> %s" % str(e))
  9610. # self.plots_updated.emit()
  9611. def worker_task(objs):
  9612. with self.proc_container.new(_("Disabling plots ...")):
  9613. for plot_obj in objs:
  9614. # obj.options['plot'] = True
  9615. if isinstance(plot_obj, CNCJobObject):
  9616. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9617. else:
  9618. plot_obj.plot(visible=False)
  9619. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9620. def toggle_plots(self, objects):
  9621. """
  9622. Toggle plots visibility
  9623. :param objects: list of Objects for which to be toggled the visibility
  9624. :return: None
  9625. """
  9626. # if no objects selected then do nothing
  9627. if not self.collection.get_selected():
  9628. return
  9629. log.debug("Toggling plots ...")
  9630. self.inform.emit(_("Working ..."))
  9631. for obj in objects:
  9632. if obj.options['plot'] is False:
  9633. obj.options['plot'] = True
  9634. else:
  9635. obj.options['plot'] = False
  9636. self.plots_updated.emit()
  9637. def clear_plots(self):
  9638. """
  9639. Clear the plots
  9640. :return: None
  9641. """
  9642. objects = self.collection.get_list()
  9643. for obj in objects:
  9644. obj.clear(obj == objects[-1])
  9645. # Clear pool to free memory
  9646. self.clear_pool()
  9647. def on_set_color_action_triggered(self):
  9648. """
  9649. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  9650. :return:
  9651. """
  9652. new_color = self.defaults['gerber_plot_fill']
  9653. clicked_action = self.sender()
  9654. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  9655. act_name = clicked_action.text()
  9656. sel_obj_list = self.collection.get_selected()
  9657. if not sel_obj_list:
  9658. return
  9659. # a default value, I just chose this one
  9660. alpha_level = 'BF'
  9661. for sel_obj in sel_obj_list:
  9662. if sel_obj.kind == 'excellon':
  9663. alpha_level = str(hex(
  9664. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  9665. elif sel_obj.kind == 'gerber':
  9666. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  9667. elif sel_obj.kind == 'geometry':
  9668. alpha_level = 'FF'
  9669. else:
  9670. log.debug(
  9671. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  9672. continue
  9673. sel_obj.alpha_level = alpha_level
  9674. if act_name == _('Red'):
  9675. new_color = '#FF0000' + alpha_level
  9676. if act_name == _('Blue'):
  9677. new_color = '#0000FF' + alpha_level
  9678. if act_name == _('Yellow'):
  9679. new_color = '#FFDF00' + alpha_level
  9680. if act_name == _('Green'):
  9681. new_color = '#00FF00' + alpha_level
  9682. if act_name == _('Purple'):
  9683. new_color = '#FF00FF' + alpha_level
  9684. if act_name == _('Brown'):
  9685. new_color = '#A52A2A' + alpha_level
  9686. if act_name == _('White'):
  9687. new_color = '#FFFFFF' + alpha_level
  9688. if act_name == _('Black'):
  9689. new_color = '#000000' + alpha_level
  9690. if act_name == _('Custom'):
  9691. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  9692. c_dialog = QtWidgets.QColorDialog()
  9693. plot_fill_color = c_dialog.getColor(initial=new_color)
  9694. if plot_fill_color.isValid() is False:
  9695. return
  9696. new_color = str(plot_fill_color.name()) + alpha_level
  9697. if act_name == _("Default"):
  9698. for sel_obj in sel_obj_list:
  9699. if sel_obj.kind == 'excellon':
  9700. new_color = self.defaults['excellon_plot_fill']
  9701. new_line_color = self.defaults['excellon_plot_line']
  9702. elif sel_obj.kind == 'gerber':
  9703. new_color = self.defaults['gerber_plot_fill']
  9704. new_line_color = self.defaults['gerber_plot_line']
  9705. elif sel_obj.kind == 'geometry':
  9706. new_color = self.defaults['geometry_plot_line']
  9707. new_line_color = self.defaults['geometry_plot_line']
  9708. else:
  9709. log.debug(
  9710. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  9711. continue
  9712. sel_obj.fill_color = new_color
  9713. sel_obj.outline_color = new_line_color
  9714. sel_obj.shapes.redraw(
  9715. update_colors=(new_color, new_line_color)
  9716. )
  9717. return
  9718. if act_name == _("Opacity"):
  9719. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  9720. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  9721. if ok_button:
  9722. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  9723. for sel_obj in sel_obj_list:
  9724. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  9725. sel_obj.shapes.redraw(
  9726. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  9727. )
  9728. return
  9729. new_line_color = color_variant(new_color[:7], 0.7)
  9730. if act_name == _("White"):
  9731. new_line_color = color_variant("#dedede", 0.7)
  9732. for sel_obj in sel_obj_list:
  9733. sel_obj.fill_color = new_color
  9734. sel_obj.outline_color = new_line_color
  9735. sel_obj.shapes.redraw(
  9736. update_colors=(new_color, new_line_color)
  9737. )
  9738. def on_grid_snap_triggered(self, state):
  9739. """
  9740. :param state: A parameter with the state of the grid, boolean
  9741. :return:
  9742. """
  9743. if state:
  9744. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  9745. else:
  9746. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  9747. self.ui.snap_infobar_label.clicked_state = state
  9748. def on_grid_icon_snap_clicked(self):
  9749. """
  9750. Slot called by clicking a GUI element, in this case a FCLabel
  9751. :return:
  9752. """
  9753. if isinstance(self.sender(), FCLabel):
  9754. self.ui.grid_snap_btn.trigger()
  9755. def generate_cnc_job(self, objects):
  9756. """
  9757. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  9758. :param objects: Selected objects in the Project Tab
  9759. :return:
  9760. """
  9761. self.report_usage("generate_cnc_job()")
  9762. # for obj in objects:
  9763. # obj.generatecncjob()
  9764. for obj in objects:
  9765. obj.on_generatecnc_button_click()
  9766. def save_project(self, filename, quit_action=False, silent=False):
  9767. """
  9768. Saves the current project to the specified file.
  9769. :param filename: Name of the file in which to save.
  9770. :type filename: str
  9771. :param quit_action: if the project saving will be followed by an app quit; boolean
  9772. :param silent: if True will not display status messages
  9773. :return: None
  9774. """
  9775. self.log.debug("save_project()")
  9776. self.save_in_progress = True
  9777. with self.proc_container.new(_("Saving FlatCAM Project")):
  9778. # Capture the latest changes
  9779. # Current object
  9780. try:
  9781. current_object = self.collection.get_active()
  9782. if current_object:
  9783. current_object.read_form()
  9784. except Exception as e:
  9785. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  9786. pass
  9787. # Serialize the whole project
  9788. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9789. "options": self.options,
  9790. "version": self.version}
  9791. if self.defaults["global_save_compressed"] is True:
  9792. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9793. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9794. # # Write
  9795. f.write(g)
  9796. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  9797. else:
  9798. # Open file
  9799. try:
  9800. f = open(filename, 'w')
  9801. except IOError:
  9802. App.log.error("Failed to open file for saving: %s", filename)
  9803. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  9804. return
  9805. # Write
  9806. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9807. f.close()
  9808. # verification of the saved project
  9809. # Open and parse
  9810. try:
  9811. saved_f = open(filename, 'r')
  9812. except IOError:
  9813. if silent is False:
  9814. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9815. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  9816. return
  9817. try:
  9818. saved_d = json.load(saved_f, object_hook=dict2obj)
  9819. except Exception:
  9820. if silent is False:
  9821. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9822. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  9823. f.close()
  9824. return
  9825. saved_f.close()
  9826. if silent is False:
  9827. if 'version' in saved_d:
  9828. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  9829. else:
  9830. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9831. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  9832. tb_settings = QSettings("Open Source", "FlatCAM")
  9833. lock_state = self.ui.lock_action.isChecked()
  9834. tb_settings.setValue('toolbar_lock', lock_state)
  9835. # This will write the setting to the platform specific storage.
  9836. del tb_settings
  9837. # if quit:
  9838. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9839. # t.start()
  9840. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9841. def start_delayed_quit(self, delay, filename, should_quit=None):
  9842. """
  9843. :param delay: period of checking if project file size is more than zero; in seconds
  9844. :param filename: the name of the project file to be checked periodically for size more than zero
  9845. :param should_quit: if the task finished will be followed by an app quit; boolean
  9846. :return:
  9847. """
  9848. to_quit = should_quit
  9849. self.save_timer = QtCore.QTimer()
  9850. self.save_timer.setInterval(delay)
  9851. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9852. self.save_timer.start()
  9853. def check_project_file_size(self, filename, should_quit=None):
  9854. """
  9855. :param filename: the name of the project file to be checked periodically for size more than zero
  9856. :param should_quit: will quit the app if True; boolean
  9857. :return:
  9858. """
  9859. try:
  9860. if os.stat(filename).st_size > 0:
  9861. self.save_in_progress = False
  9862. self.save_timer.stop()
  9863. if should_quit:
  9864. self.app_quit.emit()
  9865. except Exception:
  9866. traceback.print_exc()
  9867. def save_project_auto(self):
  9868. """
  9869. Called periodically to save the project.
  9870. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  9871. # progress.
  9872. :return:
  9873. """
  9874. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  9875. self.on_file_saveproject()
  9876. def save_project_auto_update(self):
  9877. """
  9878. Update the auto save time interval value.
  9879. :return:
  9880. """
  9881. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  9882. try:
  9883. if self.autosave_timer.isActive():
  9884. self.autosave_timer.stop()
  9885. except Exception:
  9886. pass
  9887. if self.defaults['global_autosave'] is True:
  9888. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  9889. self.autosave_timer.start()
  9890. def on_plotarea_tab_closed(self, tab_idx):
  9891. """
  9892. :param tab_idx: Index of the Tab from the plotarea that was closed
  9893. :return:
  9894. """
  9895. widget = self.ui.plot_tab_area.widget(tab_idx)
  9896. if widget is not None:
  9897. widget.deleteLater()
  9898. self.ui.plot_tab_area.removeTab(tab_idx)
  9899. def on_options_app2project(self):
  9900. """
  9901. Callback for Options->Transfer Options->App=>Project. Copies options
  9902. from application defaults to project defaults.
  9903. :return: None
  9904. """
  9905. self.report_usage("on_options_app2project")
  9906. self.defaults_read_form()
  9907. self.options.update(self.defaults)
  9908. # self.options_write_form()
  9909. def toggle_shell(self):
  9910. """
  9911. Toggle shell: if is visible close it, if it is closed then open it
  9912. :return: None
  9913. """
  9914. self.report_usage("toggle_shell()")
  9915. if self.ui.shell_dock.isVisible():
  9916. self.ui.shell_dock.hide()
  9917. self.plotcanvas.native.setFocus()
  9918. else:
  9919. self.ui.shell_dock.show()
  9920. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  9921. # self.shell._edit.setFocus()
  9922. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  9923. # HACK - simulate a mouse click - alternative
  9924. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  9925. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  9926. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  9927. # no_km)
  9928. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  9929. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  9930. # no_km)
  9931. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  9932. def on_toggle_shell_from_settings(self, state):
  9933. """
  9934. Toggle shell: if is visible close it, if it is closed then open it
  9935. :return: None
  9936. """
  9937. self.report_usage("on_toggle_shell_from_settings()")
  9938. if state is True:
  9939. if not self.ui.shell_dock.isVisible():
  9940. self.ui.shell_dock.show()
  9941. else:
  9942. if self.ui.shell_dock.isVisible():
  9943. self.ui.shell_dock.hide()
  9944. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  9945. """
  9946. Shows a message on the FlatCAM Shell
  9947. :param msg: Message to display.
  9948. :param show: Opens the shell.
  9949. :param error: Shows the message as an error.
  9950. :param warning: Shows the message as an warning.
  9951. :param success: Shows the message as an success.
  9952. :param selected: Indicate that something was selected on canvas
  9953. :return: None
  9954. """
  9955. if show:
  9956. self.ui.shell_dock.show()
  9957. try:
  9958. if error:
  9959. self.shell.append_error(msg + "\n")
  9960. elif warning:
  9961. self.shell.append_warning(msg + "\n")
  9962. elif success:
  9963. self.shell.append_success(msg + "\n")
  9964. elif selected:
  9965. self.shell.append_selected(msg + "\n")
  9966. else:
  9967. self.shell.append_output(msg + "\n")
  9968. except AttributeError:
  9969. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  9970. class ArgsThread(QtCore.QObject):
  9971. open_signal = pyqtSignal(list)
  9972. start = pyqtSignal()
  9973. if sys.platform == 'win32':
  9974. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9975. else:
  9976. address = ('/tmp/testipc', 'AF_UNIX')
  9977. def __init__(self):
  9978. super(ArgsThread, self).__init__()
  9979. self.listener = None
  9980. self.start.connect(self.run)
  9981. def my_loop(self, address):
  9982. try:
  9983. self.listener = Listener(*address)
  9984. while True:
  9985. conn = self.listener.accept()
  9986. self.serve(conn)
  9987. except socket.error:
  9988. conn = Client(*address)
  9989. conn.send(sys.argv)
  9990. conn.send('close')
  9991. # close the current instance only if there are args
  9992. if len(sys.argv) > 1:
  9993. try:
  9994. self.listener.close()
  9995. except Exception:
  9996. pass
  9997. sys.exit()
  9998. def serve(self, conn):
  9999. while True:
  10000. msg = conn.recv()
  10001. if msg == 'close':
  10002. break
  10003. self.open_signal.emit(msg)
  10004. conn.close()
  10005. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10006. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10007. @pyqtSlot()
  10008. def run(self):
  10009. self.my_loop(self.address)
  10010. # end of file