FlatCAMApp.py 574 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import webbrowser
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import lzma
  16. import threading
  17. import shutil
  18. import stat
  19. from stat import S_IREAD, S_IRGRP, S_IROTH
  20. import ctypes
  21. # import tkinter as tk
  22. # from PyQt5 import QtPrintSupport
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.graphics import renderPM
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. from contextlib import contextmanager
  30. import gc
  31. from xml.dom.minidom import parseString as parse_xml_string
  32. from multiprocessing.connection import Listener, Client
  33. from multiprocessing import Pool
  34. import socket
  35. from array import array
  36. import vispy.scene as scene
  37. # #######################################
  38. # # Imports part of FlatCAM ##
  39. # #######################################
  40. from ObjectCollection import *
  41. from FlatCAMObj import *
  42. from camlib import to_dict, dict2obj, ET, ParseError
  43. from flatcamGUI.PlotCanvas import *
  44. from flatcamGUI.PlotCanvasLegacy import *
  45. from flatcamGUI.FlatCAMGUI import *
  46. from FlatCAMCommon import LoudDict, BookmarkManager, ToolsDB, color_variant
  47. from FlatCAMPostProc import load_preprocessors
  48. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  49. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  50. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  51. from flatcamEditors.FlatCAMTextEditor import TextEditor
  52. from flatcamParsers.ParseHPGL2 import HPGL2
  53. from FlatCAMProcess import *
  54. from FlatCAMWorkerStack import WorkerStack
  55. # from flatcamGUI.VisPyVisuals import Color
  56. from vispy.gloo.util import _screenshot
  57. from vispy.io import write_png
  58. from flatcamTools import *
  59. import tclCommands
  60. import gettext
  61. import FlatCAMTranslation as fcTranslate
  62. import builtins
  63. if sys.platform == 'win32':
  64. import winreg
  65. fcTranslate.apply_language('strings')
  66. if '_' not in builtins.__dict__:
  67. _ = gettext.gettext
  68. class App(QtCore.QObject):
  69. # ########################################
  70. # # App ###
  71. # ########################################
  72. """
  73. The main application class. The constructor starts the GUI.
  74. """
  75. # Get Cmd Line Options
  76. cmd_line_shellfile = ''
  77. cmd_line_shellvar = ''
  78. cmd_line_headless = None
  79. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  80. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  81. "FlatCam.py --headless=1"
  82. try:
  83. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  84. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  85. "shellvar=",
  86. "headless=",
  87. "multiprocessing-fork="])
  88. except getopt.GetoptError:
  89. print(cmd_line_help)
  90. sys.exit(2)
  91. for opt, arg in cmd_line_options:
  92. if opt == '-h':
  93. print(cmd_line_help)
  94. sys.exit()
  95. elif opt == '--shellfile':
  96. cmd_line_shellfile = arg
  97. elif opt == '--shellvar':
  98. cmd_line_shellvar = arg
  99. elif opt == '--headless':
  100. try:
  101. cmd_line_headless = eval(arg)
  102. except NameError:
  103. pass
  104. # ## Logging ###
  105. log = logging.getLogger('base')
  106. log.setLevel(logging.DEBUG)
  107. # log.setLevel(logging.WARNING)
  108. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  109. handler = logging.StreamHandler()
  110. handler.setFormatter(formatter)
  111. log.addHandler(handler)
  112. # ##########################################################################
  113. # ################## Version and VERSION DATE ##############################
  114. # ##########################################################################
  115. version = 8.992
  116. version_date = "2020/01/20"
  117. beta = True
  118. engine = '3D'
  119. # current date now
  120. date = str(datetime.today()).rpartition('.')[0]
  121. date = ''.join(c for c in date if c not in ':-')
  122. date = date.replace(' ', '_')
  123. # URL for update checks and statistics
  124. version_url = "http://flatcam.org/version"
  125. # App URL
  126. app_url = "http://flatcam.org"
  127. # Manual URL
  128. manual_url = "http://flatcam.org/manual/index.html"
  129. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  130. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  131. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  132. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  133. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  134. # this variable will hold the project status
  135. # if True it will mean that the project was modified and not saved
  136. should_we_save = False
  137. # flag is True if saving action has been triggered
  138. save_in_progress = False
  139. # ###########################################################################
  140. # ############################# Signals ################################
  141. # ###########################################################################
  142. # Inform the user
  143. # Handled by:
  144. # * App.info() --> Print on the status bar
  145. inform = QtCore.pyqtSignal(str)
  146. app_quit = QtCore.pyqtSignal()
  147. # General purpose background task
  148. worker_task = QtCore.pyqtSignal(dict)
  149. # File opened
  150. # Handled by:
  151. # * register_folder()
  152. # * register_recent()
  153. # Note: Setting the parameters to unicode does not seem
  154. # to have an effect. Then are received as Qstring
  155. # anyway.
  156. # File type and filename
  157. file_opened = QtCore.pyqtSignal(str, str)
  158. # File type and filename
  159. file_saved = QtCore.pyqtSignal(str, str)
  160. # Percentage of progress
  161. progress = QtCore.pyqtSignal(int)
  162. plots_updated = QtCore.pyqtSignal()
  163. # Emitted by new_object() and passes the new object as argument, plot flag.
  164. # on_object_created() adds the object to the collection, plots on appropriate flag
  165. # and emits new_object_available.
  166. object_created = QtCore.pyqtSignal(object, bool, bool)
  167. # Emitted when a object has been changed (like scaled, mirrored)
  168. object_changed = QtCore.pyqtSignal(object)
  169. # Emitted after object has been plotted.
  170. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  171. object_plotted = QtCore.pyqtSignal(object)
  172. # Emitted when a new object has been added or deleted from/to the collection
  173. object_status_changed = QtCore.pyqtSignal(object, str, str)
  174. message = QtCore.pyqtSignal(str, str, str)
  175. # Emmited when shell command is finished(one command only)
  176. shell_command_finished = QtCore.pyqtSignal(object)
  177. # Emitted when multiprocess pool has been recreated
  178. pool_recreated = QtCore.pyqtSignal(object)
  179. # Emitted when an unhandled exception happens
  180. # in the worker task.
  181. thread_exception = QtCore.pyqtSignal(object)
  182. # used to signal that there are arguments for the app
  183. args_at_startup = QtCore.pyqtSignal(list)
  184. # a reusable signal to replot a list of objects
  185. # should be disconnected after use so it can be reused
  186. replot_signal = pyqtSignal(list)
  187. # signal emitted when jumping
  188. jump_signal = pyqtSignal(tuple)
  189. # signal emitted when jumping
  190. locate_signal = pyqtSignal(tuple, str)
  191. # close app signal
  192. close_app_signal = pyqtSignal()
  193. def __init__(self, user_defaults=True):
  194. """
  195. Starts the application.
  196. :return: app
  197. :rtype: App
  198. """
  199. App.log.info("FlatCAM Starting...")
  200. self.main_thread = QtWidgets.QApplication.instance().thread()
  201. # #########################################################################
  202. # Setup the listening thread for another instance launching with args #####
  203. # #########################################################################
  204. if sys.platform == 'win32' or sys.platform == 'linux':
  205. # make sure the thread is stored by using a self. otherwise it's garbage collected
  206. self.th = QtCore.QThread()
  207. self.th.start(priority=QtCore.QThread.LowestPriority)
  208. self.new_launch = ArgsThread()
  209. self.new_launch.open_signal[list].connect(self.on_startup_args)
  210. self.new_launch.moveToThread(self.th)
  211. self.new_launch.start.emit()
  212. # ############################################################################
  213. # # ################# OS-specific ############################################
  214. # ############################################################################
  215. portable = False
  216. # Folder for user settings.
  217. if sys.platform == 'win32':
  218. from win32com.shell import shell, shellcon
  219. if platform.architecture()[0] == '32bit':
  220. App.log.debug("Win32!")
  221. else:
  222. App.log.debug("Win64!")
  223. # #########################################################################
  224. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  225. # #########################################################################
  226. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  227. try:
  228. with open(config_file, 'r'):
  229. pass
  230. except FileNotFoundError:
  231. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  232. try:
  233. with open(config_file, 'r') as f:
  234. try:
  235. for line in f:
  236. param = str(line).replace('\n', '').rpartition('=')
  237. if param[0] == 'portable':
  238. try:
  239. portable = eval(param[2])
  240. except NameError:
  241. portable = False
  242. if param[0] == 'headless':
  243. if param[2].lower() == 'true':
  244. self.cmd_line_headless = 1
  245. else:
  246. self.cmd_line_headless = None
  247. except Exception as e:
  248. log.debug('App.__init__() -->%s' % str(e))
  249. return
  250. except FileNotFoundError as e:
  251. log.debug(str(e))
  252. pass
  253. if portable is False:
  254. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  255. else:
  256. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  257. self.os = 'windows'
  258. else: # Linux/Unix/MacOS
  259. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  260. self.os = 'unix'
  261. # ##########################################################################
  262. # ################## Setup folders and files ###############################
  263. # ##########################################################################
  264. if not os.path.exists(self.data_path):
  265. os.makedirs(self.data_path)
  266. App.log.debug('Created data folder: ' + self.data_path)
  267. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  268. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  269. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  270. if not os.path.exists(self.preprocessorpaths):
  271. os.makedirs(self.preprocessorpaths)
  272. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  273. # create geo_tools_db.FlatDB file if there is none
  274. try:
  275. f = open(self.data_path + '/geo_tools_db.FlatDB')
  276. f.close()
  277. except IOError:
  278. App.log.debug('Creating empty geo_tool_db.FlatDB')
  279. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  280. json.dump({}, f)
  281. f.close()
  282. # create fctool_tools_db.FlatDB file if there is none
  283. try:
  284. f = open(self.data_path + '/fctool_tools_db.FlatDB')
  285. f.close()
  286. except IOError:
  287. App.log.debug('Creating empty fctool_tool_db.FlatDB')
  288. f = open(self.data_path + '/fctool_tools_db.FlatDB', 'w')
  289. json.dump({}, f)
  290. f.close()
  291. # create current_defaults.FlatConfig file if there is none
  292. try:
  293. f = open(self.data_path + '/current_defaults.FlatConfig')
  294. f.close()
  295. except IOError:
  296. App.log.debug('Creating empty current_defaults.FlatConfig')
  297. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  298. json.dump({}, f)
  299. f.close()
  300. # create factory_defaults.FlatConfig file if there is none
  301. try:
  302. f = open(self.data_path + '/factory_defaults.FlatConfig')
  303. f.close()
  304. except IOError:
  305. App.log.debug('Creating empty factory_defaults.FlatConfig')
  306. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  307. json.dump({}, f)
  308. f.close()
  309. # create a recent files json file if there is none
  310. try:
  311. f = open(self.data_path + '/recent.json')
  312. f.close()
  313. except IOError:
  314. App.log.debug('Creating empty recent.json')
  315. f = open(self.data_path + '/recent.json', 'w')
  316. json.dump([], f)
  317. f.close()
  318. # create a recent projects json file if there is none
  319. try:
  320. fp = open(self.data_path + '/recent_projects.json')
  321. fp.close()
  322. except IOError:
  323. App.log.debug('Creating empty recent_projects.json')
  324. fp = open(self.data_path + '/recent_projects.json', 'w')
  325. json.dump([], fp)
  326. fp.close()
  327. # Application directory. CHDIR to it. Otherwise, trying to load
  328. # GUI icons will fail as their path is relative.
  329. # This will fail under cx_freeze ...
  330. self.app_home = os.path.dirname(os.path.realpath(__file__))
  331. App.log.debug("Application path is " + self.app_home)
  332. App.log.debug("Started in " + os.getcwd())
  333. # cx_freeze workaround
  334. if os.path.isfile(self.app_home):
  335. self.app_home = os.path.dirname(self.app_home)
  336. os.chdir(self.app_home)
  337. # #################################################################################
  338. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  339. # #################################################################################
  340. self.defaults = LoudDict()
  341. self.defaults.update({
  342. # Global APP Preferences
  343. "decimals_inch": 4,
  344. "decimals_metric": 4,
  345. "version": self.version,
  346. "first_run": True,
  347. "units": "MM",
  348. "global_serial": 0,
  349. "global_stats": dict(),
  350. "global_tabs_detachable": True,
  351. "global_jump_ref": 'abs',
  352. "global_locate_pt": 'bl',
  353. "global_tpdf_tmargin": 15.0,
  354. "global_tpdf_bmargin": 10.0,
  355. "global_tpdf_lmargin": 20.0,
  356. "global_tpdf_rmargin": 20.0,
  357. # General
  358. "global_graphic_engine": '3D',
  359. "global_app_level": 'b',
  360. "global_portable": False,
  361. "global_language": 'English',
  362. "global_version_check": True,
  363. "global_send_stats": True,
  364. "global_pan_button": '2',
  365. "global_mselect_key": 'Control',
  366. "global_project_at_startup": False,
  367. "global_systray_icon": True,
  368. "global_project_autohide": True,
  369. "global_toggle_tooltips": True,
  370. "global_worker_number": 2,
  371. "global_tolerance": 0.005,
  372. "global_open_style": True,
  373. "global_delete_confirmation": True,
  374. "global_compression_level": 3,
  375. "global_save_compressed": True,
  376. "global_machinist_setting": False,
  377. # Global GUI Preferences
  378. "global_gridx": 1.0,
  379. "global_gridy": 1.0,
  380. "global_snap_max": 0.05,
  381. "global_workspace": False,
  382. "global_workspaceT": "A4",
  383. "global_workspace_orientation": 'p',
  384. "global_grid_context_menu": {
  385. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  386. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  387. },
  388. "global_sel_fill": '#a5a5ffbf',
  389. "global_sel_line": '#0000ffbf',
  390. "global_alt_sel_fill": '#BBF268BF',
  391. "global_alt_sel_line": '#006E20BF',
  392. "global_draw_color": '#FF0000',
  393. "global_sel_draw_color": '#0000FF',
  394. "global_proj_item_color": '#000000',
  395. "global_proj_item_dis_color": '#b7b7cb',
  396. "global_activity_icon": 'Ball green',
  397. "global_toolbar_view": 511,
  398. "global_background_timeout": 300000, # Default value is 5 minutes
  399. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  400. # (python trace only for unknown errors),
  401. # 1 = show trace(show trace always),
  402. # 2 = (For the future).
  403. # Persistence
  404. "global_last_folder": None,
  405. "global_last_save_folder": None,
  406. # Default window geometry
  407. "global_def_win_x": 100,
  408. "global_def_win_y": 100,
  409. "global_def_win_w": 1024,
  410. "global_def_win_h": 650,
  411. "global_def_notebook_width": 1,
  412. # Constants...
  413. "global_defaults_save_period_ms": 20000, # Time between default saves.
  414. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  415. "global_shell_at_startup": False, # Show the shell at startup.
  416. "global_recent_limit": 10, # Max. items in recent list.
  417. "global_bookmarks": dict(),
  418. "global_bookmarks_limit": 10,
  419. "fit_key": 'V',
  420. "zoom_out_key": '-',
  421. "zoom_in_key": '=',
  422. "grid_toggle_key": 'G',
  423. "global_zoom_ratio": 1.5,
  424. "global_point_clipboard_format": "(%.4f, %.4f)",
  425. "global_zdownrate": None,
  426. # General GUI Settings
  427. "global_theme": 'white',
  428. "global_gray_icons": False,
  429. "global_hover": False,
  430. "global_selection_shape": True,
  431. "global_layout": "compact",
  432. "global_cursor_type": "small",
  433. "global_cursor_size": 20,
  434. "global_cursor_width": 2,
  435. "global_cursor_color": '#FF0000',
  436. "global_cursor_color_enabled": True,
  437. # Gerber General
  438. "gerber_plot": True,
  439. "gerber_solid": True,
  440. "gerber_multicolored": False,
  441. "gerber_circle_steps": 64,
  442. "gerber_use_buffer_for_union": True,
  443. "gerber_clean_apertures": True,
  444. "gerber_extra_buffering": True,
  445. "gerber_plot_fill": '#BBF268BF',
  446. "gerber_plot_line": '#006E20BF',
  447. "gerber_def_units": 'IN',
  448. "gerber_def_zeros": 'L',
  449. "gerber_save_filters": "Gerber File (*.gbr);;Gerber File (*.bot);;Gerber File (*.bsm);;"
  450. "Gerber File (*.cmp);;Gerber File (*.crc);;Gerber File (*.crs);;"
  451. "Gerber File (*.gb0);;Gerber File (*.gb1);;Gerber File (*.gb2);;"
  452. "Gerber File (*.gb3);;Gerber File (*.gb4);;Gerber File (*.gb5);;"
  453. "Gerber File (*.gb6);;Gerber File (*.gb7);;Gerber File (*.gb8);;"
  454. "Gerber File (*.gb9);;Gerber File (*.gbd);;Gerber File (*.gbl);;"
  455. "Gerber File (*.gbo);;Gerber File (*.gbp);;Gerber File (*.gbs);;"
  456. "Gerber File (*.gdo);;Gerber File (*.ger);;Gerber File (*.gko);;"
  457. "Gerber File (*.gm1);;Gerber File (*.gm2);;Gerber File (*.gm3);;"
  458. "Gerber File (*.grb);;Gerber File (*.gtl);;Gerber File (*.gto);;"
  459. "Gerber File (*.gtp);;Gerber File (*.gts);;Gerber File (*.ly15);;"
  460. "Gerber File (*.ly2);;Gerber File (*.mil);;Gerber File (*.pho);;"
  461. "Gerber File (*.plc);;Gerber File (*.pls);;Gerber File (*.smb);;"
  462. "Gerber File (*.smt);;Gerber File (*.sol);;Gerber File (*.spb);;"
  463. "Gerber File (*.spt);;Gerber File (*.ssb);;Gerber File (*.sst);;"
  464. "Gerber File (*.stc);;Gerber File (*.sts);;Gerber File (*.top);;"
  465. "Gerber File (*.tsm);;Gerber File (*.art)"
  466. "All Files (*.*)",
  467. # Gerber Options
  468. "gerber_isotooldia": 0.1,
  469. "gerber_isopasses": 1,
  470. "gerber_isooverlap": 10,
  471. "gerber_milling_type": "cl",
  472. "gerber_combine_passes": False,
  473. "gerber_iso_scope": 'all',
  474. "gerber_noncoppermargin": 0.1,
  475. "gerber_noncopperrounded": False,
  476. "gerber_bboxmargin": 0.1,
  477. "gerber_bboxrounded": False,
  478. # Gerber Advanced Options
  479. "gerber_aperture_display": False,
  480. "gerber_aperture_scale_factor": 1.0,
  481. "gerber_aperture_buffer_factor": 0.0,
  482. "gerber_follow": False,
  483. "gerber_tool_type": 'circular',
  484. "gerber_vtipdia": 0.1,
  485. "gerber_vtipangle": 30,
  486. "gerber_vcutz": -0.05,
  487. "gerber_iso_type": "full",
  488. "gerber_buffering": "full",
  489. "gerber_simplification": False,
  490. "gerber_simp_tolerance": 0.0005,
  491. # Gerber Export
  492. "gerber_exp_units": 'IN',
  493. "gerber_exp_integer": 2,
  494. "gerber_exp_decimals": 4,
  495. "gerber_exp_zeros": 'L',
  496. # Gerber Editor
  497. "gerber_editor_sel_limit": 30,
  498. "gerber_editor_newcode": 10,
  499. "gerber_editor_newsize": 0.8,
  500. "gerber_editor_newtype": 'C',
  501. "gerber_editor_newdim": "0.5, 0.5",
  502. "gerber_editor_array_size": 5,
  503. "gerber_editor_lin_axis": 'X',
  504. "gerber_editor_lin_pitch": 0.1,
  505. "gerber_editor_lin_angle": 0.0,
  506. "gerber_editor_circ_dir": 'CW',
  507. "gerber_editor_circ_angle": 0.0,
  508. "gerber_editor_scale_f": 1.0,
  509. "gerber_editor_buff_f": 0.1,
  510. "gerber_editor_ma_low": 0.0,
  511. "gerber_editor_ma_high": 1.0,
  512. # Excellon General
  513. "excellon_plot": True,
  514. "excellon_solid": True,
  515. "excellon_format_upper_in": 2,
  516. "excellon_format_lower_in": 4,
  517. "excellon_format_upper_mm": 3,
  518. "excellon_format_lower_mm": 3,
  519. "excellon_zeros": "L",
  520. "excellon_units": "INCH",
  521. "excellon_update": True,
  522. "excellon_optimization_type": 'B',
  523. "excellon_search_time": 3,
  524. "excellon_save_filters": "Excellon File (*.txt);;Excellon File (*.drd);;Excellon File (*.drl);;"
  525. "Excellon File (*.exc);;Excellon File (*.ncd);;Excellon File (*.tap);;"
  526. "Excellon File (*.xln);;All Files (*.*)",
  527. "excellon_plot_fill": '#C40000BF',
  528. "excellon_plot_line": '#750000BF',
  529. # Excellon Options
  530. "excellon_drillz": -1.7,
  531. "excellon_travelz": 2,
  532. "excellon_endz": 0.5,
  533. "excellon_feedrate": 300,
  534. "excellon_spindlespeed": 0,
  535. "excellon_dwell": False,
  536. "excellon_dwelltime": 1,
  537. "excellon_toolchange": False,
  538. "excellon_toolchangez": 15,
  539. "excellon_ppname_e": 'default',
  540. "excellon_tooldia": 0.8,
  541. "excellon_slot_tooldia": 1.8,
  542. "excellon_gcode_type": "drills",
  543. # Excellon Advanced Options
  544. "excellon_offset": 0.0,
  545. "excellon_toolchangexy": "0.0, 0.0",
  546. "excellon_startz": None,
  547. "excellon_feedrate_rapid": 1500,
  548. "excellon_z_pdepth": -0.02,
  549. "excellon_feedrate_probe": 75,
  550. "excellon_spindledir": 'CW',
  551. "excellon_f_plunge": False,
  552. "excellon_f_retract": False,
  553. # Excellon Export
  554. "excellon_exp_units": 'INCH',
  555. "excellon_exp_format": 'ndec',
  556. "excellon_exp_integer": 2,
  557. "excellon_exp_decimals": 4,
  558. "excellon_exp_zeros": 'LZ',
  559. "excellon_exp_slot_type": 'routing',
  560. # Excellon Editor
  561. "excellon_editor_sel_limit": 30,
  562. "excellon_editor_newdia": 1.0,
  563. "excellon_editor_array_size": 5,
  564. "excellon_editor_lin_dir": 'X',
  565. "excellon_editor_lin_pitch": 2.54,
  566. "excellon_editor_lin_angle": 0.0,
  567. "excellon_editor_circ_dir": 'CW',
  568. "excellon_editor_circ_angle": 12,
  569. # Excellon Slots
  570. "excellon_editor_slot_direction": 'X',
  571. "excellon_editor_slot_angle": 0.0,
  572. "excellon_editor_slot_length": 5.0,
  573. # Excellon Slot Array
  574. "excellon_editor_slot_array_size": 5,
  575. "excellon_editor_slot_lin_dir": 'X',
  576. "excellon_editor_slot_lin_pitch": 2.54,
  577. "excellon_editor_slot_lin_angle": 0.0,
  578. "excellon_editor_slot_circ_dir": 'CW',
  579. "excellon_editor_slot_circ_angle": 0.0,
  580. # Geometry General
  581. "geometry_plot": True,
  582. "geometry_circle_steps": 64,
  583. "geometry_cnctooldia": "2.4",
  584. "geometry_plot_line": "#FF0000",
  585. # Geometry Options
  586. "geometry_cutz": -2.4,
  587. "geometry_vtipdia": 0.1,
  588. "geometry_vtipangle": 30,
  589. "geometry_multidepth": False,
  590. "geometry_depthperpass": 0.8,
  591. "geometry_travelz": 2,
  592. "geometry_toolchange": False,
  593. "geometry_toolchangez": 15.0,
  594. "geometry_endz": 15.0,
  595. "geometry_feedrate": 120,
  596. "geometry_feedrate_z": 60,
  597. "geometry_spindlespeed": 0,
  598. "geometry_dwell": False,
  599. "geometry_dwelltime": 1,
  600. "geometry_ppname_g": 'default',
  601. # Geometry Advanced Options
  602. "geometry_toolchangexy": "0.0, 0.0",
  603. "geometry_startz": None,
  604. "geometry_feedrate_rapid": 1500,
  605. "geometry_extracut": False,
  606. "geometry_extracut_length": 0.1,
  607. "geometry_z_pdepth": -0.02,
  608. "geometry_f_plunge": False,
  609. "geometry_spindledir": 'CW',
  610. "geometry_feedrate_probe": 75,
  611. "geometry_segx": 0.0,
  612. "geometry_segy": 0.0,
  613. # Geometry Editor
  614. "geometry_editor_sel_limit": 30,
  615. "geometry_editor_milling_type": "cl",
  616. # CNC Job General
  617. "cncjob_plot": True,
  618. "cncjob_plot_kind": 'all',
  619. "cncjob_annotation": True,
  620. "cncjob_tooldia": 1.0,
  621. "cncjob_coords_type": "G90",
  622. "cncjob_coords_decimals": 4,
  623. "cncjob_fr_decimals": 2,
  624. "cncjob_steps_per_circle": 64,
  625. "cncjob_footer": False,
  626. "cncjob_line_ending": False,
  627. "cncjob_save_filters": "G-Code Files (*.nc);;G-Code Files (*.din);;G-Code Files (*.dnc);;"
  628. "G-Code Files (*.ecs);;G-Code Files (*.eia);;G-Code Files (*.fan);;"
  629. "G-Code Files (*.fgc);;G-Code Files (*.fnc);;G-Code Files (*.gc);;"
  630. "G-Code Files (*.gcd);;G-Code Files (*.gcode);;G-Code Files (*.h);;"
  631. "G-Code Files (*.hnc);;G-Code Files (*.i);;G-Code Files (*.min);;"
  632. "G-Code Files (*.mpf);;G-Code Files (*.mpr);;G-Code Files (*.cnc);;"
  633. "G-Code Files (*.ncc);;G-Code Files (*.ncg);;G-Code Files (*.ncp);;"
  634. "G-Code Files (*.ngc);;G-Code Files (*.out);;G-Code Files (*.ply);;"
  635. "G-Code Files (*.sbp);;G-Code Files (*.tap);;G-Code Files (*.xpi);;"
  636. "All Files (*.*)",
  637. "cncjob_plot_line": '#4650BDFF',
  638. "cncjob_plot_fill": '#5E6CFFFF',
  639. "cncjob_travel_line": '#B5AB3A4C',
  640. "cncjob_travel_fill": '#F0E24D4C',
  641. # CNC Job Options
  642. "cncjob_prepend": "",
  643. "cncjob_append": "",
  644. # CNC Job Advanced Options
  645. "cncjob_toolchange_macro": "",
  646. "cncjob_toolchange_macro_enable": False,
  647. "cncjob_annotation_fontsize": 9,
  648. "cncjob_annotation_fontcolor": '#990000',
  649. # NCC Tool
  650. "tools_ncctools": "1.0, 0.5",
  651. "tools_nccorder": 'rev',
  652. "tools_nccoverlap": 40,
  653. "tools_nccmargin": 1.0,
  654. "tools_nccmethod": "seed",
  655. "tools_nccconnect": True,
  656. "tools_ncccontour": True,
  657. "tools_nccrest": False,
  658. "tools_ncc_offset_choice": False,
  659. "tools_ncc_offset_value": 0.0000,
  660. "tools_nccref": 'itself',
  661. "tools_ncc_plotting": 'normal',
  662. "tools_nccmilling_type": 'cl',
  663. "tools_ncctool_type": 'V',
  664. "tools_ncccutz": -0.05,
  665. "tools_ncctipdia": 0.1,
  666. "tools_ncctipangle": 30,
  667. "tools_nccnewdia": 1.0,
  668. # Cutout Tool
  669. "tools_cutouttooldia": 2.4,
  670. "tools_cutoutkind": "single",
  671. "tools_cutoutmargin": 0.1,
  672. "tools_cutout_z": -1.8,
  673. "tools_cutout_depthperpass": 0.6,
  674. "tools_cutout_mdepth": True,
  675. "tools_cutoutgapsize": 4,
  676. "tools_gaps_ff": "4",
  677. "tools_cutout_convexshape": False,
  678. # Paint Tool
  679. "tools_painttooldia": 0.3,
  680. "tools_paintorder": 'rev',
  681. "tools_paintoverlap": 20,
  682. "tools_paintmargin": 0.0,
  683. "tools_paintmethod": "seed",
  684. "tools_selectmethod": "all",
  685. "tools_pathconnect": True,
  686. "tools_paintcontour": True,
  687. "tools_paint_plotting": 'normal',
  688. # 2-Sided Tool
  689. "tools_2sided_mirror_axis": "X",
  690. "tools_2sided_axis_loc": "point",
  691. "tools_2sided_drilldia": 3.125,
  692. # Film Tool
  693. "tools_film_type": 'neg',
  694. "tools_film_boundary": 1.0,
  695. "tools_film_scale_stroke": 0,
  696. "tools_film_color": '#000000',
  697. "tools_film_scale_cb": False,
  698. "tools_film_scale_x_entry": 1.0,
  699. "tools_film_scale_y_entry": 1.0,
  700. "tools_film_skew_cb": False,
  701. "tools_film_skew_x_entry": 0.0,
  702. "tools_film_skew_y_entry": 0.0,
  703. "tools_film_skew_ref_radio": 'bottomleft',
  704. "tools_film_mirror_cb": False,
  705. "tools_film_mirror_axis_radio": 'none',
  706. "tools_film_file_type_radio": 'svg',
  707. "tools_film_orientation": 'p',
  708. "tools_film_pagesize": 'A4',
  709. # Panel Tool
  710. "tools_panelize_spacing_columns": 0,
  711. "tools_panelize_spacing_rows": 0,
  712. "tools_panelize_columns": 1,
  713. "tools_panelize_rows": 1,
  714. "tools_panelize_constrain": False,
  715. "tools_panelize_constrainx": 200.0,
  716. "tools_panelize_constrainy": 290.0,
  717. "tools_panelize_panel_type": 'gerber',
  718. # Calculators Tool
  719. "tools_calc_vshape_tip_dia": 0.2,
  720. "tools_calc_vshape_tip_angle": 30,
  721. "tools_calc_vshape_cut_z": 0.05,
  722. "tools_calc_electro_length": 10.0,
  723. "tools_calc_electro_width": 10.0,
  724. "tools_calc_electro_cdensity": 13.0,
  725. "tools_calc_electro_growth": 10.0,
  726. # Transform Tool
  727. "tools_transform_rotate": 90,
  728. "tools_transform_skew_x": 0.0,
  729. "tools_transform_skew_y": 0.0,
  730. "tools_transform_scale_x": 1.0,
  731. "tools_transform_scale_y": 1.0,
  732. "tools_transform_scale_link": True,
  733. "tools_transform_scale_reference": True,
  734. "tools_transform_offset_x": 0.0,
  735. "tools_transform_offset_y": 0.0,
  736. "tools_transform_mirror_reference": False,
  737. "tools_transform_mirror_point": (0, 0),
  738. "tools_transform_buffer_dis": 0.0,
  739. "tools_transform_buffer_factor": 100.0,
  740. "tools_transform_buffer_corner": True,
  741. # SolderPaste Tool
  742. "tools_solderpaste_tools": "1.0, 0.3",
  743. "tools_solderpaste_new": 0.3,
  744. "tools_solderpaste_z_start": 0.05,
  745. "tools_solderpaste_z_dispense": 0.1,
  746. "tools_solderpaste_z_stop": 0.05,
  747. "tools_solderpaste_z_travel": 0.1,
  748. "tools_solderpaste_z_toolchange": 1.0,
  749. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  750. "tools_solderpaste_frxy": 150,
  751. "tools_solderpaste_frz": 150,
  752. "tools_solderpaste_frz_dispense": 1.0,
  753. "tools_solderpaste_speedfwd": 300,
  754. "tools_solderpaste_dwellfwd": 1,
  755. "tools_solderpaste_speedrev": 200,
  756. "tools_solderpaste_dwellrev": 1,
  757. "tools_solderpaste_pp": 'Paste_1',
  758. # Subtract Tool
  759. "tools_sub_close_paths": True,
  760. # ###################################################################################
  761. # ################################ TOOLS 2 ##########################################
  762. # ###################################################################################
  763. # Optimal Tool
  764. "tools_opt_precision": 4,
  765. # Check Rules Tool
  766. "tools_cr_trace_size": True,
  767. "tools_cr_trace_size_val": 0.25,
  768. "tools_cr_c2c": True,
  769. "tools_cr_c2c_val": 0.25,
  770. "tools_cr_c2o": True,
  771. "tools_cr_c2o_val": 1.0,
  772. "tools_cr_s2s": True,
  773. "tools_cr_s2s_val": 0.25,
  774. "tools_cr_s2sm": True,
  775. "tools_cr_s2sm_val": 0.25,
  776. "tools_cr_s2o": True,
  777. "tools_cr_s2o_val": 1.0,
  778. "tools_cr_sm2sm": True,
  779. "tools_cr_sm2sm_val": 0.25,
  780. "tools_cr_ri": True,
  781. "tools_cr_ri_val": 0.3,
  782. "tools_cr_h2h": True,
  783. "tools_cr_h2h_val": 0.3,
  784. "tools_cr_dh": True,
  785. "tools_cr_dh_val": 0.3,
  786. # QRCode Tool
  787. "tools_qrcode_version": 1,
  788. "tools_qrcode_error": 'L',
  789. "tools_qrcode_box_size": 3,
  790. "tools_qrcode_border_size": 4,
  791. "tools_qrcode_qrdata": '',
  792. "tools_qrcode_polarity": 'pos',
  793. "tools_qrcode_rounded": 's',
  794. "tools_qrcode_fill_color": '#000000',
  795. "tools_qrcode_back_color": '#FFFFFF',
  796. "tools_qrcode_sel_limit": 330,
  797. # Copper Thieving Tool
  798. "tools_copper_thieving_clearance": 0.25,
  799. "tools_copper_thieving_margin": 1.0,
  800. "tools_copper_thieving_reference": 'itself',
  801. "tools_copper_thieving_box_type": 'rect',
  802. "tools_copper_thieving_circle_steps": 64,
  803. "tools_copper_thieving_fill_type": 'solid',
  804. "tools_copper_thieving_dots_dia": 1.0,
  805. "tools_copper_thieving_dots_spacing": 2.0,
  806. "tools_copper_thieving_squares_size": 1.0,
  807. "tools_copper_thieving_squares_spacing": 2.0,
  808. "tools_copper_thieving_lines_size": 0.25,
  809. "tools_copper_thieving_lines_spacing": 2.0,
  810. "tools_copper_thieving_rb_margin": 1.0,
  811. "tools_copper_thieving_rb_thickness": 1.0,
  812. "tools_copper_thieving_mask_clearance": 0.0,
  813. # Fiducials Tool
  814. "tools_fiducials_dia": 1.0,
  815. "tools_fiducials_margin": 1.0,
  816. "tools_fiducials_mode": 'auto',
  817. "tools_fiducials_second_pos": 'up',
  818. "tools_fiducials_type": 'circular',
  819. "tools_fiducials_line_thickness": 0.25,
  820. # Calibration Tool
  821. "tools_cal_calsource": 'object',
  822. "tools_cal_travelz": 2.0,
  823. "tools_cal_verz": 0.1,
  824. "tools_cal_zeroz": False,
  825. "tools_cal_toolchangez": 15,
  826. "tools_cal_toolchange_xy": '',
  827. "tools_cal_sec_point": 'tl',
  828. # Drills Extraction Tool
  829. "tools_edrills_hole_type": 'fixed',
  830. "tools_edrills_hole_fixed_dia": 0.5,
  831. "tools_edrills_hole_prop_factor": 80.0,
  832. "tools_edrills_circular_ring": 0.2,
  833. "tools_edrills_oblong_ring": 0.2,
  834. "tools_edrills_square_ring": 0.2,
  835. "tools_edrills_rectangular_ring": 0.2,
  836. "tools_edrills_others_ring": 0.2,
  837. "tools_edrills_circular": True,
  838. "tools_edrills_oblong": False,
  839. "tools_edrills_square": False,
  840. "tools_edrills_rectangular": False,
  841. "tools_edrills_others": False,
  842. # Align Objects Tool
  843. "tools_align_objects_align_type": 'sp',
  844. # Utilities
  845. # file associations
  846. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  847. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  848. 'ncg, ncp, ngc, out, ply, rol, sbp, tap, xpi',
  849. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, gb0, gb1, gb2, gb3, gb4, gb5, gb6, gb7, gb8, gb9, gbd, '
  850. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  851. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  852. # Keyword list
  853. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  854. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  855. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  856. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  857. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwelltime, '
  858. 'extracut_length, '
  859. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  860. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  861. 'minoffset, name, offset, opt_type, order, outname, overlap, '
  862. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  863. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  864. 'toolchange_xy, toolchangez, '
  865. 'tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  866. 'z_move',
  867. "script_autocompleter": True,
  868. "script_text": "",
  869. "script_plot": True,
  870. "script_source_file": "",
  871. "document_autocompleter": False,
  872. "document_text": "",
  873. "document_plot": True,
  874. "document_source_file": "",
  875. "document_font_color": '#000000',
  876. "document_sel_color": '#0055ff',
  877. "document_font_size": 6,
  878. "document_tab_size": 80,
  879. })
  880. # ############################################################
  881. # ############### Load defaults from file ####################
  882. # ############################################################
  883. self.old_defaults_found = False
  884. if user_defaults:
  885. self.load_defaults(filename='current_defaults')
  886. if self.defaults['units'] == 'MM':
  887. self.decimals = int(self.defaults['decimals_metric'])
  888. else:
  889. self.decimals = int(self.defaults['decimals_inch'])
  890. if self.defaults["global_gray_icons"] is False:
  891. self.resource_location = 'share'
  892. else:
  893. self.resource_location = 'share/dark_resources'
  894. self.current_units = self.defaults['units']
  895. # store here the current self.defaults so it can be restored if Preferences changes are cancelled
  896. self.current_defaults = dict()
  897. self.current_defaults.update(self.defaults)
  898. # ##########################################################################
  899. # ##################### SETUP OBJECT CLASSES ###############################
  900. # ##########################################################################
  901. self.setup_obj_classes()
  902. # ##########################################################################
  903. # ##################### CREATE MULTIPROCESSING POOL ########################
  904. # ##########################################################################
  905. self.pool = Pool()
  906. # ##########################################################################
  907. # ################## Setting the Splash Screen #############################
  908. # ##########################################################################
  909. splash_settings = QSettings("Open Source", "FlatCAM")
  910. if splash_settings.contains("splash_screen"):
  911. show_splash = splash_settings.value("splash_screen")
  912. else:
  913. splash_settings.setValue('splash_screen', 1)
  914. # This will write the setting to the platform specific storage.
  915. del splash_settings
  916. show_splash = 1
  917. if show_splash and self.cmd_line_headless != 1:
  918. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  919. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  920. # self.splash.setMask(splash_pix.mask())
  921. # move splashscreen to the current monitor
  922. desktop = QtWidgets.QApplication.desktop()
  923. screen = desktop.screenNumber(QtGui.QCursor.pos())
  924. current_screen_center = desktop.availableGeometry(screen).center()
  925. self.splash.move(current_screen_center - self.splash.rect().center())
  926. self.splash.show()
  927. self.splash.showMessage(_("FlatCAM is initializing ..."),
  928. alignment=Qt.AlignBottom | Qt.AlignLeft,
  929. color=QtGui.QColor("gray"))
  930. else:
  931. show_splash = 0
  932. # #############################################################################
  933. # ##################### Initialize GUI ########################################
  934. # #############################################################################
  935. # FlatCAM colors used in plotting
  936. self.FC_light_green = '#BBF268BF'
  937. self.FC_dark_green = '#006E20BF'
  938. self.FC_light_blue = '#a5a5ffbf'
  939. self.FC_dark_blue = '#0000ffbf'
  940. QtCore.QObject.__init__(self)
  941. self.ui = FlatCAMGUI(self)
  942. self.on_grid_snap_triggered(state=True)
  943. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  944. if theme_settings.contains("theme"):
  945. theme = theme_settings.value('theme', type=str)
  946. else:
  947. theme = 'white'
  948. if self.defaults["global_cursor_color_enabled"]:
  949. self.cursor_color_3D = self.defaults["global_cursor_color"]
  950. else:
  951. if theme == 'white':
  952. self.cursor_color_3D = 'black'
  953. else:
  954. self.cursor_color_3D = 'gray'
  955. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  956. self.ui.final_save.connect(self.final_save)
  957. # restore the toolbar view
  958. self.restore_toolbar_view()
  959. # restore the GUI geometry
  960. self.restore_main_win_geom()
  961. # set FlatCAM units in the Status bar
  962. self.set_screen_units(self.defaults['units'])
  963. # #############################################################################
  964. # ######################## UPDATE PREFERENCES GUI FORMS #######################
  965. # #############################################################################
  966. # when adding entries here read the comments in the method found bellow named:
  967. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  968. self.defaults_form_fields = {
  969. # General App
  970. "decimals_inch": self.ui.general_defaults_form.general_app_group.precision_inch_entry,
  971. "decimals_metric": self.ui.general_defaults_form.general_app_group.precision_metric_entry,
  972. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  973. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  974. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  975. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  976. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  977. "global_systray_icon": self.ui.general_defaults_form.general_app_group.systray_cb,
  978. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  979. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  980. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  981. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  982. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  983. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  984. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  985. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  986. "global_tpdf_tmargin": self.ui.general_defaults_form.general_app_group.tmargin_entry,
  987. "global_tpdf_bmargin": self.ui.general_defaults_form.general_app_group.bmargin_entry,
  988. "global_tpdf_lmargin": self.ui.general_defaults_form.general_app_group.lmargin_entry,
  989. "global_tpdf_rmargin": self.ui.general_defaults_form.general_app_group.rmargin_entry,
  990. # General GUI Preferences
  991. "global_theme": self.ui.general_defaults_form.general_gui_group.theme_radio,
  992. "global_gray_icons": self.ui.general_defaults_form.general_gui_group.gray_icons_cb,
  993. "global_layout": self.ui.general_defaults_form.general_gui_group.layout_combo,
  994. "global_hover": self.ui.general_defaults_form.general_gui_group.hover_cb,
  995. "global_selection_shape": self.ui.general_defaults_form.general_gui_group.selection_cb,
  996. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  997. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  998. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  999. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  1000. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  1001. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  1002. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  1003. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  1004. "global_project_autohide": self.ui.general_defaults_form.general_gui_group.project_autohide_cb,
  1005. # General GUI Settings
  1006. "global_gridx": self.ui.general_defaults_form.general_app_set_group.gridx_entry,
  1007. "global_gridy": self.ui.general_defaults_form.general_app_set_group.gridy_entry,
  1008. "global_snap_max": self.ui.general_defaults_form.general_app_set_group.snap_max_dist_entry,
  1009. "global_workspace": self.ui.general_defaults_form.general_app_set_group.workspace_cb,
  1010. "global_workspaceT": self.ui.general_defaults_form.general_app_set_group.wk_cb,
  1011. "global_workspace_orientation": self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio,
  1012. "global_cursor_type": self.ui.general_defaults_form.general_app_set_group.cursor_radio,
  1013. "global_cursor_size": self.ui.general_defaults_form.general_app_set_group.cursor_size_entry,
  1014. "global_cursor_width": self.ui.general_defaults_form.general_app_set_group.cursor_width_entry,
  1015. "global_cursor_color_enabled": self.ui.general_defaults_form.general_app_set_group.mouse_cursor_color_cb,
  1016. "global_cursor_color": self.ui.general_defaults_form.general_app_set_group.mouse_cursor_entry,
  1017. "global_pan_button": self.ui.general_defaults_form.general_app_set_group.pan_button_radio,
  1018. "global_mselect_key": self.ui.general_defaults_form.general_app_set_group.mselect_radio,
  1019. "global_delete_confirmation": self.ui.general_defaults_form.general_app_set_group.delete_conf_cb,
  1020. "global_open_style": self.ui.general_defaults_form.general_app_set_group.open_style_cb,
  1021. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_set_group.toggle_tooltips_cb,
  1022. "global_machinist_setting": self.ui.general_defaults_form.general_app_set_group.machinist_cb,
  1023. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_set_group.bm_limit_spinner,
  1024. "global_activity_icon": self.ui.general_defaults_form.general_app_set_group.activity_combo,
  1025. # Gerber General
  1026. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  1027. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  1028. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  1029. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  1030. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  1031. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  1032. "gerber_clean_apertures": self.ui.gerber_defaults_form.gerber_gen_group.gerber_clean_cb,
  1033. "gerber_extra_buffering": self.ui.gerber_defaults_form.gerber_gen_group.gerber_extra_buffering,
  1034. "gerber_plot_fill": self.ui.gerber_defaults_form.gerber_gen_group.pf_color_entry,
  1035. "gerber_plot_line": self.ui.gerber_defaults_form.gerber_gen_group.pl_color_entry,
  1036. # Gerber Options
  1037. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  1038. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  1039. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  1040. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  1041. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  1042. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  1043. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  1044. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  1045. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  1046. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  1047. # Gerber Advanced Options
  1048. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  1049. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  1050. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  1051. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  1052. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  1053. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  1054. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  1055. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  1056. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  1057. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  1058. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  1059. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  1060. # Gerber Export
  1061. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  1062. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  1063. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  1064. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  1065. # Gerber Editor
  1066. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  1067. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  1068. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  1069. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  1070. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  1071. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  1072. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  1073. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  1074. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  1075. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  1076. "gerber_editor_circ_angle":
  1077. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  1078. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  1079. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  1080. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  1081. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  1082. # Excellon General
  1083. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  1084. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  1085. "excellon_format_upper_in":
  1086. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  1087. "excellon_format_lower_in":
  1088. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  1089. "excellon_format_upper_mm":
  1090. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1091. "excellon_format_lower_mm":
  1092. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1093. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  1094. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  1095. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  1096. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  1097. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  1098. "excellon_plot_fill": self.ui.excellon_defaults_form.excellon_gen_group.fill_color_entry,
  1099. "excellon_plot_line": self.ui.excellon_defaults_form.excellon_gen_group.line_color_entry,
  1100. # Excellon Options
  1101. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  1102. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  1103. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  1104. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  1105. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  1106. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  1107. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  1108. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  1109. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  1110. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  1111. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  1112. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  1113. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  1114. # Excellon Advanced Options
  1115. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  1116. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  1117. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  1118. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1119. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  1120. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  1121. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  1122. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  1123. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  1124. # Excellon Export
  1125. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  1126. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  1127. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  1128. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  1129. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  1130. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  1131. # Excellon Editor
  1132. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  1133. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  1134. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  1135. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  1136. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  1137. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  1138. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  1139. "excellon_editor_circ_angle":
  1140. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  1141. # Excellon Slots
  1142. "excellon_editor_slot_direction":
  1143. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  1144. "excellon_editor_slot_angle":
  1145. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  1146. "excellon_editor_slot_length":
  1147. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  1148. # Excellon Slots
  1149. "excellon_editor_slot_array_size":
  1150. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  1151. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  1152. "excellon_editor_slot_lin_pitch":
  1153. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  1154. "excellon_editor_slot_lin_angle":
  1155. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  1156. "excellon_editor_slot_circ_dir":
  1157. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  1158. "excellon_editor_slot_circ_angle":
  1159. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  1160. # Geometry General
  1161. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  1162. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  1163. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  1164. "geometry_plot_line": self.ui.geometry_defaults_form.geometry_gen_group.line_color_entry,
  1165. # Geometry Options
  1166. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  1167. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  1168. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  1169. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  1170. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  1171. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  1172. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  1173. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  1174. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  1175. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  1176. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  1177. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  1178. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  1179. # Geometry Advanced Options
  1180. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  1181. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  1182. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1183. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  1184. "geometry_extracut_length": self.ui.geometry_defaults_form.geometry_adv_opt_group.e_cut_entry,
  1185. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  1186. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  1187. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  1188. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  1189. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  1190. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  1191. # Geometry Editor
  1192. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  1193. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  1194. # CNCJob General
  1195. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  1196. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  1197. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  1198. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  1199. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  1200. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  1201. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  1202. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  1203. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  1204. "cncjob_plot_line": self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_entry,
  1205. "cncjob_plot_fill": self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_entry,
  1206. "cncjob_travel_line": self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_entry,
  1207. "cncjob_travel_fill": self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_entry,
  1208. # CNC Job Options
  1209. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  1210. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  1211. # CNC Job Advanced Options
  1212. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  1213. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  1214. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  1215. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  1216. # NCC Tool
  1217. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  1218. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  1219. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  1220. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  1221. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  1222. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  1223. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  1224. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  1225. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  1226. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  1227. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  1228. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  1229. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  1230. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  1231. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  1232. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  1233. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  1234. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  1235. # CutOut Tool
  1236. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  1237. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  1238. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  1239. "tools_cutout_z": self.ui.tools_defaults_form.tools_cutout_group.cutz_entry,
  1240. "tools_cutout_depthperpass": self.ui.tools_defaults_form.tools_cutout_group.maxdepth_entry,
  1241. "tools_cutout_mdepth": self.ui.tools_defaults_form.tools_cutout_group.mpass_cb,
  1242. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  1243. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  1244. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  1245. # Paint Area Tool
  1246. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  1247. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  1248. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  1249. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  1250. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  1251. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  1252. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  1253. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  1254. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  1255. # 2-sided Tool
  1256. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  1257. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  1258. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  1259. # Film Tool
  1260. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  1261. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  1262. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  1263. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  1264. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  1265. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  1266. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  1267. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  1268. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  1269. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  1270. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  1271. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  1272. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  1273. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  1274. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  1275. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  1276. # Panelize Tool
  1277. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  1278. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  1279. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  1280. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  1281. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  1282. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  1283. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  1284. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  1285. # Calculators Tool
  1286. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  1287. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  1288. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  1289. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  1290. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  1291. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  1292. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  1293. # Transformations Tool
  1294. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  1295. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  1296. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  1297. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  1298. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  1299. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  1300. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  1301. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  1302. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  1303. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  1304. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  1305. "tools_transform_buffer_dis": self.ui.tools_defaults_form.tools_transform_group.buffer_entry,
  1306. "tools_transform_buffer_factor": self.ui.tools_defaults_form.tools_transform_group.buffer_factor_entry,
  1307. "tools_transform_buffer_corner": self.ui.tools_defaults_form.tools_transform_group.buffer_rounded_cb,
  1308. # SolderPaste Dispensing Tool
  1309. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  1310. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  1311. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  1312. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  1313. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  1314. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  1315. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  1316. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  1317. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  1318. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  1319. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  1320. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  1321. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  1322. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  1323. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  1324. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  1325. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  1326. # ###################################################################################
  1327. # ################################ TOOLS 2 ##########################################
  1328. # ###################################################################################
  1329. # Optimal Tool
  1330. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  1331. # Check Rules Tool
  1332. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  1333. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  1334. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  1335. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  1336. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  1337. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  1338. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  1339. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  1340. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  1341. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  1342. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  1343. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  1344. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  1345. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  1346. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  1347. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  1348. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  1349. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  1350. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  1351. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  1352. # QRCode Tool
  1353. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  1354. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  1355. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  1356. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  1357. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  1358. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  1359. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  1360. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  1361. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  1362. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  1363. # Copper Thieving Tool
  1364. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  1365. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  1366. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  1367. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  1368. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  1369. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  1370. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  1371. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  1372. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  1373. "tools_copper_thieving_squares_spacing":
  1374. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  1375. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  1376. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  1377. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  1378. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  1379. "tools_copper_thieving_mask_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_ppm_entry,
  1380. # Fiducials Tool
  1381. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  1382. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  1383. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  1384. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  1385. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  1386. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  1387. # Calibration Tool
  1388. "tools_cal_calsource": self.ui.tools2_defaults_form.tools2_cal_group.cal_source_radio,
  1389. "tools_cal_travelz": self.ui.tools2_defaults_form.tools2_cal_group.travelz_entry,
  1390. "tools_cal_verz": self.ui.tools2_defaults_form.tools2_cal_group.verz_entry,
  1391. "tools_cal_zeroz": self.ui.tools2_defaults_form.tools2_cal_group.zeroz_cb,
  1392. "tools_cal_toolchangez": self.ui.tools2_defaults_form.tools2_cal_group.toolchangez_entry,
  1393. "tools_cal_toolchange_xy": self.ui.tools2_defaults_form.tools2_cal_group.toolchange_xy_entry,
  1394. "tools_cal_sec_point": self.ui.tools2_defaults_form.tools2_cal_group.second_point_radio,
  1395. # Extract Drills Tool
  1396. "tools_edrills_hole_type": self.ui.tools2_defaults_form.tools2_edrills_group.hole_size_radio,
  1397. "tools_edrills_hole_fixed_dia": self.ui.tools2_defaults_form.tools2_edrills_group.dia_entry,
  1398. "tools_edrills_hole_prop_factor": self.ui.tools2_defaults_form.tools2_edrills_group.factor_entry,
  1399. "tools_edrills_circular_ring": self.ui.tools2_defaults_form.tools2_edrills_group.circular_ring_entry,
  1400. "tools_edrills_oblong_ring": self.ui.tools2_defaults_form.tools2_edrills_group.oblong_ring_entry,
  1401. "tools_edrills_square_ring": self.ui.tools2_defaults_form.tools2_edrills_group.square_ring_entry,
  1402. "tools_edrills_rectangular_ring": self.ui.tools2_defaults_form.tools2_edrills_group.rectangular_ring_entry,
  1403. "tools_edrills_others_ring": self.ui.tools2_defaults_form.tools2_edrills_group.other_ring_entry,
  1404. "tools_edrills_circular": self.ui.tools2_defaults_form.tools2_edrills_group.circular_cb,
  1405. "tools_edrills_oblong": self.ui.tools2_defaults_form.tools2_edrills_group.oblong_cb,
  1406. "tools_edrills_square": self.ui.tools2_defaults_form.tools2_edrills_group.square_cb,
  1407. "tools_edrills_rectangular": self.ui.tools2_defaults_form.tools2_edrills_group.rectangular_cb,
  1408. "tools_edrills_others": self.ui.tools2_defaults_form.tools2_edrills_group.other_cb,
  1409. # Utilities
  1410. # File associations
  1411. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  1412. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  1413. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  1414. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  1415. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  1416. }
  1417. # update the Preferences GUI elements with the values in the self.defaults
  1418. self.defaults_write_form()
  1419. # When the self.defaults dictionary changes will update the Preferences GUI forms
  1420. self.defaults.set_change_callback(self.on_defaults_dict_change)
  1421. # ##############################################################################
  1422. # ########################## FIRST RUN SECTION #################################
  1423. # ##################### It's done only once after install ####################
  1424. # ##############################################################################
  1425. if self.defaults["first_run"] is True:
  1426. self.save_factory_defaults(silent_message=False)
  1427. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  1428. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1429. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1430. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1431. initial_lay = 'compact'
  1432. self.on_layout(lay=initial_lay)
  1433. # Set the combobox in Preferences to the current layout
  1434. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  1435. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  1436. # after the first run, this object should be False
  1437. self.defaults["first_run"] = False
  1438. self.save_defaults(silent=True)
  1439. # #############################################################################
  1440. # ############################## Data #########################################
  1441. # #############################################################################
  1442. self.recent = []
  1443. self.recent_projects = []
  1444. self.clipboard = QtWidgets.QApplication.clipboard()
  1445. self.project_filename = None
  1446. self.toggle_units_ignore = False
  1447. # #############################################################################
  1448. # ########################## LOAD PREPROCESSORS ###############################
  1449. # #############################################################################
  1450. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  1451. # the preprocessor file
  1452. self.preprocessors = load_preprocessors(self)
  1453. # make sure that always the 'default' preprocessor is the first item in the dictionary
  1454. if 'default' in self.preprocessors.keys():
  1455. new_ppp_dict = dict()
  1456. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  1457. default_pp = self.preprocessors.pop('default')
  1458. new_ppp_dict['default'] = default_pp
  1459. # then add the rest of the keys
  1460. for name, val_class in self.preprocessors.items():
  1461. new_ppp_dict[name] = val_class
  1462. # and now put back the ordered dict with 'default' key first
  1463. self.preprocessors = new_ppp_dict
  1464. for name in list(self.preprocessors.keys()):
  1465. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  1466. if name.partition('_')[0] == 'Paste':
  1467. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  1468. continue
  1469. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1470. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  1471. if name == 'hpgl':
  1472. continue
  1473. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1474. # #############################################################################
  1475. # ########################## LOAD LANGUAGES ##################################
  1476. # #############################################################################
  1477. self.languages = fcTranslate.load_languages()
  1478. for name in sorted(self.languages.values()):
  1479. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  1480. # #############################################################################
  1481. # ############################ APPLY APP LANGUAGE #############################
  1482. # #############################################################################
  1483. ret_val = fcTranslate.apply_language('strings')
  1484. if ret_val == "no language":
  1485. self.inform.emit('[ERROR] %s' %
  1486. _("Could not find the Language files. The App strings are missing."))
  1487. log.debug("Could not find the Language files. The App strings are missing.")
  1488. else:
  1489. # make the current language the current selection on the language combobox
  1490. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1491. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1492. # #############################################################################
  1493. # ########################### CREATE UNIQUE SERIAL NUMBER #####################
  1494. # #############################################################################
  1495. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1496. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1497. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1498. self.save_defaults(silent=True, first_time=True)
  1499. self.propagate_defaults(silent=True)
  1500. # def auto_save_defaults():
  1501. # try:
  1502. # self.save_defaults(silent=True)
  1503. # self.propagate_defaults(silent=True)
  1504. # finally:
  1505. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1506. # the following lines activates automatic defaults save
  1507. # if user_defaults:
  1508. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1509. # #############################################################################
  1510. # ########################### UPDATE THE OPTIONS ##############################
  1511. # #############################################################################
  1512. self.options = LoudDict()
  1513. # ----------------------------------------------------------------------------------------------------
  1514. # Update the self.options from the self.defaults
  1515. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1516. # -----------------------------------------------------------------------------------------------------
  1517. # Copy app defaults to project options
  1518. for def_key, def_val in self.defaults.items():
  1519. self.options[def_key] = deepcopy(def_val)
  1520. # self.options.update(self.defaults)
  1521. self.gen_form = None
  1522. self.ger_form = None
  1523. self.exc_form = None
  1524. self.geo_form = None
  1525. self.cnc_form = None
  1526. self.tools_form = None
  1527. self.tools2_form = None
  1528. self.fa_form = None
  1529. # Will show the Preferences GUI
  1530. self.show_preferences_gui()
  1531. # Initialize the color box's color in Preferences -> Global -> Color
  1532. self.init_color_pickers_in_preferences_gui()
  1533. # ### End of Data ####
  1534. # #############################################################################
  1535. # ######################## SETUP OBJECT COLLECTION ############################
  1536. # #############################################################################
  1537. self.collection = ObjectCollection(self)
  1538. self.ui.project_tab_layout.addWidget(self.collection.view)
  1539. # ### Adjust tabs width ## ##
  1540. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1541. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1542. self.collection.view.setMinimumWidth(290)
  1543. self.log.debug("Finished creating Object Collection.")
  1544. # #############################################################################
  1545. # ############################## SETUP Plot Area ##############################
  1546. # #############################################################################
  1547. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1548. if self.defaults["global_graphic_engine"] == '3D':
  1549. self.is_legacy = False
  1550. else:
  1551. self.is_legacy = True
  1552. # Event signals disconnect id holders
  1553. self.mp = None
  1554. self.mm = None
  1555. self.mr = None
  1556. self.mdc = None
  1557. self.mp_zc = None
  1558. self.kp = None
  1559. # Matplotlib axis
  1560. self.axes = None
  1561. if show_splash:
  1562. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1563. "Canvas initialization started."),
  1564. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1565. color=QtGui.QColor("gray"))
  1566. start_plot_time = time.time() # debug
  1567. self.plotcanvas = None
  1568. self.app_cursor = None
  1569. self.hover_shapes = None
  1570. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  1571. # setup the PlotCanvas
  1572. self.on_plotcanvas_setup()
  1573. end_plot_time = time.time()
  1574. self.used_time = end_plot_time - start_plot_time
  1575. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1576. if show_splash:
  1577. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1578. "Canvas initialization started.\n"
  1579. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1580. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1581. color=QtGui.QColor("gray"))
  1582. self.ui.splitter.setStretchFactor(1, 2)
  1583. # #############################################################################
  1584. # ################################### SYS TRAY ################################
  1585. # #############################################################################
  1586. if self.defaults["global_systray_icon"]:
  1587. self.parent_w = QtWidgets.QWidget()
  1588. if self.cmd_line_headless == 1:
  1589. self.trayIcon = FlatCAMSystemTray(app=self,
  1590. icon=QtGui.QIcon(self.resource_location +
  1591. '/flatcam_icon32_green.png'),
  1592. headless=True,
  1593. parent=self.parent_w)
  1594. else:
  1595. self.trayIcon = FlatCAMSystemTray(app=self,
  1596. icon=QtGui.QIcon(self.resource_location +
  1597. '/flatcam_icon32_green.png'),
  1598. parent=self.parent_w)
  1599. # #############################################################################
  1600. # ################################## Worker SETUP #############################
  1601. # #############################################################################
  1602. if self.defaults["global_worker_number"]:
  1603. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1604. else:
  1605. self.workers = WorkerStack(workers_number=2)
  1606. self.worker_task.connect(self.workers.add_task)
  1607. self.log.debug("Finished creating Workers crew.")
  1608. # #############################################################################
  1609. # ################################# Activity Monitor ##########################
  1610. # #############################################################################
  1611. self.activity_view = FlatCAMActivityView(app=self)
  1612. self.ui.infobar.addWidget(self.activity_view)
  1613. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1614. # #############################################################################
  1615. # ################################## Signal handling ##########################
  1616. # #############################################################################
  1617. # ################################# Custom signals ###########################
  1618. # signal for displaying messages in status bar
  1619. self.inform.connect(self.info)
  1620. # signal to be called when the app is quiting
  1621. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1622. self.message.connect(self.message_dialog)
  1623. # self.progress.connect(self.set_progress_bar)
  1624. # signals that are emitted when object state changes
  1625. self.object_created.connect(self.on_object_created)
  1626. self.object_changed.connect(self.on_object_changed)
  1627. self.object_plotted.connect(self.on_object_plotted)
  1628. self.plots_updated.connect(self.on_plots_updated)
  1629. # signals emitted when file state change
  1630. self.file_opened.connect(self.register_recent)
  1631. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1632. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1633. # ############# Standard signals ###################
  1634. # ### Menu
  1635. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1636. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1637. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1638. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1639. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1640. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1641. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1642. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1643. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1644. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1645. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1646. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1647. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1648. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1649. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1650. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1651. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1652. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  1653. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1654. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1655. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1656. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1657. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1658. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  1659. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1660. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1661. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1662. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1663. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1664. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1665. self.ui.menufile_exit.triggered.connect(self.final_save)
  1666. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1667. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1668. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1669. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1670. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1671. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1672. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1673. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1674. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1675. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1676. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1677. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1678. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1679. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1680. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1681. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1682. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1683. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1684. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1685. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1686. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1687. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1688. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1689. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1690. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1691. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1692. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1693. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1694. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1695. self.ui.menuoptions_tools_db.triggered.connect(self.on_tools_database)
  1696. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1697. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1698. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1699. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1700. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1701. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1702. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1703. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1704. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1705. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1706. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1707. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1708. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1709. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1710. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1711. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1712. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1713. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1714. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1715. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1716. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1717. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1718. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1719. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1720. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1721. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1722. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1723. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1724. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1725. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1726. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1727. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1728. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1729. # ToolBar signals
  1730. self.connect_toolbar_signals()
  1731. # Notebook and Plot Tab Area signals
  1732. # make the right click on the notebook tab and plot tab area tab raise a menu
  1733. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1734. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1735. self.on_tab_setup_context_menu()
  1736. # activate initial state
  1737. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1738. # Context Menu
  1739. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1740. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1741. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1742. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1743. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1744. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1745. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1746. self.ui.clearplot.triggered.connect(self.clear_plots)
  1747. self.ui.replot.triggered.connect(self.plot_all)
  1748. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1749. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1750. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1751. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1752. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1753. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1754. # Project Context Menu -> Color Setting
  1755. for act in self.ui.menuprojectcolor.actions():
  1756. act.triggered.connect(self.on_set_color_action_triggered)
  1757. # Preferences Plot Area TAB
  1758. self.ui.pref_save_button.clicked.connect(lambda: self.on_save_button(save_to_file=True))
  1759. self.ui.pref_apply_button.clicked.connect(lambda: self.on_save_button(save_to_file=False))
  1760. self.ui.pref_close_button.clicked.connect(self.on_pref_close_button)
  1761. self.ui.pref_defaults_button.clicked.connect(self.on_restore_defaults_preferences)
  1762. # #############################################################################
  1763. # ######################### GUI PREFERENCES SIGNALS ###########################
  1764. # #############################################################################
  1765. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1766. lambda: self.on_toggle_units(no_pref=False))
  1767. # ############################# Workspace Setting Signals #####################
  1768. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1769. self.on_workspace_modified)
  1770. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1771. self.on_workspace_modified
  1772. )
  1773. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1774. self.ui.general_defaults_form.general_gui_group.layout_combo.activated.connect(self.on_layout)
  1775. # #############################################################################
  1776. # ############################# GUI SETTINGS SIGNALS ##########################
  1777. # #############################################################################
  1778. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1779. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1780. # ########## Tools related signals #############
  1781. # Film Tool
  1782. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1783. self.on_film_color_entry)
  1784. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1785. self.on_film_color_button)
  1786. # QRCode Tool
  1787. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1788. self.on_qrcode_fill_color_entry)
  1789. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1790. self.on_qrcode_fill_color_button)
  1791. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1792. self.on_qrcode_back_color_entry)
  1793. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1794. self.on_qrcode_back_color_button)
  1795. # portability changed signal
  1796. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1797. # Object list
  1798. self.collection.view.activated.connect(self.on_row_activated)
  1799. self.collection.item_selected.connect(self.on_row_selected)
  1800. self.object_status_changed.connect(self.on_collection_updated)
  1801. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1802. # Export Excellon parameters.
  1803. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1804. self.on_update_exc_export
  1805. )
  1806. # call it once to make sure it is updated at startup
  1807. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1808. # when there are arguments at application startup this get launched
  1809. self.args_at_startup[list].connect(self.on_startup_args)
  1810. # #############################################################################
  1811. # ########################## FILE ASSOCIATIONS SIGNALS ########################
  1812. # #############################################################################
  1813. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1814. lambda: self.restore_extensions(ext_type='excellon'))
  1815. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1816. lambda: self.restore_extensions(ext_type='gcode'))
  1817. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1818. lambda: self.restore_extensions(ext_type='gerber'))
  1819. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1820. lambda: self.delete_all_extensions(ext_type='excellon'))
  1821. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1822. lambda: self.delete_all_extensions(ext_type='gcode'))
  1823. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1824. lambda: self.delete_all_extensions(ext_type='gerber'))
  1825. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1826. lambda: self.add_extension(ext_type='excellon'))
  1827. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1828. lambda: self.add_extension(ext_type='gcode'))
  1829. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1830. lambda: self.add_extension(ext_type='gerber'))
  1831. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1832. lambda: self.del_extension(ext_type='excellon'))
  1833. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1834. lambda: self.del_extension(ext_type='gcode'))
  1835. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1836. lambda: self.del_extension(ext_type='gerber'))
  1837. # connect the 'Apply' buttons from the Preferences/File Associations
  1838. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1839. lambda: self.on_register_files(obj_type='excellon'))
  1840. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1841. lambda: self.on_register_files(obj_type='gcode'))
  1842. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1843. lambda: self.on_register_files(obj_type='gerber'))
  1844. # #############################################################################
  1845. # ################################ KEYWORDS SIGNALS ###########################
  1846. # #############################################################################
  1847. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1848. lambda: self.restore_extensions(ext_type='keyword'))
  1849. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1850. lambda: self.delete_all_extensions(ext_type='keyword'))
  1851. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1852. lambda: self.add_extension(ext_type='keyword'))
  1853. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1854. lambda: self.del_extension(ext_type='keyword'))
  1855. # connect the abort_all_tasks related slots to the related signals
  1856. self.proc_container.idle_flag.connect(self.app_is_idle)
  1857. # signal emitted when a tab is closed in the Plot Area
  1858. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1859. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  1860. # signal to close the application
  1861. self.close_app_signal.connect(self.kill_app)
  1862. # #####################################################################################
  1863. # ########### FINISHED CONNECTING SIGNALS #############################################
  1864. # #####################################################################################
  1865. self.log.debug("Finished connecting Signals.")
  1866. # #####################################################################################
  1867. # ########################## Other setups #############################################
  1868. # #####################################################################################
  1869. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1870. # depending on from where those tools are called different actions can be done
  1871. self.call_source = 'app'
  1872. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1873. self.tool_tab_locked = False
  1874. # decide if to show or hide the Notebook side of the screen at startup
  1875. if self.defaults["global_project_at_startup"] is True:
  1876. self.ui.splitter.setSizes([1, 1])
  1877. else:
  1878. self.ui.splitter.setSizes([0, 1])
  1879. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1880. self.setup_component_editor()
  1881. # #####################################################################################
  1882. # ######################### Auto-complete KEYWORDS ####################################
  1883. # #####################################################################################
  1884. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1885. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1886. 'delete', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon', 'ee', 'export_exc',
  1887. 'export_gcode', 'export_gerber', 'egr', 'export_svg', 'ext', 'exteriors', 'follow',
  1888. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1889. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1890. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1891. 'mirror', 'ncc',
  1892. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1893. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1894. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1895. 'save', 'save_project',
  1896. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1897. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1898. 'version', 'write_gcode'
  1899. ]
  1900. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1901. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1902. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1903. 'axisoffset',
  1904. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1905. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz',
  1906. 'dwelltime', 'extracut_length',
  1907. 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1908. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1909. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  1910. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1911. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1912. 'spacing_columns',
  1913. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'toolchangez',
  1914. 'tooldia', 'use_threads', 'value',
  1915. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1916. ]
  1917. self.tcl_keywords = [
  1918. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1919. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1920. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1921. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1922. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1923. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1924. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1925. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1926. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1927. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1928. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1929. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1930. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1931. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1932. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1933. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1934. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1935. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1936. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1937. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1938. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1939. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1940. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1941. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1942. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1943. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1944. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1945. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1946. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1947. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1948. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1949. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1950. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1951. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1952. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1953. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1954. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1955. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1956. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1957. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1958. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1959. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1960. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1961. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1962. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1963. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1964. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1965. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1966. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1967. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1968. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1969. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1970. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1971. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1972. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1973. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1974. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1975. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1976. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1977. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1978. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1979. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1980. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1981. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1982. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1983. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1984. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1985. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1986. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1987. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1988. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1989. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1990. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1991. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1992. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1993. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1994. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1995. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1996. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1997. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1998. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1999. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  2000. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  2001. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  2002. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  2003. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  2004. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  2005. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  2006. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  2007. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  2008. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  2009. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  2010. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  2011. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  2012. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  2013. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  2014. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  2015. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  2016. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  2017. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  2018. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  2019. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  2020. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  2021. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  2022. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  2023. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  2024. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  2025. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  2026. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  2027. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  2028. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  2029. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  2030. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  2031. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  2032. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  2033. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  2034. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  2035. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  2036. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  2037. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  2038. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  2039. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  2040. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  2041. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  2042. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  2043. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  2044. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  2045. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  2046. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  2047. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  2048. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  2049. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  2050. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  2051. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  2052. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  2053. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  2054. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  2055. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  2056. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  2057. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  2058. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  2059. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  2060. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  2061. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  2062. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  2063. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  2064. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  2065. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  2066. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  2067. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  2068. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  2069. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  2070. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  2071. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  2072. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  2073. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2074. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2075. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2076. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2077. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2078. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2079. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2080. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2081. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2082. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2083. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2084. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2085. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2086. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2087. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2088. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2089. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2090. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2091. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2092. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2093. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2094. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2095. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2096. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2097. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2098. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2099. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2100. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2101. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2102. ]
  2103. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2104. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2105. # ####################################################################################
  2106. # ####################### Shell SETUP ################################################
  2107. # ####################################################################################
  2108. # this will hold the TCL instance
  2109. self.tcl = None
  2110. self.init_tcl()
  2111. self.shell = FCShell(self, version=self.version)
  2112. self.shell._edit.set_model_data(self.myKeywords)
  2113. self.shell.setWindowIcon(self.ui.app_icon)
  2114. self.shell.setWindowTitle("FlatCAM Shell")
  2115. self.shell.resize(*self.defaults["global_shell_shape"])
  2116. self.shell.append_output("FlatCAM %s - " % self.version)
  2117. self.shell.append_output(_("Type >help< to get started\n\n"))
  2118. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2119. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2120. self.ui.shell_dock.setWidget(self.shell)
  2121. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2122. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2123. QtWidgets.QDockWidget.DockWidgetFloatable |
  2124. QtWidgets.QDockWidget.DockWidgetClosable)
  2125. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2126. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2127. if self.defaults["global_shell_at_startup"]:
  2128. self.ui.shell_dock.show()
  2129. else:
  2130. self.ui.shell_dock.hide()
  2131. # ##################################################################################
  2132. # ###################### Tools and Plugins #########################################
  2133. # ##################################################################################
  2134. self.dblsidedtool = None
  2135. self.distance_tool = None
  2136. self.distance_min_tool = None
  2137. self.panelize_tool = None
  2138. self.film_tool = None
  2139. self.paste_tool = None
  2140. self.calculator_tool = None
  2141. self.rules_tool = None
  2142. self.sub_tool = None
  2143. self.move_tool = None
  2144. self.cutout_tool = None
  2145. self.ncclear_tool = None
  2146. self.optimal_tool = None
  2147. self.paint_tool = None
  2148. self.transform_tool = None
  2149. self.properties_tool = None
  2150. self.pdf_tool = None
  2151. self.image_tool = None
  2152. self.pcb_wizard_tool = None
  2153. self.cal_exc_tool = None
  2154. self.qrcode_tool = None
  2155. self.copper_thieving_tool = None
  2156. self.fiducial_tool = None
  2157. self.edrills_tool = None
  2158. self.align_objects_tool = None
  2159. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2160. try:
  2161. self.install_tools()
  2162. except AttributeError as e:
  2163. log.debug("App.__init__() install tools() --> %s" % str(e))
  2164. # ##################################################################################
  2165. # ########################### SETUP RECENT ITEMS ###################################
  2166. # ##################################################################################
  2167. self.setup_recent_items()
  2168. # ##################################################################################
  2169. # ########################### BookMarks Manager ####################################
  2170. # ##################################################################################
  2171. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2172. self.install_bookmarks()
  2173. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2174. # ##################################################################################
  2175. # ############################## Tools Database ####################################
  2176. # ##################################################################################
  2177. self.tools_db_tab = None
  2178. # ### System Font Parsing ###
  2179. # self.f_parse = ParseFont(self)
  2180. # self.parse_system_fonts()
  2181. # #####################################################################################
  2182. # ######################## Check for updates ##########################################
  2183. # #####################################################################################
  2184. # Separate thread (Not worker)
  2185. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2186. if (self.beta is False or self.beta is None) and \
  2187. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2188. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2189. self.thr2 = QtCore.QThread()
  2190. self.worker_task.emit({'fcn': self.version_check,
  2191. 'params': []})
  2192. self.thr2.start(QtCore.QThread.LowPriority)
  2193. # #####################################################################################
  2194. # ######################### Register files with FlatCAM; #############################
  2195. # ######################### It works only for Windows for now ########################
  2196. # #####################################################################################
  2197. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2198. self.on_register_files()
  2199. # #####################################################################################
  2200. # ###################### Variables for global usage ###################################
  2201. # #####################################################################################
  2202. # hold the App units
  2203. self.units = 'MM'
  2204. # coordinates for relative position display
  2205. self.rel_point1 = (0, 0)
  2206. self.rel_point2 = (0, 0)
  2207. # variable to store coordinates
  2208. self.pos = (0, 0)
  2209. self.pos_canvas = (0, 0)
  2210. self.pos_jump = (0, 0)
  2211. # variable to store mouse coordinates
  2212. self.mouse = [0, 0]
  2213. # decide if we have a double click or single click
  2214. self.doubleclick = False
  2215. # store here the is_dragging value
  2216. self.event_is_dragging = False
  2217. # variable to store if a command is active (then the var is not None) and which one it is
  2218. self.command_active = None
  2219. # variable to store the status of moving selection action
  2220. # None value means that it's not an selection action
  2221. # True value = a selection from left to right
  2222. # False value = a selection from right to left
  2223. self.selection_type = None
  2224. # List to store the objects that are currently loaded in FlatCAM
  2225. # This list is updated on each object creation or object delete
  2226. self.all_objects_list = list()
  2227. # List to store the objects that are selected
  2228. self.sel_objects_list = list()
  2229. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2230. self.key_modifiers = None
  2231. # Variable to hold the status of the axis
  2232. self.toggle_axis = True
  2233. # Variable to hold the status of the grid lines
  2234. self.toggle_grid_lines = True
  2235. # Variable to store the status of the fullscreen event
  2236. self.toggle_fscreen = False
  2237. # Variable to store the status of the code editor
  2238. self.toggle_codeeditor = False
  2239. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2240. self.click_noproject = False
  2241. self.cursor = None
  2242. # Variable to store the GCODE that was edited
  2243. self.gcode_edited = ""
  2244. self.text_editor_tab = None
  2245. # reference for the self.ui.code_editor
  2246. self.reference_code_editor = None
  2247. self.script_code = ''
  2248. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2249. self.preferences_changed_flag = False
  2250. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  2251. self.tools_db_changed_flag = False
  2252. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2253. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2254. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2255. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2256. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2257. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2258. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  2259. 'sbp', 'tap', 'xpi']
  2260. self.svg_list = ['svg']
  2261. self.dxf_list = ['dxf']
  2262. self.pdf_list = ['pdf']
  2263. self.prj_list = ['flatprj']
  2264. self.conf_list = ['flatconfig']
  2265. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2266. # flag for polygons not cleared
  2267. self.poly_not_cleared = False
  2268. # VisPy visuals
  2269. self.isHovering = False
  2270. self.notHovering = True
  2271. # Window geometry
  2272. self.x_pos = None
  2273. self.y_pos = None
  2274. self.width = None
  2275. self.height = None
  2276. # when True, the app has to return from any thread
  2277. self.abort_flag = False
  2278. # set the value used in the Windows Title
  2279. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2280. # this holds a widget that is installed in the Plot Area when View Source option is used
  2281. self.source_editor_tab = None
  2282. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  2283. # VisPy visuals
  2284. if self.is_legacy is False:
  2285. try:
  2286. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  2287. except AttributeError:
  2288. self.tool_shapes = None
  2289. else:
  2290. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2291. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  2292. # ###############################################################################
  2293. # ################# ADDING FlatCAM EDITORS section ##############################
  2294. # ###############################################################################
  2295. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2296. # at the first launch of the App , the editors will not be functional.
  2297. try:
  2298. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2299. except AttributeError:
  2300. pass
  2301. try:
  2302. self.exc_editor = FlatCAMExcEditor(self)
  2303. except AttributeError:
  2304. pass
  2305. try:
  2306. self.grb_editor = FlatCAMGrbEditor(self)
  2307. except AttributeError:
  2308. pass
  2309. self.log.debug("Finished adding FlatCAM Editor's.")
  2310. self.set_ui_title(name=_("New Project - Not saved"))
  2311. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2312. current_platform = platform.architecture()[0]
  2313. if current_platform != '64bit':
  2314. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2315. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2316. # ###############################################################################
  2317. # ####################### Finished the CONSTRUCTOR ##############################
  2318. # ###############################################################################
  2319. App.log.debug("END of constructor. Releasing control.")
  2320. # #####################################################################################
  2321. # ########################## SHOW GUI #################################################
  2322. # #####################################################################################
  2323. # if the app is not started as headless, show it
  2324. if self.cmd_line_headless != 1:
  2325. if show_splash:
  2326. # finish the splash
  2327. self.splash.finish(self.ui)
  2328. mgui_settings = QSettings("Open Source", "FlatCAM")
  2329. if mgui_settings.contains("maximized_gui"):
  2330. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  2331. if maximized_ui is True:
  2332. self.ui.showMaximized()
  2333. else:
  2334. self.ui.show()
  2335. else:
  2336. self.ui.show()
  2337. if self.defaults["global_systray_icon"]:
  2338. self.trayIcon.show()
  2339. else:
  2340. log.warning("******************* RUNNING HEADLESS *******************")
  2341. # #####################################################################################
  2342. # ########################## START-UP ARGUMENTS #######################################
  2343. # #####################################################################################
  2344. # test if the program was started with a script as parameter
  2345. if self.cmd_line_shellvar:
  2346. try:
  2347. cnt = 0
  2348. command_tcl = 0
  2349. for i in self.cmd_line_shellvar.split(','):
  2350. if i is not None:
  2351. # noinspection PyBroadException
  2352. try:
  2353. command_tcl = eval(i)
  2354. except Exception:
  2355. command_tcl = i
  2356. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2357. cnt += 1
  2358. # if there are Windows paths then replace the path separator with a Unix like one
  2359. if sys.platform == 'win32':
  2360. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2361. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2362. except Exception as ext:
  2363. print("ERROR: ", ext)
  2364. sys.exit(2)
  2365. if self.cmd_line_shellfile:
  2366. if self.cmd_line_headless != 1:
  2367. if self.ui.shell_dock.isHidden():
  2368. self.ui.shell_dock.show()
  2369. try:
  2370. with open(self.cmd_line_shellfile, "r") as myfile:
  2371. # if show_splash:
  2372. # self.splash.showMessage('%s: %ssec\n%s' % (
  2373. # _("Canvas initialization started.\n"
  2374. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  2375. # _("Executing Tcl Script ...")),
  2376. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  2377. # color=QtGui.QColor("gray"))
  2378. cmd_line_shellfile_text = myfile.read()
  2379. if self.cmd_line_headless != 1:
  2380. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2381. else:
  2382. self.shell._sysShell.exec_command(cmd_line_shellfile_text, no_echo=True)
  2383. except Exception as ext:
  2384. print("ERROR: ", ext)
  2385. sys.exit(2)
  2386. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2387. # the path/file_name must be enclosed in quotes if it contain spaces
  2388. if App.args:
  2389. self.args_at_startup.emit(App.args)
  2390. if self.old_defaults_found is True:
  2391. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  2392. "Please reboot the application to update."))
  2393. self.old_defaults_found = False
  2394. @staticmethod
  2395. def copy_and_overwrite(from_path, to_path):
  2396. """
  2397. From here:
  2398. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2399. :param from_path: source path
  2400. :param to_path: destination path
  2401. :return: None
  2402. """
  2403. if os.path.exists(to_path):
  2404. shutil.rmtree(to_path)
  2405. try:
  2406. shutil.copytree(from_path, to_path)
  2407. except FileNotFoundError:
  2408. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2409. shutil.copytree(from_new_path, to_path)
  2410. def on_startup_args(self, args, silent=False):
  2411. """
  2412. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2413. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  2414. :param args: a list containing the application args at startup
  2415. :return: None
  2416. """
  2417. if args is not None:
  2418. args_to_process = args
  2419. else:
  2420. args_to_process = App.args
  2421. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2422. for argument in args_to_process:
  2423. if '.FlatPrj'.lower() in argument.lower():
  2424. try:
  2425. project_name = str(argument)
  2426. if project_name == "":
  2427. if silent is False:
  2428. self.inform.emit(_("Open cancelled."))
  2429. else:
  2430. # self.open_project(project_name)
  2431. run_from_arg = True
  2432. # self.worker_task.emit({'fcn': self.open_project,
  2433. # 'params': [project_name, run_from_arg]})
  2434. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2435. except Exception as e:
  2436. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2437. elif '.FlatConfig'.lower() in argument.lower():
  2438. try:
  2439. file_name = str(argument)
  2440. if file_name == "":
  2441. if silent is False:
  2442. self.inform.emit(_("Open Config file failed."))
  2443. else:
  2444. run_from_arg = True
  2445. # self.worker_task.emit({'fcn': self.open_config_file,
  2446. # 'params': [file_name, run_from_arg]})
  2447. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2448. except Exception as e:
  2449. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2450. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2451. try:
  2452. file_name = str(argument)
  2453. if file_name == "":
  2454. if silent is False:
  2455. self.inform.emit(_("Open Script file failed."))
  2456. else:
  2457. if silent is False:
  2458. self.on_fileopenscript(name=file_name)
  2459. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2460. self.on_filerunscript(name=file_name)
  2461. except Exception as e:
  2462. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2463. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2464. log.debug("App.on_startup_args() --> Quit event.")
  2465. sys.exit()
  2466. elif 'save'.lower() in argument.lower():
  2467. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2468. self.save_defaults()
  2469. else:
  2470. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2471. proc_arg = argument.lower()
  2472. for ext in exc_list:
  2473. proc_ext = ext.replace(' ', '')
  2474. proc_ext = '.%s' % proc_ext
  2475. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2476. file_name = str(argument)
  2477. if file_name == "":
  2478. if silent is False:
  2479. self.inform.emit(_("Open Excellon file failed."))
  2480. else:
  2481. self.on_fileopenexcellon(name=file_name)
  2482. return
  2483. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2484. for ext in gco_list:
  2485. proc_ext = ext.replace(' ', '')
  2486. proc_ext = '.%s' % proc_ext
  2487. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2488. file_name = str(argument)
  2489. if file_name == "":
  2490. if silent is False:
  2491. self.inform.emit(_("Open GCode file failed."))
  2492. else:
  2493. self.on_fileopengcode(name=file_name)
  2494. return
  2495. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2496. for ext in grb_list:
  2497. proc_ext = ext.replace(' ', '')
  2498. proc_ext = '.%s' % proc_ext
  2499. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2500. file_name = str(argument)
  2501. if file_name == "":
  2502. if silent is False:
  2503. self.inform.emit(_("Open Gerber file failed."))
  2504. else:
  2505. self.on_fileopengerber(name=file_name)
  2506. return
  2507. # if it reached here without already returning then the app was registered with a file that it does not
  2508. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2509. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2510. # for arg in args_to_process:
  2511. # if 'FlatCAM.exe' in arg:
  2512. # continue
  2513. # else:
  2514. # sys.exit(2)
  2515. def set_ui_title(self, name):
  2516. """
  2517. Sets the title of the main window.
  2518. :param name: String that store the project path and project name
  2519. :return: None
  2520. """
  2521. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2522. (self.version,
  2523. ('BETA' if self.beta else ''),
  2524. platform.architecture()[0],
  2525. self.engine,
  2526. name)
  2527. )
  2528. def on_app_restart(self):
  2529. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2530. # be left in the SySTray
  2531. try:
  2532. self.trayIcon.hide()
  2533. except Exception:
  2534. pass
  2535. fcTranslate.restart_program(app=self)
  2536. def defaults_read_form(self):
  2537. """
  2538. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2539. :return: None
  2540. """
  2541. for option in self.defaults_form_fields:
  2542. try:
  2543. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2544. except Exception as e:
  2545. log.debug("App.defaults_read_form() --> %s" % str(e))
  2546. def defaults_write_form(self, factor=None, fl_units=None, source_dict=None):
  2547. """
  2548. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2549. self.defaults dictionary.
  2550. :param factor: will apply a factor to the values that written in the GUI elements
  2551. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2552. :param source_dict: the repository of options, usually is the self.defaults
  2553. :return: None
  2554. """
  2555. options_storage = self.defaults if source_dict is None else source_dict
  2556. for option in options_storage:
  2557. if source_dict:
  2558. self.defaults_write_form_field(option, factor=factor, units=fl_units, defaults_dict=source_dict)
  2559. else:
  2560. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2561. # try:
  2562. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2563. # except KeyError:
  2564. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2565. # pass
  2566. def defaults_write_form_field(self, field, factor=None, units=None, defaults_dict=None):
  2567. """
  2568. Basically it is the worker in the self.defaults_write_form()
  2569. :param field: the GUI element in Preferences GUI to be updated
  2570. :param factor: factor to be applied to the field parameter
  2571. :param units: current FLatCAM measuring units
  2572. :param defaults_dict: the defaults storage
  2573. :return: None, it updates GUI elements
  2574. """
  2575. def_dict = self.defaults if defaults_dict is None else defaults_dict
  2576. try:
  2577. if factor is None:
  2578. if units is None:
  2579. self.defaults_form_fields[field].set_value(def_dict[field])
  2580. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2581. self.defaults_form_fields[field].set_value(def_dict[field])
  2582. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2583. self.defaults_form_fields[field].set_value(def_dict[field])
  2584. else:
  2585. if units is None:
  2586. self.defaults_form_fields[field].set_value(def_dict[field] * factor)
  2587. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2588. self.defaults_form_fields[field].set_value((def_dict[field] * factor))
  2589. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2590. self.defaults_form_fields[field].set_value((def_dict[field] * factor))
  2591. except KeyError:
  2592. pass
  2593. except AttributeError:
  2594. log.debug(field)
  2595. def clear_pool(self):
  2596. """
  2597. Clear the multiprocessing pool and calls garbage collector.
  2598. :return: None
  2599. """
  2600. self.pool.close()
  2601. self.pool = Pool()
  2602. self.pool_recreated.emit(self.pool)
  2603. gc.collect()
  2604. def install_tools(self):
  2605. """
  2606. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2607. Instantiation of the Tools classes.
  2608. The order that the tools are installed is important as they can depend on each other install position.
  2609. :return: None
  2610. """
  2611. self.distance_tool = Distance(self)
  2612. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  2613. before=self.ui.menueditorigin,
  2614. separator=False)
  2615. self.distance_min_tool = DistanceMin(self)
  2616. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  2617. pos=self.ui.menuedit,
  2618. before=self.ui.menueditorigin,
  2619. separator=True)
  2620. self.dblsidedtool = DblSidedTool(self)
  2621. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  2622. self.cal_exc_tool = ToolCalibration(self)
  2623. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  2624. before=self.dblsidedtool.menuAction,
  2625. separator=False)
  2626. self.align_objects_tool = AlignObjects(self)
  2627. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  2628. self.edrills_tool = ToolExtractDrills(self)
  2629. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  2630. self.panelize_tool = Panelize(self)
  2631. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  2632. self.film_tool = Film(self)
  2633. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  2634. self.paste_tool = SolderPaste(self)
  2635. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  2636. self.calculator_tool = ToolCalculator(self)
  2637. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  2638. self.sub_tool = ToolSub(self)
  2639. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  2640. pos=self.ui.menutool, separator=True)
  2641. self.rules_tool = RulesCheck(self)
  2642. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  2643. pos=self.ui.menutool, separator=False)
  2644. self.optimal_tool = ToolOptimal(self)
  2645. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  2646. pos=self.ui.menutool, separator=True)
  2647. self.move_tool = ToolMove(self)
  2648. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  2649. before=self.ui.menueditorigin, separator=True)
  2650. self.cutout_tool = CutOut(self)
  2651. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  2652. before=self.sub_tool.menuAction)
  2653. self.ncclear_tool = NonCopperClear(self)
  2654. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  2655. before=self.sub_tool.menuAction, separator=True)
  2656. self.paint_tool = ToolPaint(self)
  2657. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  2658. before=self.sub_tool.menuAction, separator=True)
  2659. self.copper_thieving_tool = ToolCopperThieving(self)
  2660. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  2661. pos=self.ui.menutool)
  2662. self.fiducial_tool = ToolFiducials(self)
  2663. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  2664. pos=self.ui.menutool)
  2665. self.qrcode_tool = QRCode(self)
  2666. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  2667. pos=self.ui.menutool)
  2668. self.transform_tool = ToolTransform(self)
  2669. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  2670. pos=self.ui.menuoptions, separator=True)
  2671. self.properties_tool = Properties(self)
  2672. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  2673. pos=self.ui.menuoptions)
  2674. self.pdf_tool = ToolPDF(self)
  2675. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  2676. pos=self.ui.menufileimport,
  2677. separator=True)
  2678. self.image_tool = ToolImage(self)
  2679. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  2680. pos=self.ui.menufileimport,
  2681. separator=True)
  2682. self.pcb_wizard_tool = PcbWizard(self)
  2683. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  2684. pos=self.ui.menufileimport)
  2685. self.log.debug("Tools are installed.")
  2686. def remove_tools(self):
  2687. """
  2688. Will remove all the actions in the Tool menu.
  2689. :return: None
  2690. """
  2691. for act in self.ui.menutool.actions():
  2692. self.ui.menutool.removeAction(act)
  2693. def init_tools(self):
  2694. """
  2695. Initialize the Tool tab in the notebook side of the central widget.
  2696. Remove the actions in the Tools menu.
  2697. Instantiate again the FlatCAM tools (plugins).
  2698. All this is required when changing the layout: standard, compact etc.
  2699. :return: None
  2700. """
  2701. log.debug("init_tools()")
  2702. # delete the data currently in the Tools Tab and the Tab itself
  2703. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2704. if widget is not None:
  2705. widget.deleteLater()
  2706. self.ui.notebook.removeTab(2)
  2707. # rebuild the Tools Tab
  2708. self.ui.tool_tab = QtWidgets.QWidget()
  2709. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2710. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2711. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2712. self.ui.tool_scroll_area = VerticalScrollArea()
  2713. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2714. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2715. # first remove all of them
  2716. self.remove_tools()
  2717. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2718. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  2719. '&Command Line\tS')
  2720. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2721. # third install all of them
  2722. try:
  2723. self.install_tools()
  2724. except AttributeError:
  2725. pass
  2726. self.log.debug("Tools are initialized.")
  2727. # def parse_system_fonts(self):
  2728. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2729. # 'params': []})
  2730. def connect_toolbar_signals(self):
  2731. """
  2732. Reconnect the signals to the actions in the toolbar.
  2733. This has to be done each time after the FlatCAM tools are removed/installed.
  2734. :return: None
  2735. """
  2736. # Toolbar
  2737. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2738. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2739. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2740. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2741. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2742. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2743. self.ui.replot_btn.triggered.connect(self.plot_all)
  2744. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2745. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2746. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2747. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2748. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2749. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2750. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2751. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2752. self.ui.copy_btn.triggered.connect(self.on_copy_object)
  2753. self.ui.delete_btn.triggered.connect(self.on_delete)
  2754. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2755. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2756. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2757. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2758. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  2759. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2760. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2761. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2762. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2763. # Tools Toolbar Signals
  2764. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2765. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  2766. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  2767. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  2768. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2769. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2770. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2771. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2772. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2773. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2774. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2775. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2776. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2777. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2778. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2779. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2780. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2781. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2782. def object2editor(self):
  2783. """
  2784. Send the current Geometry or Excellon object (if any) into the it's editor.
  2785. :return: None
  2786. """
  2787. self.report_usage("object2editor()")
  2788. # disable the objects menu as it may interfere with the Editors
  2789. self.ui.menuobjects.setDisabled(True)
  2790. edited_object = self.collection.get_active()
  2791. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2792. isinstance(edited_object, FlatCAMExcellon):
  2793. pass
  2794. else:
  2795. self.inform.emit('[WARNING_NOTCL] %s' %
  2796. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2797. return
  2798. if isinstance(edited_object, FlatCAMGeometry):
  2799. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2800. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2801. # we set the notebook to hidden
  2802. self.ui.splitter.setSizes([0, 1])
  2803. if edited_object.multigeo is True:
  2804. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2805. if len(sel_rows) > 1:
  2806. self.inform.emit('[WARNING_NOTCL] %s' %
  2807. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2808. "is not possible.\n"
  2809. "Edit only one geometry at a time."))
  2810. # determine the tool dia of the selected tool
  2811. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2812. # now find the key in the edited_object.tools that has this tooldia
  2813. multi_tool = 1
  2814. for tool in edited_object.tools:
  2815. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2816. multi_tool = tool
  2817. break
  2818. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2819. else:
  2820. self.geo_editor.edit_fcgeometry(edited_object)
  2821. # set call source to the Editor we go into
  2822. self.call_source = 'geo_editor'
  2823. elif isinstance(edited_object, FlatCAMExcellon):
  2824. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2825. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2826. if self.ui.splitter.sizes()[0] == 0:
  2827. self.ui.splitter.setSizes([1, 1])
  2828. self.exc_editor.edit_fcexcellon(edited_object)
  2829. # set call source to the Editor we go into
  2830. self.call_source = 'exc_editor'
  2831. elif isinstance(edited_object, FlatCAMGerber):
  2832. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2833. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2834. if self.ui.splitter.sizes()[0] == 0:
  2835. self.ui.splitter.setSizes([1, 1])
  2836. self.grb_editor.edit_fcgerber(edited_object)
  2837. # set call source to the Editor we go into
  2838. self.call_source = 'grb_editor'
  2839. # reset the following variables so the UI is built again after edit
  2840. edited_object.ui_build = False
  2841. edited_object.build_aperture_storage = False
  2842. # make sure that we can't select another object while in Editor Mode:
  2843. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2844. self.ui.project_frame.setDisabled(True)
  2845. # delete any selection shape that might be active as they are not relevant in Editor
  2846. self.delete_selection_shape()
  2847. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2848. self.ui.plot_tab_area.protectTab(0)
  2849. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  2850. self.should_we_save = True
  2851. def editor2object(self, cleanup=None):
  2852. """
  2853. Transfers the Geometry or Excellon from it's editor to the current object.
  2854. :return: None
  2855. """
  2856. self.report_usage("editor2object()")
  2857. # re-enable the objects menu that was disabled on entry in Editor mode
  2858. self.ui.menuobjects.setDisabled(False)
  2859. # do not update a geometry or excellon object unless it comes out of an editor
  2860. if self.call_source != 'app':
  2861. edited_obj = self.collection.get_active()
  2862. if cleanup is None:
  2863. msgbox = QtWidgets.QMessageBox()
  2864. msgbox.setText(_("Do you want to save the edited object?"))
  2865. msgbox.setWindowTitle(_("Close Editor"))
  2866. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2867. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2868. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2869. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2870. msgbox.setDefaultButton(bt_yes)
  2871. msgbox.exec_()
  2872. response = msgbox.clickedButton()
  2873. if response == bt_yes:
  2874. # clean the Tools Tab
  2875. self.ui.tool_scroll_area.takeWidget()
  2876. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2877. self.ui.notebook.setTabText(2, "Tool")
  2878. if isinstance(edited_obj, FlatCAMGeometry):
  2879. obj_type = "Geometry"
  2880. if cleanup is None:
  2881. self.geo_editor.update_fcgeometry(edited_obj)
  2882. self.geo_editor.update_options(edited_obj)
  2883. self.geo_editor.deactivate()
  2884. # update the geo object options so it is including the bounding box values
  2885. try:
  2886. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2887. edited_obj.options['xmin'] = xmin
  2888. edited_obj.options['ymin'] = ymin
  2889. edited_obj.options['xmax'] = xmax
  2890. edited_obj.options['ymax'] = ymax
  2891. except AttributeError as e:
  2892. self.inform.emit('[WARNING] %s' %
  2893. _("Object empty after edit."))
  2894. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2895. elif isinstance(edited_obj, FlatCAMGerber):
  2896. obj_type = "Gerber"
  2897. if cleanup is None:
  2898. self.grb_editor.update_fcgerber()
  2899. self.grb_editor.update_options(edited_obj)
  2900. self.grb_editor.deactivate_grb_editor()
  2901. # delete the old object (the source object) if it was an empty one
  2902. try:
  2903. if len(edited_obj.solid_geometry) == 0:
  2904. old_name = edited_obj.options['name']
  2905. self.collection.set_active(old_name)
  2906. self.collection.delete_active()
  2907. except TypeError:
  2908. # if the solid_geometry is a single Polygon the len() will not work
  2909. # in any case, falling here means that we have something in the solid_geometry, even if only
  2910. # a single Polygon, therefore we pass this
  2911. pass
  2912. # restore GUI to the Selected TAB
  2913. # Remove anything else in the GUI
  2914. self.ui.selected_scroll_area.takeWidget()
  2915. # Switch notebook to Selected page
  2916. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2917. elif isinstance(edited_obj, FlatCAMExcellon):
  2918. obj_type = "Excellon"
  2919. if cleanup is None:
  2920. self.exc_editor.update_fcexcellon(edited_obj)
  2921. self.exc_editor.update_options(edited_obj)
  2922. self.exc_editor.deactivate()
  2923. # delete the old object (the source object) if it was an empty one
  2924. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2925. old_name = edited_obj.options['name']
  2926. self.collection.set_active(old_name)
  2927. self.collection.delete_active()
  2928. # restore GUI to the Selected TAB
  2929. # Remove anything else in the GUI
  2930. self.ui.tool_scroll_area.takeWidget()
  2931. # Switch notebook to Selected page
  2932. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2933. else:
  2934. self.inform.emit('[WARNING_NOTCL] %s' %
  2935. _("Select a Gerber, Geometry or Excellon Object to update."))
  2936. return
  2937. self.inform.emit('[selected] %s %s' %
  2938. (obj_type, _("is updated, returning to App...")))
  2939. elif response == bt_no:
  2940. # clean the Tools Tab
  2941. self.ui.tool_scroll_area.takeWidget()
  2942. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2943. self.ui.notebook.setTabText(2, "Tool")
  2944. if isinstance(edited_obj, FlatCAMGeometry):
  2945. self.geo_editor.deactivate()
  2946. elif isinstance(edited_obj, FlatCAMGerber):
  2947. self.grb_editor.deactivate_grb_editor()
  2948. elif isinstance(edited_obj, FlatCAMExcellon):
  2949. self.exc_editor.deactivate()
  2950. # set focus on the project tab
  2951. else:
  2952. self.inform.emit('[WARNING_NOTCL] %s' %
  2953. _("Select a Gerber, Geometry or Excellon Object to update."))
  2954. return
  2955. edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2956. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2957. elif response == bt_cancel:
  2958. return
  2959. else:
  2960. if isinstance(edited_obj, FlatCAMGeometry):
  2961. self.geo_editor.deactivate()
  2962. elif isinstance(edited_obj, FlatCAMGerber):
  2963. self.grb_editor.deactivate_grb_editor()
  2964. elif isinstance(edited_obj, FlatCAMExcellon):
  2965. self.exc_editor.deactivate()
  2966. else:
  2967. self.inform.emit('[WARNING_NOTCL] %s' %
  2968. _("Select a Gerber, Geometry or Excellon Object to update."))
  2969. return
  2970. # if notebook is hidden we show it
  2971. if self.ui.splitter.sizes()[0] == 0:
  2972. self.ui.splitter.setSizes([1, 1])
  2973. # restore the call_source to app
  2974. self.call_source = 'app'
  2975. edited_obj.plot()
  2976. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2977. self.ui.plot_tab_area.protectTab(0)
  2978. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2979. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2980. self.ui.project_frame.setDisabled(False)
  2981. def get_last_folder(self):
  2982. """
  2983. Get the folder path from where the last file was opened.
  2984. :return: String, last opened folder path
  2985. """
  2986. return self.defaults["global_last_folder"]
  2987. def get_last_save_folder(self):
  2988. """
  2989. Get the folder path from where the last file was saved.
  2990. :return: String, last saved folder path
  2991. """
  2992. loc = self.defaults["global_last_save_folder"]
  2993. if loc is None:
  2994. loc = self.defaults["global_last_folder"]
  2995. if loc is None:
  2996. loc = os.path.dirname(__file__)
  2997. return loc
  2998. def report_usage(self, resource):
  2999. """
  3000. Increments usage counter for the given resource
  3001. in self.defaults['global_stats'].
  3002. :param resource: Name of the resource.
  3003. :return: None
  3004. """
  3005. if resource in self.defaults['global_stats']:
  3006. self.defaults['global_stats'][resource] += 1
  3007. else:
  3008. self.defaults['global_stats'][resource] = 1
  3009. def init_tcl(self):
  3010. """
  3011. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  3012. :return: None
  3013. """
  3014. if hasattr(self, 'tcl') and self.tcl is not None:
  3015. # self.tcl = None
  3016. # TODO we need to clean non default variables and procedures here
  3017. # new object cannot be used here as it will not remember values created for next passes,
  3018. # because tcl was execudted in old instance of TCL
  3019. pass
  3020. else:
  3021. self.tcl = tk.Tcl()
  3022. self.setup_shell()
  3023. self.log.debug("TCL Shell has been initialized.")
  3024. # TODO: This shouldn't be here.
  3025. class TclErrorException(Exception):
  3026. """
  3027. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  3028. """
  3029. pass
  3030. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  3031. """
  3032. Shows a message on the FlatCAM Shell
  3033. :param msg: Message to display.
  3034. :param show: Opens the shell.
  3035. :param error: Shows the message as an error.
  3036. :param warning: Shows the message as an warning.
  3037. :param success: Shows the message as an success.
  3038. :param selected: Indicate that something was selected on canvas
  3039. :return: None
  3040. """
  3041. if show:
  3042. self.ui.shell_dock.show()
  3043. try:
  3044. if error:
  3045. self.shell.append_error(msg + "\n")
  3046. elif warning:
  3047. self.shell.append_warning(msg + "\n")
  3048. elif success:
  3049. self.shell.append_success(msg + "\n")
  3050. elif selected:
  3051. self.shell.append_selected(msg + "\n")
  3052. else:
  3053. self.shell.append_output(msg + "\n")
  3054. except AttributeError:
  3055. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  3056. def raise_tcl_unknown_error(self, unknownException):
  3057. """
  3058. Raise exception if is different type than TclErrorException
  3059. this is here mainly to show unknown errors inside TCL shell console.
  3060. :param unknownException:
  3061. :return:
  3062. """
  3063. if not isinstance(unknownException, self.TclErrorException):
  3064. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  3065. else:
  3066. raise unknownException
  3067. def display_tcl_error(self, error, error_info=None):
  3068. """
  3069. Escape bracket [ with '\' otherwise there is error
  3070. "ERROR: missing close-bracket" instead of real error
  3071. :param error: it may be text or exception
  3072. :param error_info: Some informations about the error
  3073. :return: None
  3074. """
  3075. if isinstance(error, Exception):
  3076. exc_type, exc_value, exc_traceback = error_info
  3077. if not isinstance(error, self.TclErrorException):
  3078. show_trace = 1
  3079. else:
  3080. show_trace = int(self.defaults['global_verbose_error_level'])
  3081. if show_trace > 0:
  3082. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  3083. trc_formated = []
  3084. for a in reversed(trc):
  3085. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  3086. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  3087. else:
  3088. text = "%s" % error
  3089. else:
  3090. text = error
  3091. text = text.replace('[', '\\[').replace('"', '\\"')
  3092. self.tcl.eval('return -code error "%s"' % text)
  3093. def raise_tcl_error(self, text):
  3094. """
  3095. This method pass exception from python into TCL as error, so we get stacktrace and reason
  3096. :param text: text of error
  3097. :return: raise exception
  3098. """
  3099. self.display_tcl_error(text)
  3100. raise self.TclErrorException(text)
  3101. def exec_command(self, text, no_echo=False):
  3102. """
  3103. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3104. Also handles execution in separated threads
  3105. :param text: FlatCAM TclCommand with parameters
  3106. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3107. will create crashes of the _Expandable_Edit widget
  3108. :return: output if there was any
  3109. """
  3110. self.report_usage('exec_command')
  3111. result = self.exec_command_test(text, False, no_echo=no_echo)
  3112. # MS: added this method call so the geometry is updated once the TCL command is executed
  3113. # if no_plot is None:
  3114. # self.plot_all()
  3115. return result
  3116. def exec_command_test(self, text, reraise=True, no_echo=False):
  3117. """
  3118. Same as exec_command(...) with additional control over exceptions.
  3119. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3120. :param text: Input command
  3121. :param reraise: Re-raise TclError exceptions in Python (mostly for unittests).
  3122. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3123. will create crashes of the _Expandable_Edit widget
  3124. :return: Output from the command
  3125. """
  3126. tcl_command_string = str(text)
  3127. try:
  3128. if no_echo is False:
  3129. self.shell.open_processing() # Disables input box.
  3130. result = self.tcl.eval(str(tcl_command_string))
  3131. if result != 'None' and no_echo is False:
  3132. self.shell.append_output(result + '\n')
  3133. except tk.TclError as e:
  3134. # This will display more precise answer if something in TCL shell fails
  3135. result = self.tcl.eval("set errorInfo")
  3136. self.log.error("Exec command Exception: %s" % (result + '\n'))
  3137. if no_echo is False:
  3138. self.shell.append_error('ERROR: ' + result + '\n')
  3139. # Show error in console and just return or in test raise exception
  3140. if reraise:
  3141. raise e
  3142. finally:
  3143. if no_echo is False:
  3144. self.shell.close_processing()
  3145. pass
  3146. return result
  3147. # """
  3148. # Code below is unsused. Saved for later.
  3149. # """
  3150. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3151. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3152. # self.log.debug(parts)
  3153. # try:
  3154. # if parts[0] not in commands:
  3155. # self.shell.append_error("Unknown command\n")
  3156. # return
  3157. #
  3158. # #import inspect
  3159. # #inspect.getargspec(someMethod)
  3160. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3161. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3162. # self.shell.append_error(
  3163. # "Command %s takes %d arguments. %d given.\n" %
  3164. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3165. # )
  3166. # return
  3167. #
  3168. # cmdfcn = commands[parts[0]]["fcn"]
  3169. # cmdconv = commands[parts[0]]["converters"]
  3170. # if len(parts) - 1 > 0:
  3171. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3172. # else:
  3173. # retval = cmdfcn()
  3174. # retfcn = commands[parts[0]]["retfcn"]
  3175. # if retval and retfcn(retval):
  3176. # self.shell.append_output(retfcn(retval) + "\n")
  3177. #
  3178. # except Exception as e:
  3179. # #self.shell.append_error(''.join(traceback.format_exc()))
  3180. # #self.shell.append_error("?\n")
  3181. # self.shell.append_error(str(e) + "\n")
  3182. def info(self, msg):
  3183. """
  3184. Informs the user. Normally on the status bar, optionally
  3185. also on the shell.
  3186. :param msg: Text to write.
  3187. :return: None
  3188. """
  3189. # Type of message in brackets at the beginning of the message.
  3190. match = re.search("\[([^\]]+)\](.*)", msg)
  3191. if match:
  3192. level = match.group(1)
  3193. msg_ = match.group(2)
  3194. self.ui.fcinfo.set_status(str(msg_), level=level)
  3195. if level.lower() == "error":
  3196. self.shell_message(msg, error=True, show=True)
  3197. elif level.lower() == "warning":
  3198. self.shell_message(msg, warning=True, show=True)
  3199. elif level.lower() == "error_notcl":
  3200. self.shell_message(msg, error=True, show=False)
  3201. elif level.lower() == "warning_notcl":
  3202. self.shell_message(msg, warning=True, show=False)
  3203. elif level.lower() == "success":
  3204. self.shell_message(msg, success=True, show=False)
  3205. elif level.lower() == "selected":
  3206. self.shell_message(msg, selected=True, show=False)
  3207. else:
  3208. self.shell_message(msg, show=False)
  3209. else:
  3210. self.ui.fcinfo.set_status(str(msg), level="info")
  3211. # make sure that if the message is to clear the infobar with a space
  3212. # is not printed over and over on the shell
  3213. if msg != '':
  3214. self.shell_message(msg)
  3215. def restore_toolbar_view(self):
  3216. """
  3217. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3218. was saved in the defaults dictionary.
  3219. :return: None
  3220. """
  3221. tb = self.defaults["global_toolbar_view"]
  3222. if tb & 1:
  3223. self.ui.toolbarfile.setVisible(True)
  3224. else:
  3225. self.ui.toolbarfile.setVisible(False)
  3226. if tb & 2:
  3227. self.ui.toolbargeo.setVisible(True)
  3228. else:
  3229. self.ui.toolbargeo.setVisible(False)
  3230. if tb & 4:
  3231. self.ui.toolbarview.setVisible(True)
  3232. else:
  3233. self.ui.toolbarview.setVisible(False)
  3234. if tb & 8:
  3235. self.ui.toolbartools.setVisible(True)
  3236. else:
  3237. self.ui.toolbartools.setVisible(False)
  3238. if tb & 16:
  3239. self.ui.exc_edit_toolbar.setVisible(True)
  3240. else:
  3241. self.ui.exc_edit_toolbar.setVisible(False)
  3242. if tb & 32:
  3243. self.ui.geo_edit_toolbar.setVisible(True)
  3244. else:
  3245. self.ui.geo_edit_toolbar.setVisible(False)
  3246. if tb & 64:
  3247. self.ui.grb_edit_toolbar.setVisible(True)
  3248. else:
  3249. self.ui.grb_edit_toolbar.setVisible(False)
  3250. if tb & 128:
  3251. self.ui.snap_toolbar.setVisible(True)
  3252. else:
  3253. self.ui.snap_toolbar.setVisible(False)
  3254. if tb & 256:
  3255. self.ui.toolbarshell.setVisible(True)
  3256. else:
  3257. self.ui.toolbarshell.setVisible(False)
  3258. def load_defaults(self, filename):
  3259. """
  3260. Loads the aplication's default settings from current_defaults.FlatConfig into
  3261. ``self.defaults``.
  3262. :return: None
  3263. """
  3264. try:
  3265. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3266. options = f.read()
  3267. f.close()
  3268. except IOError:
  3269. self.log.error("Could not load defaults file.")
  3270. self.inform.emit('[ERROR] %s' % _("Could not load defaults file."))
  3271. # in case the defaults file can't be loaded, show all toolbars
  3272. self.defaults["global_toolbar_view"] = 511
  3273. return
  3274. try:
  3275. defaults = json.loads(options)
  3276. except Exception:
  3277. # in case the defaults file can't be loaded, show all toolbars
  3278. self.defaults["global_toolbar_view"] = 511
  3279. e = sys.exc_info()[0]
  3280. App.log.error(str(e))
  3281. self.inform.emit('[ERROR] %s' % _("Failed to parse defaults file."))
  3282. return
  3283. if defaults:
  3284. if 'version' not in defaults or defaults['version'] != self.defaults['version']:
  3285. for k, v in defaults.items():
  3286. if k in self.defaults and k != 'version':
  3287. self.defaults[k] = v
  3288. # delete old factory defaults
  3289. try:
  3290. fact_def_file_path = os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  3291. os.chmod(fact_def_file_path, stat.S_IRWXO | stat.S_IWRITE | stat.S_IWGRP)
  3292. os.remove(fact_def_file_path)
  3293. # recreate a new factory defaults file and save the factory defaults data into it
  3294. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  3295. json.dump(self.defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3296. f_f_def_s.close()
  3297. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  3298. os.chmod(fact_def_file_path, S_IREAD | S_IRGRP | S_IROTH)
  3299. except Exception as e:
  3300. log.debug("App.load_defaults() -> deleting old factory defaults file -> %s" % str(e))
  3301. self.old_defaults_found = True
  3302. else:
  3303. self.old_defaults_found = False
  3304. self.defaults.update(defaults)
  3305. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3306. def on_restore_defaults_preferences(self):
  3307. """
  3308. Loads the application's factory default settings from factory_defaults.FlatConfig into
  3309. ``self.defaults``.
  3310. :return: None
  3311. """
  3312. App.log.debug("App.on_restore_defaults_preferences()")
  3313. filename = self.data_path + '/factory_defaults.FlatConfig'
  3314. if filename == "":
  3315. self.inform.emit('[WARNING_NOTCL] %s' % _("Preferences default restore was cancelled."))
  3316. else:
  3317. try:
  3318. f = open(filename)
  3319. options = f.read()
  3320. f.close()
  3321. except IOError:
  3322. self.log.error("Could not load factory defaults file.")
  3323. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  3324. return
  3325. try:
  3326. defaults_from_file = json.loads(options)
  3327. except Exception:
  3328. e = sys.exc_info()[0]
  3329. App.log.error(str(e))
  3330. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  3331. return
  3332. self.defaults.update(defaults_from_file)
  3333. # update the dict that is used to restore the values in the defaults form if Cancel is clicked in the
  3334. # Preferences window
  3335. self.current_defaults.update(defaults_from_file)
  3336. self.on_preferences_edited()
  3337. self.inform.emit('[success] %s' % _("Preferences default values are restored."))
  3338. def on_import_preferences(self):
  3339. """
  3340. Loads the application default settings from a saved file into
  3341. ``self.defaults`` dictionary.
  3342. :return: None
  3343. """
  3344. self.report_usage("on_import_preferences")
  3345. App.log.debug("App.on_import_preferences()")
  3346. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3347. try:
  3348. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3349. directory=self.data_path,
  3350. filter=filter_)
  3351. except TypeError:
  3352. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3353. filter=filter_)
  3354. filename = str(filename)
  3355. if filename == "":
  3356. self.inform.emit('[WARNING_NOTCL] %s' % _("FlatCAM preferences import cancelled."))
  3357. else:
  3358. try:
  3359. f = open(filename)
  3360. options = f.read()
  3361. f.close()
  3362. except IOError:
  3363. self.log.error("Could not load defaults file.")
  3364. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  3365. return
  3366. try:
  3367. defaults_from_file = json.loads(options)
  3368. except Exception:
  3369. e = sys.exc_info()[0]
  3370. App.log.error(str(e))
  3371. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  3372. return
  3373. self.defaults.update(defaults_from_file)
  3374. # update the dict that is used to restore the values in the defaults form if Cancel is clicked in the
  3375. # Preferences window
  3376. self.current_defaults.update(defaults_from_file)
  3377. self.on_preferences_edited()
  3378. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  3379. def on_export_preferences(self):
  3380. """
  3381. Save the defaults dictionary to a file.
  3382. :return: None
  3383. """
  3384. self.report_usage("on_export_preferences")
  3385. App.log.debug("on_export_preferences()")
  3386. defaults_file_content = None
  3387. self.date = str(datetime.today()).rpartition('.')[0]
  3388. self.date = ''.join(c for c in self.date if c not in ':-')
  3389. self.date = self.date.replace(' ', '_')
  3390. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3391. try:
  3392. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3393. caption=_("Export FlatCAM Preferences"),
  3394. directory=self.data_path + '/preferences_' + self.date,
  3395. filter=filter__
  3396. )
  3397. except TypeError:
  3398. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3399. filter=filter__)
  3400. filename = str(filename)
  3401. defaults_from_file = {}
  3402. if filename == "":
  3403. self.inform.emit('[WARNING_NOTCL] %s' % _("FlatCAM preferences export cancelled."))
  3404. return
  3405. else:
  3406. try:
  3407. f = open(filename, 'w')
  3408. defaults_file_content = f.read()
  3409. f.close()
  3410. except PermissionError:
  3411. self.inform.emit('[WARNING] %s' %
  3412. _("Permission denied, saving not possible.\n"
  3413. "Most likely another app is holding the file open and not accessible."))
  3414. return
  3415. except IOError:
  3416. App.log.debug('Creating a new preferences file ...')
  3417. f = open(filename, 'w')
  3418. json.dump({}, f)
  3419. f.close()
  3420. except Exception:
  3421. e = sys.exc_info()[0]
  3422. App.log.error("Could not load defaults file.")
  3423. App.log.error(str(e))
  3424. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load preferences file."))
  3425. return
  3426. try:
  3427. defaults_from_file = json.loads(defaults_file_content)
  3428. except Exception:
  3429. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3430. # Update options
  3431. self.defaults_read_form()
  3432. defaults_from_file.update(self.defaults)
  3433. self.propagate_defaults(silent=True)
  3434. # Save update options
  3435. try:
  3436. f = open(filename, "w")
  3437. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3438. f.close()
  3439. except Exception:
  3440. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  3441. return
  3442. if self.defaults["global_open_style"] is False:
  3443. self.file_opened.emit("preferences", filename)
  3444. self.file_saved.emit("preferences", filename)
  3445. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  3446. def save_geometry(self, x, y, width, height, notebook_width):
  3447. """
  3448. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3449. launch of the application.
  3450. :param x: X position of the main window
  3451. :param y: Y position of the main window
  3452. :param width: width of the main window
  3453. :param height: height of the main window
  3454. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3455. :return: None
  3456. """
  3457. self.defaults["global_def_win_x"] = x
  3458. self.defaults["global_def_win_y"] = y
  3459. self.defaults["global_def_win_w"] = width
  3460. self.defaults["global_def_win_h"] = height
  3461. self.defaults["global_def_notebook_width"] = notebook_width
  3462. self.save_defaults()
  3463. def restore_main_win_geom(self):
  3464. try:
  3465. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3466. self.defaults["global_def_win_y"],
  3467. self.defaults["global_def_win_w"],
  3468. self.defaults["global_def_win_h"])
  3469. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3470. except KeyError as e:
  3471. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3472. def message_dialog(self, title, message, kind="info"):
  3473. """
  3474. Builds and show a custom QMessageBox to be used in FlatCAM.
  3475. :param title: title of the QMessageBox
  3476. :param message: message to be displayed
  3477. :param kind: type of QMessageBox; will display a specific icon.
  3478. :return:
  3479. """
  3480. icon = {"info": QtWidgets.QMessageBox.Information,
  3481. "warning": QtWidgets.QMessageBox.Warning,
  3482. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3483. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3484. dlg.setText(message)
  3485. dlg.exec_()
  3486. def register_recent(self, kind, filename):
  3487. """
  3488. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3489. dictionary.
  3490. :param kind: type of file that was opened
  3491. :param filename: the path and file name for the file that was opened
  3492. :return:
  3493. """
  3494. self.log.debug("register_recent()")
  3495. self.log.debug(" %s" % kind)
  3496. self.log.debug(" %s" % filename)
  3497. record = {'kind': str(kind), 'filename': str(filename)}
  3498. if record in self.recent:
  3499. return
  3500. if record in self.recent_projects:
  3501. return
  3502. if record['kind'] == 'project':
  3503. self.recent_projects.insert(0, record)
  3504. else:
  3505. self.recent.insert(0, record)
  3506. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3507. self.recent.pop()
  3508. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3509. self.recent_projects.pop()
  3510. try:
  3511. f = open(self.data_path + '/recent.json', 'w')
  3512. except IOError:
  3513. App.log.error("Failed to open recent items file for writing.")
  3514. self.inform.emit('[ERROR_NOTCL] %s' %
  3515. _('Failed to open recent files file for writing.'))
  3516. return
  3517. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3518. f.close()
  3519. try:
  3520. fp = open(self.data_path + '/recent_projects.json', 'w')
  3521. except IOError:
  3522. App.log.error("Failed to open recent items file for writing.")
  3523. self.inform.emit('[ERROR_NOTCL] %s' %
  3524. _('Failed to open recent projects file for writing.'))
  3525. return
  3526. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3527. fp.close()
  3528. # Re-build the recent items menu
  3529. self.setup_recent_items()
  3530. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3531. """
  3532. Creates a new specialized FlatCAMObj and attaches it to the application,
  3533. this is, updates the GUI accordingly, any other records and plots it.
  3534. This method is thread-safe.
  3535. Notes:
  3536. * If the name is in use, the self.collection will modify it
  3537. when appending it to the collection. There is no need to handle
  3538. name conflicts here.
  3539. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3540. :type kind: str
  3541. :param name: Name for the object.
  3542. :type name: str
  3543. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3544. The function is called with 2 parameters: the new object and the App instance.
  3545. :type initialize: function
  3546. :param active:
  3547. :param fit:
  3548. :param plot: If to plot the resulting object
  3549. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3550. self.colleaction
  3551. :return: None
  3552. :rtype: None
  3553. """
  3554. App.log.debug("new_object()")
  3555. obj_plot = plot
  3556. obj_autoselected = autoselected
  3557. t0 = time.time() # Debug
  3558. # ## Create object
  3559. classdict = {
  3560. "gerber": FlatCAMGerber,
  3561. "excellon": FlatCAMExcellon,
  3562. "cncjob": FlatCAMCNCjob,
  3563. "geometry": FlatCAMGeometry,
  3564. "script": FlatCAMScript,
  3565. "document": FlatCAMDocument
  3566. }
  3567. App.log.debug("Calling object constructor...")
  3568. # Object creation/instantiation
  3569. obj = classdict[kind](name)
  3570. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3571. # IMPORTANT
  3572. # The key names in defaults and options dictionary's are not random:
  3573. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3574. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  3575. # copied to self.options. After that, below, depending on the type of
  3576. # object that is created, it will strip the name of the object and the underline (if the original key was
  3577. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3578. # "toolchange"
  3579. for option in self.options:
  3580. if option.find(kind + "_") == 0:
  3581. oname = option[len(kind) + 1:]
  3582. obj.options[oname] = self.options[option]
  3583. obj.isHovering = False
  3584. obj.notHovering = True
  3585. # Initialize as per user request
  3586. # User must take care to implement initialize
  3587. # in a thread-safe way as is is likely that we
  3588. # have been invoked in a separate thread.
  3589. t1 = time.time()
  3590. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3591. try:
  3592. return_value = initialize(obj, self)
  3593. except Exception as e:
  3594. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  3595. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3596. msg += traceback.format_exc()
  3597. self.inform.emit(msg)
  3598. return "fail"
  3599. t2 = time.time()
  3600. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3601. if return_value == 'fail':
  3602. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3603. return "fail"
  3604. # Check units and convert if necessary
  3605. # This condition CAN be true because initialize() can change obj.units
  3606. if self.options["units"].upper() != obj.units.upper():
  3607. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  3608. obj.convert_units(self.options["units"])
  3609. t3 = time.time()
  3610. self.log.debug("%f seconds converting units." % (t3 - t2))
  3611. # Create the bounding box for the object and then add the results to the obj.options
  3612. # But not for Scripts or for Documents
  3613. if kind != 'document' and kind != 'script':
  3614. try:
  3615. xmin, ymin, xmax, ymax = obj.bounds()
  3616. obj.options['xmin'] = xmin
  3617. obj.options['ymin'] = ymin
  3618. obj.options['xmax'] = xmax
  3619. obj.options['ymax'] = ymax
  3620. except Exception as e:
  3621. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  3622. return "fail"
  3623. try:
  3624. if kind == 'excellon':
  3625. obj.fill_color = self.app.defaults["excellon_plot_fill"]
  3626. obj.outline_color = self.app.defaults["excellon_plot_line"]
  3627. if kind == 'gerber':
  3628. obj.fill_color = self.app.defaults["gerber_plot_fill"]
  3629. obj.outline_color = self.app.defaults["gerber_plot_line"]
  3630. except Exception as e:
  3631. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  3632. # update the KeyWords list with the name of the file
  3633. self.myKeywords.append(obj.options['name'])
  3634. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3635. # Move the object to the main thread and let the app know that it is available.
  3636. obj.moveToThread(self.main_thread)
  3637. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3638. return obj
  3639. def new_excellon_object(self):
  3640. """
  3641. Creates a new, blank Excellon object.
  3642. :return: None
  3643. """
  3644. self.report_usage("new_excellon_object()")
  3645. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3646. def new_geometry_object(self):
  3647. """
  3648. Creates a new, blank and single-tool Geometry object.
  3649. :return: None
  3650. """
  3651. self.report_usage("new_geometry_object()")
  3652. def initialize(obj, app):
  3653. obj.multitool = False
  3654. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3655. def new_gerber_object(self):
  3656. """
  3657. Creates a new, blank Gerber object.
  3658. :return: None
  3659. """
  3660. self.report_usage("new_gerber_object()")
  3661. def initialize(grb_obj, app):
  3662. grb_obj.multitool = False
  3663. grb_obj.source_file = []
  3664. grb_obj.multigeo = False
  3665. grb_obj.follow = False
  3666. grb_obj.apertures = {}
  3667. grb_obj.solid_geometry = []
  3668. try:
  3669. grb_obj.options['xmin'] = 0
  3670. grb_obj.options['ymin'] = 0
  3671. grb_obj.options['xmax'] = 0
  3672. grb_obj.options['ymax'] = 0
  3673. except KeyError:
  3674. pass
  3675. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3676. def new_script_object(self, name=None, text=None):
  3677. """
  3678. Creates a new, blank TCL Script object.
  3679. :param name: a name for the new object
  3680. :param text: pass a source file to the newly created script to be loaded in it
  3681. :return: None
  3682. """
  3683. self.report_usage("new_script_object()")
  3684. if text is not None:
  3685. new_source_file = text
  3686. else:
  3687. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3688. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n"\
  3689. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  3690. "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n"\
  3691. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3692. "ListSys, MillDrills,\n"\
  3693. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3694. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"\
  3695. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3696. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3697. "# SubtractRectangle, Version, WriteGCode\n"
  3698. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3699. '# %s:\n' % _('TCL Tutorial is here') + \
  3700. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3701. '# %s:\n' % _("FlatCAM commands list")
  3702. new_source_file += commands_list + '\n'
  3703. def initialize(obj, app):
  3704. obj.source_file = deepcopy(new_source_file)
  3705. if name is None:
  3706. outname = 'new_script'
  3707. else:
  3708. outname = name
  3709. self.new_object('script', outname, initialize, plot=False)
  3710. def new_document_object(self):
  3711. """
  3712. Creates a new, blank Document object.
  3713. :return: None
  3714. """
  3715. self.report_usage("new_document_object()")
  3716. def initialize(obj, app):
  3717. obj.source_file = ""
  3718. self.new_object('document', 'new_document', initialize, plot=False)
  3719. def on_object_created(self, obj, plot, auto_select):
  3720. """
  3721. Event callback for object creation.
  3722. It will add the new object to the collection. After that it will plot the object in a threaded way
  3723. :param obj: The newly created FlatCAM object.
  3724. :param plot: if the newly create object t obe plotted
  3725. :param auto_select: if the newly created object to be autoselected after creation
  3726. :return: None
  3727. """
  3728. t0 = time.time() # DEBUG
  3729. self.log.debug("on_object_created()")
  3730. # The Collection might change the name if there is a collision
  3731. self.collection.append(obj)
  3732. # after adding the object to the collection always update the list of objects that are in the collection
  3733. self.all_objects_list = self.collection.get_list()
  3734. # self.inform.emit('[selected] %s created & selected: %s' %
  3735. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3736. if obj.kind == 'gerber':
  3737. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3738. kind=obj.kind.capitalize(),
  3739. color='green',
  3740. name=str(obj.options['name']), tx=_("created/selected"))
  3741. )
  3742. elif obj.kind == 'excellon':
  3743. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3744. kind=obj.kind.capitalize(),
  3745. color='brown',
  3746. name=str(obj.options['name']), tx=_("created/selected"))
  3747. )
  3748. elif obj.kind == 'cncjob':
  3749. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3750. kind=obj.kind.capitalize(),
  3751. color='blue',
  3752. name=str(obj.options['name']), tx=_("created/selected"))
  3753. )
  3754. elif obj.kind == 'geometry':
  3755. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3756. kind=obj.kind.capitalize(),
  3757. color='red',
  3758. name=str(obj.options['name']), tx=_("created/selected"))
  3759. )
  3760. elif obj.kind == 'script':
  3761. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3762. kind=obj.kind.capitalize(),
  3763. color='orange',
  3764. name=str(obj.options['name']), tx=_("created/selected"))
  3765. )
  3766. elif obj.kind == 'document':
  3767. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3768. kind=obj.kind.capitalize(),
  3769. color='darkCyan',
  3770. name=str(obj.options['name']), tx=_("created/selected"))
  3771. )
  3772. # update the SHELL auto-completer model with the name of the new object
  3773. self.shell._edit.set_model_data(self.myKeywords)
  3774. if auto_select:
  3775. # select the just opened object but deselect the previous ones
  3776. self.collection.set_all_inactive()
  3777. self.collection.set_active(obj.options["name"])
  3778. else:
  3779. self.collection.set_all_inactive()
  3780. # here it is done the object plotting
  3781. def worker_task(t_obj):
  3782. with self.proc_container.new(_("Plotting")):
  3783. if isinstance(t_obj, FlatCAMCNCjob):
  3784. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3785. else:
  3786. t_obj.plot()
  3787. t1 = time.time() # DEBUG
  3788. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3789. self.object_plotted.emit(t_obj)
  3790. # Send to worker
  3791. # self.worker.add_task(worker_task, [self])
  3792. if plot is True:
  3793. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3794. def on_object_changed(self, obj):
  3795. """
  3796. Called whenever the geometry of the object was changed in some way.
  3797. This require the update of it's bounding values so it can be the selected on canvas.
  3798. Update the bounding box data from obj.options
  3799. :param obj: the object that was changed
  3800. :return: None
  3801. """
  3802. xmin, ymin, xmax, ymax = obj.bounds()
  3803. obj.options['xmin'] = xmin
  3804. obj.options['ymin'] = ymin
  3805. obj.options['xmax'] = xmax
  3806. obj.options['ymax'] = ymax
  3807. log.debug("Object changed, updating the bounding box data on self.options")
  3808. # delete the old selection shape
  3809. self.delete_selection_shape()
  3810. self.should_we_save = True
  3811. def on_object_plotted(self):
  3812. """
  3813. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3814. :return: None
  3815. """
  3816. self.on_zoom_fit(None)
  3817. def on_about(self):
  3818. """
  3819. Displays the "about" dialog found in the Menu --> Help.
  3820. :return: None
  3821. """
  3822. self.report_usage("on_about")
  3823. version = self.version
  3824. version_date = self.version_date
  3825. beta = self.beta
  3826. class AboutDialog(QtWidgets.QDialog):
  3827. def __init__(self, app, parent=None):
  3828. QtWidgets.QDialog.__init__(self, parent)
  3829. self.app = app
  3830. # Icon and title
  3831. self.setWindowIcon(parent.app_icon)
  3832. self.setWindowTitle(_("About FlatCAM"))
  3833. self.resize(600, 200)
  3834. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3835. # self.setStyleSheet(
  3836. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3837. # "background-attachment: fixed"
  3838. # )
  3839. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  3840. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3841. # palette = QtGui.QPalette()
  3842. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3843. # self.setPalette(palette)
  3844. logo = QtWidgets.QLabel()
  3845. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  3846. title = QtWidgets.QLabel(
  3847. "<font size=8><B>FlatCAM</B></font><BR>"
  3848. "{title}<BR>"
  3849. "<BR>"
  3850. "<BR>"
  3851. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3852. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3853. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3854. "<B>{issue}</B></a><BR>".format(
  3855. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3856. devel=_("Development"),
  3857. down=_("DOWNLOAD"),
  3858. issue=_("Issue tracker"))
  3859. )
  3860. title.setOpenExternalLinks(True)
  3861. closebtn = QtWidgets.QPushButton(_("Close"))
  3862. tab_widget = QtWidgets.QTabWidget()
  3863. description_label = QtWidgets.QLabel(
  3864. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3865. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3866. version=version,
  3867. beta=('BETA' if beta else ''),
  3868. date=version_date,
  3869. arch=platform.architecture()[0])
  3870. )
  3871. description_label.setOpenExternalLinks(True)
  3872. lic_lbl_header = QtWidgets.QLabel(
  3873. '%s:<br>%s<br>' % (
  3874. _('Licensed under the MIT license'),
  3875. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3876. "http://www.opensource.org/licenses/mit-license.php</a>"
  3877. )
  3878. )
  3879. lic_lbl_header.setOpenExternalLinks(True)
  3880. lic_lbl_body = QtWidgets.QLabel(
  3881. _(
  3882. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3883. 'of this software and associated documentation files (the "Software"), to deal\n'
  3884. 'in the Software without restriction, including without limitation the rights\n'
  3885. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3886. 'copies of the Software, and to permit persons to whom the Software is\n'
  3887. 'furnished to do so, subject to the following conditions:\n\n'
  3888. 'The above copyright notice and this permission notice shall be included in\n'
  3889. 'all copies or substantial portions of the Software.\n\n'
  3890. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3891. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3892. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3893. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3894. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3895. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3896. 'THE SOFTWARE.'
  3897. )
  3898. )
  3899. attributions_label = QtWidgets.QLabel(
  3900. _(
  3901. 'Some of the icons used are from the following sources:<br>'
  3902. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  3903. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3904. 'title="Flaticon">www.flaticon.com</a></div>'
  3905. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  3906. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  3907. )
  3908. )
  3909. # layouts
  3910. layout1 = QtWidgets.QVBoxLayout()
  3911. layout1_1 = QtWidgets.QHBoxLayout()
  3912. layout1_2 = QtWidgets.QHBoxLayout()
  3913. layout2 = QtWidgets.QHBoxLayout()
  3914. layout3 = QtWidgets.QHBoxLayout()
  3915. self.setLayout(layout1)
  3916. layout1.addLayout(layout1_1)
  3917. layout1.addLayout(layout1_2)
  3918. layout1.addLayout(layout2)
  3919. layout1.addLayout(layout3)
  3920. layout1_1.addStretch()
  3921. layout1_1.addWidget(description_label)
  3922. layout1_2.addWidget(tab_widget)
  3923. self.splash_tab = QtWidgets.QWidget()
  3924. self.splash_tab.setObjectName("splash_about")
  3925. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3926. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3927. tab_widget.addTab(self.splash_tab, _("Splash"))
  3928. self.programmmers_tab = QtWidgets.QWidget()
  3929. self.programmmers_tab.setObjectName("programmers_about")
  3930. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3931. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3932. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3933. self.translators_tab = QtWidgets.QWidget()
  3934. self.translators_tab.setObjectName("translators_about")
  3935. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3936. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3937. tab_widget.addTab(self.translators_tab, _("Translators"))
  3938. self.license_tab = QtWidgets.QWidget()
  3939. self.license_tab.setObjectName("license_about")
  3940. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3941. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3942. tab_widget.addTab(self.license_tab, _("License"))
  3943. self.attributions_tab = QtWidgets.QWidget()
  3944. self.attributions_tab.setObjectName("attributions_about")
  3945. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3946. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3947. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3948. self.splash_tab_layout.addWidget(logo, stretch=0)
  3949. self.splash_tab_layout.addWidget(title, stretch=1)
  3950. pal = QtGui.QPalette()
  3951. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3952. self.prog_grid_lay = QtWidgets.QGridLayout()
  3953. self.prog_grid_lay.setHorizontalSpacing(20)
  3954. self.prog_grid_lay.setColumnStretch(0, 0)
  3955. self.prog_grid_lay.setColumnStretch(2, 1)
  3956. prog_widget = QtWidgets.QWidget()
  3957. prog_widget.setLayout(self.prog_grid_lay)
  3958. prog_scroll = QtWidgets.QScrollArea()
  3959. prog_scroll.setWidget(prog_widget)
  3960. prog_scroll.setWidgetResizable(True)
  3961. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3962. prog_scroll.setPalette(pal)
  3963. self.programmmers_tab_layout.addWidget(prog_scroll)
  3964. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3965. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3966. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3967. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3968. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3969. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3970. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3971. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3972. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3973. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3974. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3975. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3976. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3977. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3978. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3979. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3980. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3981. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3982. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3983. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3984. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3985. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3986. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3987. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3988. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  3989. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  3990. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  3991. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  3992. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  3993. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  3994. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  3995. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  3996. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  3997. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  3998. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  3999. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 28, 0)
  4000. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 29, 0)
  4001. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 30, 0)
  4002. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 31, 0)
  4003. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 34, 0)
  4004. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  4005. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  4006. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  4007. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  4008. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  4009. self.translator_grid_lay = QtWidgets.QGridLayout()
  4010. self.translator_grid_lay.setColumnStretch(0, 0)
  4011. self.translator_grid_lay.setColumnStretch(1, 0)
  4012. self.translator_grid_lay.setColumnStretch(2, 1)
  4013. self.translator_grid_lay.setColumnStretch(3, 0)
  4014. # trans_widget = QtWidgets.QWidget()
  4015. # trans_widget.setLayout(self.translator_grid_lay)
  4016. # self.translators_tab_layout.addWidget(trans_widget)
  4017. # self.translators_tab_layout.addStretch()
  4018. trans_widget = QtWidgets.QWidget()
  4019. trans_widget.setLayout(self.translator_grid_lay)
  4020. trans_scroll = QtWidgets.QScrollArea()
  4021. trans_scroll.setWidget(trans_widget)
  4022. trans_scroll.setWidgetResizable(True)
  4023. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  4024. trans_scroll.setPalette(pal)
  4025. self.translators_tab_layout.addWidget(trans_scroll)
  4026. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  4027. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  4028. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  4029. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  4030. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  4031. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  4032. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  4033. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  4034. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  4035. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  4036. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  4037. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  4038. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  4039. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  4040. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  4041. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  4042. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  4043. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  4044. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  4045. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  4046. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  4047. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  4048. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  4049. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  4050. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  4051. self.translator_grid_lay.setColumnStretch(0, 0)
  4052. self.translators_tab_layout.addStretch()
  4053. self.license_tab_layout.addWidget(lic_lbl_header)
  4054. self.license_tab_layout.addWidget(lic_lbl_body)
  4055. self.license_tab_layout.addStretch()
  4056. self.attributions_tab_layout.addWidget(attributions_label)
  4057. self.attributions_tab_layout.addStretch()
  4058. layout3.addStretch()
  4059. layout3.addWidget(closebtn)
  4060. closebtn.clicked.connect(self.accept)
  4061. AboutDialog(app=self, parent=self.ui).exec_()
  4062. def install_bookmarks(self, book_dict=None):
  4063. """
  4064. Install the bookmarks actions in the Help menu -> Bookmarks
  4065. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  4066. :return: None
  4067. """
  4068. if book_dict is None:
  4069. self.defaults["global_bookmarks"].update(
  4070. {
  4071. '1': ['FlatCAM', "http://flatcam.org"],
  4072. '2': ['Backup Site', ""]
  4073. }
  4074. )
  4075. else:
  4076. self.defaults["global_bookmarks"].clear()
  4077. self.defaults["global_bookmarks"].update(book_dict)
  4078. # first try to disconnect if somehow they get connected from elsewhere
  4079. for act in self.ui.menuhelp_bookmarks.actions():
  4080. try:
  4081. act.triggered.disconnect()
  4082. except TypeError:
  4083. pass
  4084. # clear all actions except the last one who is the Bookmark manager
  4085. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  4086. pass
  4087. else:
  4088. self.ui.menuhelp_bookmarks.removeAction(act)
  4089. bm_limit = int(self.defaults["global_bookmarks_limit"])
  4090. if self.defaults["global_bookmarks"]:
  4091. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  4092. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  4093. # the JSON is first making the keys as strings (therefore I have to use strings too
  4094. # or do the conversion :(
  4095. # )
  4096. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  4097. # the '10' entry jsut after '1' therefore ordering as strings
  4098. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  4099. key=lambda x: int(x[0]))
  4100. for entry, bookmark in sorted_bookmarks:
  4101. title = bookmark[0]
  4102. weblink = bookmark[1]
  4103. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  4104. act.setText(title)
  4105. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  4106. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  4107. if title == 'Backup Site' and weblink == "":
  4108. act.triggered.connect(self.on_backup_site)
  4109. else:
  4110. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  4111. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  4112. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  4113. def on_bookmarks_manager(self):
  4114. """
  4115. Adds the bookmark manager in a Tab in Plot Area
  4116. :return:
  4117. """
  4118. for idx in range(self.ui.plot_tab_area.count()):
  4119. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  4120. # there can be only one instance of Bookmark Manager at one time
  4121. return
  4122. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  4123. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  4124. # add the tab if it was closed
  4125. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  4126. # delete the absolute and relative position and messages in the infobar
  4127. self.ui.position_label.setText("")
  4128. self.ui.rel_position_label.setText("")
  4129. # Switch plot_area to preferences page
  4130. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  4131. def on_backup_site(self):
  4132. msgbox = QtWidgets.QMessageBox()
  4133. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  4134. "1. FlatCAM.org website is down\n"
  4135. "2. Someone forked FlatCAM project and wants to point\n"
  4136. "to his own website\n\n"
  4137. "If you can't get any informations about FlatCAM beta\n"
  4138. "use the YouTube channel link from the Help menu."))
  4139. msgbox.setWindowTitle(_("Alternative website"))
  4140. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  4141. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  4142. msgbox.setDefaultButton(bt_yes)
  4143. msgbox.exec_()
  4144. # response = msgbox.clickedButton()
  4145. def on_file_savedefaults(self):
  4146. """
  4147. Callback for menu item File->Save Defaults. Saves application default options
  4148. ``self.defaults`` to current_defaults.FlatConfig.
  4149. :return: None
  4150. """
  4151. self.save_defaults()
  4152. # def on_app_exit(self):
  4153. # self.report_usage("on_app_exit()")
  4154. #
  4155. # if self.collection.get_list():
  4156. # msgbox = QtWidgets.QMessageBox()
  4157. # # msgbox.setText("<B>Save changes ...</B>")
  4158. # msgbox.setText("There are files/objects opened in FlatCAM. "
  4159. # "\n"
  4160. # "Do you want to Save the project?")
  4161. # msgbox.setWindowTitle("Save changes")
  4162. # msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4163. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  4164. # QtWidgets.QMessageBox.Cancel)
  4165. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  4166. #
  4167. # response = msgbox.exec_()
  4168. #
  4169. # if response == QtWidgets.QMessageBox.Yes:
  4170. # self.on_file_saveprojectas(thread=False)
  4171. # elif response == QtWidgets.QMessageBox.Cancel:
  4172. # return
  4173. # self.save_defaults()
  4174. # else:
  4175. # self.save_defaults()
  4176. # log.debug("Application defaults saved ... Exit event.")
  4177. # QtWidgets.qApp.quit()
  4178. def save_defaults(self, silent=False, data_path=None, first_time=False):
  4179. """
  4180. Saves application default options
  4181. ``self.defaults`` to current_defaults.FlatConfig file.
  4182. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  4183. used at the next launch of the application.
  4184. :param silent: whether to display a message in status bar or not; boolean
  4185. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  4186. When the application is portable it should be a mobile location.
  4187. :return: None
  4188. """
  4189. self.report_usage("save_defaults")
  4190. if data_path is None:
  4191. data_path = self.data_path
  4192. # Read options from file
  4193. try:
  4194. f = open(data_path + "/current_defaults.FlatConfig")
  4195. defaults_file_content = f.read()
  4196. f.close()
  4197. except Exception:
  4198. e = sys.exc_info()[0]
  4199. App.log.error("Could not load defaults file.")
  4200. App.log.error(str(e))
  4201. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  4202. return
  4203. try:
  4204. defaults = json.loads(defaults_file_content)
  4205. except Exception:
  4206. e = sys.exc_info()[0]
  4207. App.log.error("Failed to parse defaults file.")
  4208. App.log.error(str(e))
  4209. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  4210. return
  4211. # Update options
  4212. self.defaults_read_form()
  4213. defaults.update(self.defaults)
  4214. self.propagate_defaults(silent=True)
  4215. # Save the toolbar view
  4216. tb_status = 0
  4217. if self.ui.toolbarfile.isVisible():
  4218. tb_status += 1
  4219. if self.ui.toolbargeo.isVisible():
  4220. tb_status += 2
  4221. if self.ui.toolbarview.isVisible():
  4222. tb_status += 4
  4223. if self.ui.toolbartools.isVisible():
  4224. tb_status += 8
  4225. if self.ui.exc_edit_toolbar.isVisible():
  4226. tb_status += 16
  4227. if self.ui.geo_edit_toolbar.isVisible():
  4228. tb_status += 32
  4229. if self.ui.grb_edit_toolbar.isVisible():
  4230. tb_status += 64
  4231. if self.ui.snap_toolbar.isVisible():
  4232. tb_status += 128
  4233. if self.ui.toolbarshell.isVisible():
  4234. tb_status += 256
  4235. if first_time is False:
  4236. self.defaults["global_toolbar_view"] = tb_status
  4237. # Save update options
  4238. filename = data_path + "/current_defaults.FlatConfig"
  4239. try:
  4240. f = open(filename, "w")
  4241. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4242. f.close()
  4243. except Exception as e:
  4244. log.debug("App.save_defaults() --> %s" % str(e))
  4245. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  4246. return
  4247. if not silent:
  4248. self.inform.emit('[success] %s' % _("Preferences saved."))
  4249. def save_factory_defaults(self, silent_message=False, data_path=None):
  4250. """
  4251. Saves application factory default options
  4252. ``self.defaults`` to factory_defaults.FlatConfig.
  4253. It's a one time job done just after the first install.
  4254. :param silent_message: whether to display a message in status bar or not; boolean
  4255. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4256. When the application is portable it should be a mobile location.
  4257. :return: None
  4258. """
  4259. self.report_usage("save_factory_defaults")
  4260. if data_path is None:
  4261. data_path = self.data_path
  4262. # Read options from file
  4263. try:
  4264. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4265. factory_defaults_file_content = f_f_def.read()
  4266. f_f_def.close()
  4267. except Exception:
  4268. e = sys.exc_info()[0]
  4269. App.log.error("Could not load factory defaults file.")
  4270. App.log.error(str(e))
  4271. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  4272. return
  4273. try:
  4274. factory_defaults = json.loads(factory_defaults_file_content)
  4275. except Exception:
  4276. e = sys.exc_info()[0]
  4277. App.log.error("Failed to parse factory defaults file.")
  4278. App.log.error(str(e))
  4279. if silent_message is False:
  4280. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  4281. return
  4282. # Update options
  4283. self.defaults_read_form()
  4284. factory_defaults.update(self.defaults)
  4285. self.propagate_defaults(silent=True)
  4286. # Save update options
  4287. try:
  4288. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4289. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4290. f_f_def_s.close()
  4291. except Exception as e:
  4292. log.debug("App.save_factory_default() save update --> %s" % str(e))
  4293. if silent_message is False:
  4294. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write factory defaults to file."))
  4295. return
  4296. if silent_message is False:
  4297. self.inform.emit(_("Factory defaults saved."))
  4298. def final_save(self):
  4299. """
  4300. Callback for doing a preferences save to file whenever the application is about to quit.
  4301. If the project has changes, it will ask the user to save the project.
  4302. :return: None
  4303. """
  4304. if self.save_in_progress:
  4305. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  4306. return
  4307. if self.should_we_save and self.collection.get_list():
  4308. msgbox = QtWidgets.QMessageBox()
  4309. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4310. "\n"
  4311. "Do you want to Save the project?"))
  4312. msgbox.setWindowTitle(_("Save changes"))
  4313. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4314. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4315. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4316. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4317. msgbox.setDefaultButton(bt_yes)
  4318. msgbox.exec_()
  4319. response = msgbox.clickedButton()
  4320. if response == bt_yes:
  4321. try:
  4322. self.trayIcon.hide()
  4323. except Exception:
  4324. pass
  4325. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4326. elif response == bt_no:
  4327. try:
  4328. self.trayIcon.hide()
  4329. except Exception:
  4330. pass
  4331. self.quit_application()
  4332. elif response == bt_cancel:
  4333. return
  4334. else:
  4335. try:
  4336. self.trayIcon.hide()
  4337. except Exception:
  4338. pass
  4339. self.quit_application()
  4340. def quit_application(self):
  4341. """
  4342. Called (as a pyslot or not) when the application is quit.
  4343. :return: None
  4344. """
  4345. self.save_defaults(silent=True)
  4346. log.debug("App.final_save() --> App Defaults saved.")
  4347. if self.cmd_line_headless != 1:
  4348. # save app state to file
  4349. stgs = QSettings("Open Source", "FlatCAM")
  4350. stgs.setValue('saved_gui_state', self.ui.saveState())
  4351. stgs.setValue('maximized_gui', self.ui.isMaximized())
  4352. stgs.setValue(
  4353. 'language',
  4354. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  4355. )
  4356. stgs.setValue(
  4357. 'notebook_font_size',
  4358. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  4359. )
  4360. stgs.setValue(
  4361. 'axis_font_size',
  4362. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  4363. )
  4364. stgs.setValue(
  4365. 'textbox_font_size',
  4366. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  4367. )
  4368. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4369. stgs.setValue(
  4370. 'machinist',
  4371. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  4372. )
  4373. # This will write the setting to the platform specific storage.
  4374. del stgs
  4375. log.debug("App.final_save() --> App UI state saved.")
  4376. self.close_app_signal.emit()
  4377. def kill_app(self):
  4378. QtWidgets.qApp.quit()
  4379. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  4380. # we use the following command
  4381. sys.exit(0)
  4382. def on_portable_checked(self, state):
  4383. """
  4384. Callback called when the checkbox in Preferences GUI is checked.
  4385. It will set the application as portable by creating the preferences and recent files in the
  4386. 'config' folder found in the FlatCAM installation folder.
  4387. :param state: boolean, the state of the checkbox when clicked/checked
  4388. :return:
  4389. """
  4390. line_no = 0
  4391. data = None
  4392. if sys.platform != 'win32':
  4393. # this won't work in Linux or MacOS
  4394. return
  4395. # test if the app was frozen and choose the path for the configuration file
  4396. if getattr(sys, "frozen", False) is True:
  4397. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4398. else:
  4399. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4400. config_file = current_data_path + '\\configuration.txt'
  4401. try:
  4402. with open(config_file, 'r') as f:
  4403. try:
  4404. data = f.readlines()
  4405. except Exception as e:
  4406. log.debug('App.__init__() -->%s' % str(e))
  4407. return
  4408. except FileNotFoundError:
  4409. pass
  4410. for line in data:
  4411. line = line.strip('\n')
  4412. param = str(line).rpartition('=')
  4413. if param[0] == 'portable':
  4414. break
  4415. line_no += 1
  4416. if state:
  4417. data[line_no] = 'portable=True\n'
  4418. # create the new defauults files
  4419. # create current_defaults.FlatConfig file if there is none
  4420. try:
  4421. f = open(current_data_path + '/current_defaults.FlatConfig')
  4422. f.close()
  4423. except IOError:
  4424. App.log.debug('Creating empty current_defaults.FlatConfig')
  4425. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4426. json.dump({}, f)
  4427. f.close()
  4428. # create factory_defaults.FlatConfig file if there is none
  4429. try:
  4430. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4431. f.close()
  4432. except IOError:
  4433. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4434. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4435. json.dump({}, f)
  4436. f.close()
  4437. try:
  4438. f = open(current_data_path + '/recent.json')
  4439. f.close()
  4440. except IOError:
  4441. App.log.debug('Creating empty recent.json')
  4442. f = open(current_data_path + '/recent.json', 'w')
  4443. json.dump([], f)
  4444. f.close()
  4445. try:
  4446. fp = open(current_data_path + '/recent_projects.json')
  4447. fp.close()
  4448. except IOError:
  4449. App.log.debug('Creating empty recent_projects.json')
  4450. fp = open(current_data_path + '/recent_projects.json', 'w')
  4451. json.dump([], fp)
  4452. fp.close()
  4453. # save the current defaults to the new defaults file
  4454. self.save_defaults(silent=True, data_path=current_data_path)
  4455. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4456. else:
  4457. data[line_no] = 'portable=False\n'
  4458. with open(config_file, 'w') as f:
  4459. f.writelines(data)
  4460. def on_toggle_shell(self):
  4461. """
  4462. Toggle shell: if is visible close it, if it is closed then open it
  4463. :return: None
  4464. """
  4465. self.report_usage("on_toggle_shell()")
  4466. if self.ui.shell_dock.isVisible():
  4467. self.ui.shell_dock.hide()
  4468. else:
  4469. self.ui.shell_dock.show()
  4470. def on_register_files(self, obj_type=None):
  4471. """
  4472. Called whenever there is a need to register file extensions with FlatCAM.
  4473. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4474. :param obj_type: the type of object to be register for.
  4475. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4476. :return: None
  4477. """
  4478. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4479. new_reg_path = 'Software\\Classes\\'
  4480. # find if the current user is admin
  4481. try:
  4482. is_admin = os.getuid() == 0
  4483. except AttributeError:
  4484. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4485. if is_admin is True:
  4486. root_path = winreg.HKEY_LOCAL_MACHINE
  4487. else:
  4488. root_path = winreg.HKEY_CURRENT_USER
  4489. # create the keys
  4490. def set_reg(name, root_path, new_reg_path, value):
  4491. try:
  4492. winreg.CreateKey(root_path, new_reg_path)
  4493. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4494. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4495. return True
  4496. except WindowsError:
  4497. return False
  4498. # delete key in registry
  4499. def delete_reg(root_path, reg_path, key_to_del):
  4500. key_to_del_path = reg_path + key_to_del
  4501. try:
  4502. winreg.DeleteKey(root_path, key_to_del_path)
  4503. return True
  4504. except WindowsError:
  4505. return False
  4506. if obj_type is None or obj_type == 'excellon':
  4507. exc_list = \
  4508. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4509. exc_list = [x for x in exc_list if x != '']
  4510. # register all keys in the Preferences window
  4511. for ext in exc_list:
  4512. new_k = new_reg_path + '.%s' % ext
  4513. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4514. # and unregister those that are no longer in the Preferences windows but are in the file
  4515. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4516. if ext not in exc_list:
  4517. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4518. # now write the updated extensions to the self.defaults
  4519. # new_ext = ''
  4520. # for ext in exc_list:
  4521. # new_ext = new_ext + ext + ', '
  4522. # self.defaults["fa_excellon"] = new_ext
  4523. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4524. if obj_type is None or obj_type == 'gcode':
  4525. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4526. gco_list = [x for x in gco_list if x != '']
  4527. # register all keys in the Preferences window
  4528. for ext in gco_list:
  4529. new_k = new_reg_path + '.%s' % ext
  4530. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4531. # and unregister those that are no longer in the Preferences windows but are in the file
  4532. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4533. if ext not in gco_list:
  4534. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4535. # now write the updated extensions to the self.defaults
  4536. # new_ext = ''
  4537. # for ext in gco_list:
  4538. # new_ext = new_ext + ext + ', '
  4539. # self.defaults["fa_gcode"] = new_ext
  4540. self.inform.emit('[success] %s' %
  4541. _("Selected GCode file extensions registered with FlatCAM."))
  4542. if obj_type is None or obj_type == 'gerber':
  4543. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4544. grb_list = [x for x in grb_list if x != '']
  4545. # register all keys in the Preferences window
  4546. for ext in grb_list:
  4547. new_k = new_reg_path + '.%s' % ext
  4548. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4549. # and unregister those that are no longer in the Preferences windows but are in the file
  4550. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4551. if ext not in grb_list:
  4552. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4553. # now write the updated extensions to the self.defaults
  4554. # new_ext = ''
  4555. # for ext in grb_list:
  4556. # new_ext = new_ext + ext + ', '
  4557. # self.defaults["fa_gerber"] = new_ext
  4558. self.inform.emit('[success] %s' %
  4559. _("Selected Gerber file extensions registered with FlatCAM."))
  4560. def add_extension(self, ext_type):
  4561. """
  4562. Add a file extension to the list for a specific object
  4563. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4564. :return:
  4565. """
  4566. if ext_type == 'excellon':
  4567. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4568. if new_ext == '':
  4569. return
  4570. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4571. if new_ext in old_val:
  4572. return
  4573. old_val.append(new_ext)
  4574. old_val.sort()
  4575. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4576. if ext_type == 'gcode':
  4577. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4578. if new_ext == '':
  4579. return
  4580. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4581. if new_ext in old_val:
  4582. return
  4583. old_val.append(new_ext)
  4584. old_val.sort()
  4585. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4586. if ext_type == 'gerber':
  4587. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4588. if new_ext == '':
  4589. return
  4590. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4591. if new_ext in old_val:
  4592. return
  4593. old_val.append(new_ext)
  4594. old_val.sort()
  4595. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4596. if ext_type == 'keyword':
  4597. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4598. if new_kw == '':
  4599. return
  4600. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4601. if new_kw in old_val:
  4602. return
  4603. old_val.append(new_kw)
  4604. old_val.sort()
  4605. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4606. # update the self.myKeywords so the model is updated
  4607. self.autocomplete_kw_list = \
  4608. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4609. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4610. self.shell._edit.set_model_data(self.myKeywords)
  4611. def del_extension(self, ext_type):
  4612. """
  4613. Remove a file extension from the list for a specific object
  4614. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4615. :return:
  4616. """
  4617. if ext_type == 'excellon':
  4618. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4619. if new_ext == '':
  4620. return
  4621. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4622. if new_ext not in old_val:
  4623. return
  4624. old_val.remove(new_ext)
  4625. old_val.sort()
  4626. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4627. if ext_type == 'gcode':
  4628. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4629. if new_ext == '':
  4630. return
  4631. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4632. if new_ext not in old_val:
  4633. return
  4634. old_val.remove(new_ext)
  4635. old_val.sort()
  4636. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4637. if ext_type == 'gerber':
  4638. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4639. if new_ext == '':
  4640. return
  4641. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4642. if new_ext not in old_val:
  4643. return
  4644. old_val.remove(new_ext)
  4645. old_val.sort()
  4646. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4647. if ext_type == 'keyword':
  4648. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4649. if new_kw == '':
  4650. return
  4651. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4652. if new_kw not in old_val:
  4653. return
  4654. old_val.remove(new_kw)
  4655. old_val.sort()
  4656. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4657. # update the self.myKeywords so the model is updated
  4658. self.autocomplete_kw_list = \
  4659. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4660. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4661. self.shell._edit.set_model_data(self.myKeywords)
  4662. def restore_extensions(self, ext_type):
  4663. """
  4664. Restore all file extensions associations with FlatCAM, for a specific object
  4665. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4666. :return:
  4667. """
  4668. if ext_type == 'excellon':
  4669. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4670. # for the ability to open Excellon files with .txt extension
  4671. new_exc_list = deepcopy(self.exc_list)
  4672. try:
  4673. new_exc_list.remove('txt')
  4674. except ValueError:
  4675. pass
  4676. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4677. if ext_type == 'gcode':
  4678. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4679. if ext_type == 'gerber':
  4680. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4681. if ext_type == 'keyword':
  4682. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4683. # update the self.myKeywords so the model is updated
  4684. self.autocomplete_kw_list = self.default_keywords
  4685. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4686. self.shell._edit.set_model_data(self.myKeywords)
  4687. def delete_all_extensions(self, ext_type):
  4688. """
  4689. Delete all file extensions associations with FlatCAM, for a specific object
  4690. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4691. :return:
  4692. """
  4693. if ext_type == 'excellon':
  4694. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4695. if ext_type == 'gcode':
  4696. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4697. if ext_type == 'gerber':
  4698. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4699. if ext_type == 'keyword':
  4700. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4701. # update the self.myKeywords so the model is updated
  4702. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4703. self.shell._edit.set_model_data(self.myKeywords)
  4704. def on_edit_join(self, name=None):
  4705. """
  4706. Callback for Edit->Join. Joins the selected geometry objects into
  4707. a new one.
  4708. :return: None
  4709. """
  4710. self.report_usage("on_edit_join()")
  4711. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4712. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4713. geo_type_set = set()
  4714. objs = self.collection.get_selected()
  4715. if len(objs) < 2:
  4716. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4717. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4718. return 'fail'
  4719. for obj in objs:
  4720. geo_type_set.add(obj.multigeo)
  4721. # if len(geo_type_list) == 1 means that all list elements are the same
  4722. if len(geo_type_set) != 1:
  4723. self.inform.emit('[ERROR] %s' %
  4724. _("Failed join. The Geometry objects are of different types.\n"
  4725. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4726. "convert from one to another and retry joining \n"
  4727. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4728. "the result may not be what was expected. \n"
  4729. "Check the generated GCODE."))
  4730. return
  4731. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4732. if True in geo_type_set:
  4733. def initialize(geo_obj, app):
  4734. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4735. app.inform.emit('[success] %s.' % _("Multigeo. Geometry merging finished"))
  4736. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4737. for v in obj.tools.values():
  4738. v['data']['name'] = obj_name_multi
  4739. self.new_object("geometry", obj_name_multi, initialize)
  4740. else:
  4741. def initialize(geo_obj, app):
  4742. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4743. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4744. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4745. for v in obj.tools.values():
  4746. v['data']['name'] = obj_name_single
  4747. self.new_object("geometry", obj_name_single, initialize)
  4748. self.should_we_save = True
  4749. def on_edit_join_exc(self):
  4750. """
  4751. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4752. a new Excellon.
  4753. :return: None
  4754. """
  4755. self.report_usage("on_edit_join_exc()")
  4756. objs = self.collection.get_selected()
  4757. for obj in objs:
  4758. if not isinstance(obj, FlatCAMExcellon):
  4759. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4760. return
  4761. if len(objs) < 2:
  4762. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4763. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4764. return 'fail'
  4765. def initialize(exc_obj, app):
  4766. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=exc_obj)
  4767. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4768. self.new_object("excellon", 'Combo_Excellon', initialize)
  4769. self.should_we_save = True
  4770. def on_edit_join_grb(self):
  4771. """
  4772. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4773. a new Gerber object.
  4774. :return: None
  4775. """
  4776. self.report_usage("on_edit_join_grb()")
  4777. objs = self.collection.get_selected()
  4778. for obj in objs:
  4779. if not isinstance(obj, FlatCAMGerber):
  4780. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4781. return
  4782. if len(objs) < 2:
  4783. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4784. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4785. return 'fail'
  4786. def initialize(grb_obj, app):
  4787. FlatCAMGerber.merge(self, grb_list=objs, grb_final=grb_obj)
  4788. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4789. self.new_object("gerber", 'Combo_Gerber', initialize)
  4790. self.should_we_save = True
  4791. def on_convert_singlegeo_to_multigeo(self):
  4792. """
  4793. Called for converting a Geometry object from single-geo to multi-geo.
  4794. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4795. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4796. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4797. the solid-geometry of that tool.
  4798. :return: None
  4799. """
  4800. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4801. obj = self.collection.get_active()
  4802. if obj is None:
  4803. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4804. return
  4805. if not isinstance(obj, FlatCAMGeometry):
  4806. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4807. return
  4808. obj.multigeo = True
  4809. for tooluid, dict_value in obj.tools.items():
  4810. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4811. if not isinstance(obj.solid_geometry, list):
  4812. obj.solid_geometry = [obj.solid_geometry]
  4813. obj.solid_geometry[:] = []
  4814. obj.plot()
  4815. self.should_we_save = True
  4816. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4817. def on_convert_multigeo_to_singlegeo(self):
  4818. """
  4819. Called for converting a Geometry object from multi-geo to single-geo.
  4820. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4821. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4822. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4823. the solid-geometry of that tool.
  4824. :return: None
  4825. """
  4826. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4827. obj = self.collection.get_active()
  4828. if obj is None:
  4829. self.inform.emit('[ERROR_NOTCL] %s' %
  4830. _("Failed. Select a Geometry Object and try again."))
  4831. return
  4832. if not isinstance(obj, FlatCAMGeometry):
  4833. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4834. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4835. return
  4836. obj.multigeo = False
  4837. total_solid_geometry = []
  4838. for tooluid, dict_value in obj.tools.items():
  4839. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4840. # clear the original geometry
  4841. dict_value['solid_geometry'][:] = []
  4842. obj.solid_geometry = deepcopy(total_solid_geometry)
  4843. obj.plot()
  4844. self.should_we_save = True
  4845. self.inform.emit('[success] %s' %
  4846. _("A Geometry object was converted to SingleGeo type."))
  4847. def on_defaults_dict_change(self, field):
  4848. """
  4849. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4850. Edit -> Preferences tab window.
  4851. :param field: the key of the self.defaults dictionary that was changed.
  4852. :return: None
  4853. """
  4854. self.defaults_write_form_field(field)
  4855. if field == "units":
  4856. self.set_screen_units(self.defaults['units'])
  4857. def set_screen_units(self, units):
  4858. """
  4859. Set the FlatCAM units on the status bar.
  4860. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4861. :return: None
  4862. """
  4863. self.ui.units_label.setText("[" + units.lower() + "]")
  4864. def on_toggle_units_click(self):
  4865. try:
  4866. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4867. except (TypeError, AttributeError):
  4868. pass
  4869. if self.defaults["units"] == 'MM':
  4870. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4871. else:
  4872. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4873. self.on_toggle_units(no_pref=True)
  4874. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4875. lambda: self.on_toggle_units(no_pref=False))
  4876. def on_toggle_units(self, no_pref=False):
  4877. """
  4878. Callback for the Units radio-button change in the Preferences tab.
  4879. Changes the application's default units adn for the project too.
  4880. If changing the project's units, the change propagates to all of
  4881. the objects in the project.
  4882. :return: None
  4883. """
  4884. self.report_usage("on_toggle_units")
  4885. if self.toggle_units_ignore:
  4886. return
  4887. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4888. # If option is the same, then ignore
  4889. if new_units == self.defaults["units"].upper():
  4890. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4891. return
  4892. # Options to scale
  4893. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4894. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4895. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4896. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4897. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4898. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4899. "excellon_editor_slot_lin_pitch",
  4900. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4901. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4902. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4903. "geometry_feedrate_probe", "geometry_startz",
  4904. 'cncjob_tooldia',
  4905. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4906. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4907. "tools_nccnewdia",
  4908. "tools_2sided_drilldia", "tools_film_boundary",
  4909. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4910. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4911. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4912. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4913. "tools_transform_offset_y",
  4914. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4915. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4916. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4917. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4918. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4919. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4920. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4921. "tools_fiducials_line_thickness",
  4922. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4923. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4924. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4925. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4926. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4927. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  4928. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  4929. def scale_defaults(sfactor):
  4930. for dim in dimensions:
  4931. if dim == 'excellon_toolchangexy':
  4932. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4933. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4934. coords_xy[0] *= sfactor
  4935. coords_xy[1] *= sfactor
  4936. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4937. self.decimals, coords_xy[1])
  4938. elif dim == 'geometry_toolchangexy':
  4939. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4940. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4941. coords_xy[0] *= sfactor
  4942. coords_xy[1] *= sfactor
  4943. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4944. self.decimals, coords_xy[1])
  4945. elif dim == 'geometry_cnctooldia':
  4946. if type(self.defaults["geometry_cnctooldia"]) == float:
  4947. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  4948. else:
  4949. try:
  4950. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4951. tools_diameters = [eval(a) for a in tools_string if a != '']
  4952. except Exception as e:
  4953. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4954. continue
  4955. self.defaults['geometry_cnctooldia'] = ''
  4956. for t in range(len(tools_diameters)):
  4957. tools_diameters[t] *= sfactor
  4958. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  4959. elif dim == 'tools_ncctools':
  4960. ncctools = list()
  4961. if type(self.defaults["tools_ncctools"]) == float:
  4962. ncctools = [self.defaults["tools_ncctools"]]
  4963. else:
  4964. try:
  4965. tools_string = self.defaults["tools_ncctools"].split(",")
  4966. ncctools = [eval(a) for a in tools_string if a != '']
  4967. except Exception as e:
  4968. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4969. continue
  4970. self.defaults['tools_ncctools'] = ''
  4971. for t in range(len(ncctools)):
  4972. ncctools[t] *= sfactor
  4973. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  4974. elif dim == 'tools_solderpaste_tools':
  4975. sptools = list()
  4976. if type(self.defaults["tools_solderpaste_tools"]) == float:
  4977. sptools = [self.defaults["tools_solderpaste_tools"]]
  4978. else:
  4979. try:
  4980. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4981. sptools = [eval(a) for a in tools_string if a != '']
  4982. except Exception as e:
  4983. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4984. continue
  4985. self.defaults['tools_solderpaste_tools'] = ""
  4986. for t in range(len(sptools)):
  4987. sptools[t] *= sfactor
  4988. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  4989. elif dim == 'tools_solderpaste_xy_toolchange':
  4990. try:
  4991. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4992. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4993. sp_coords[0] *= sfactor
  4994. sp_coords[1] *= sfactor
  4995. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  4996. self.decimals, sp_coords[1])
  4997. except Exception as e:
  4998. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4999. continue
  5000. elif dim == 'global_gridx' or dim == 'global_gridy':
  5001. if new_units == 'IN':
  5002. val = 0.1
  5003. try:
  5004. val = float(self.defaults[dim]) * sfactor
  5005. except Exception as e:
  5006. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5007. continue
  5008. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  5009. else:
  5010. val = 0.1
  5011. try:
  5012. val = float(self.defaults[dim]) * sfactor
  5013. except Exception as e:
  5014. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5015. continue
  5016. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  5017. else:
  5018. val = 0.1
  5019. if self.defaults[dim]:
  5020. try:
  5021. val = float(self.defaults[dim]) * sfactor
  5022. except Exception as e:
  5023. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  5024. continue
  5025. self.defaults[dim] = val
  5026. # The scaling factor depending on choice of units.
  5027. factor = 25.4 if new_units == 'MM' else 1/25.4
  5028. # Changing project units. Warn user.
  5029. msgbox = QtWidgets.QMessageBox()
  5030. msgbox.setWindowTitle(_("Toggle Units"))
  5031. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  5032. msgbox.setText(_("Changing the units of the project\n"
  5033. "will scale all objects.\n\n"
  5034. "Do you want to continue?"))
  5035. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5036. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5037. msgbox.setDefaultButton(bt_ok)
  5038. msgbox.exec_()
  5039. response = msgbox.clickedButton()
  5040. if response == bt_ok:
  5041. if no_pref is False:
  5042. self.defaults_read_form()
  5043. scale_defaults(factor)
  5044. self.defaults_write_form(fl_units=new_units)
  5045. self.defaults["units"] = new_units
  5046. # update the defaults from form, some may assume that the conversion is enough and it's not
  5047. self.on_options_app2project()
  5048. # update the objects
  5049. for obj in self.collection.get_list():
  5050. obj.convert_units(new_units)
  5051. # make that the properties stored in the object are also updated
  5052. self.object_changed.emit(obj)
  5053. # rebuild the object UI
  5054. obj.build_ui()
  5055. # change this only if the workspace is active
  5056. if self.defaults['global_workspace'] is True:
  5057. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  5058. # adjust the grid values on the main toolbar
  5059. val_x = float(self.defaults['global_gridx']) * factor
  5060. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  5061. current = self.collection.get_active()
  5062. if current is not None:
  5063. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  5064. if not isinstance(current, FlatCAMGeometry):
  5065. current.to_form()
  5066. # replot all objects
  5067. self.plot_all()
  5068. # set the status labels to reflect the current FlatCAM units
  5069. self.set_screen_units(new_units)
  5070. # signal to the app that we changed the object properties and it shoud save the project
  5071. self.should_we_save = True
  5072. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  5073. else:
  5074. # Undo toggling
  5075. self.toggle_units_ignore = True
  5076. if self.defaults['units'].upper() == 'MM':
  5077. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  5078. else:
  5079. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  5080. self.toggle_units_ignore = False
  5081. # store the grid values so they are not changed in the next step
  5082. val_x = float(self.defaults['global_gridx'])
  5083. val_y = float(self.defaults['global_gridy'])
  5084. self.inform.emit('[WARNING_NOTCL]%s' % _("Units conversion cancelled."))
  5085. self.defaults_read_form()
  5086. # the self.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  5087. # I don't want it for the grid values, so I update them here
  5088. self.defaults['global_gridx'] = val_x
  5089. self.defaults['global_gridy'] = val_y
  5090. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  5091. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  5092. def on_fullscreen(self, disable=False):
  5093. self.report_usage("on_fullscreen()")
  5094. if self.toggle_fscreen is False and disable is False:
  5095. # self.ui.showFullScreen()
  5096. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  5097. a = self.ui.geometry()
  5098. self.x_pos = a.x()
  5099. self.y_pos = a.y()
  5100. self.width = a.width()
  5101. self.height = a.height()
  5102. # set new geometry to full desktop rect
  5103. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  5104. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  5105. # everything else will not work without this hack. This happen in Windows.
  5106. # https://bugreports.qt.io/browse/QTBUG-41309
  5107. desktop = QtWidgets.QApplication.desktop()
  5108. screen = desktop.screenNumber(QtGui.QCursor.pos())
  5109. rec = desktop.screenGeometry(screen)
  5110. x = rec.x() - 1
  5111. y = rec.y() - 1
  5112. h = rec.height() + 2
  5113. w = rec.width() + 2
  5114. self.ui.setGeometry(x, y, w, h)
  5115. self.ui.show()
  5116. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  5117. tb.setVisible(False)
  5118. self.ui.splitter_left.setVisible(False)
  5119. self.toggle_fscreen = True
  5120. elif self.toggle_fscreen is True or disable is True:
  5121. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  5122. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  5123. self.ui.showNormal()
  5124. self.restore_toolbar_view()
  5125. self.ui.splitter_left.setVisible(True)
  5126. self.toggle_fscreen = False
  5127. def on_toggle_plotarea(self):
  5128. self.report_usage("on_toggle_plotarea()")
  5129. try:
  5130. name = self.ui.plot_tab_area.widget(0).objectName()
  5131. except AttributeError:
  5132. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  5133. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5134. self.ui.plot_tab_area.protectTab(0)
  5135. return
  5136. if name != 'plotarea':
  5137. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5138. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5139. self.ui.plot_tab_area.protectTab(0)
  5140. else:
  5141. self.ui.plot_tab_area.closeTab(0)
  5142. def on_toggle_notebook(self):
  5143. if self.ui.splitter.sizes()[0] == 0:
  5144. self.ui.splitter.setSizes([1, 1])
  5145. self.ui.menu_toggle_nb.setChecked(True)
  5146. else:
  5147. self.ui.splitter.setSizes([0, 1])
  5148. self.ui.menu_toggle_nb.setChecked(False)
  5149. def on_toggle_axis(self):
  5150. self.report_usage("on_toggle_axis()")
  5151. if self.toggle_axis is False:
  5152. if self.is_legacy is False:
  5153. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  5154. parent=self.plotcanvas.view.scene)
  5155. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  5156. parent=self.plotcanvas.view.scene)
  5157. else:
  5158. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  5159. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  5160. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  5161. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  5162. self.plotcanvas.canvas.draw()
  5163. self.toggle_axis = True
  5164. else:
  5165. if self.is_legacy is False:
  5166. self.plotcanvas.v_line.parent = None
  5167. self.plotcanvas.h_line.parent = None
  5168. else:
  5169. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  5170. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  5171. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  5172. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  5173. self.plotcanvas.canvas.draw()
  5174. self.toggle_axis = False
  5175. def on_toggle_grid(self):
  5176. self.report_usage("on_toggle_grid()")
  5177. self.ui.grid_snap_btn.trigger()
  5178. self.on_grid_snap_triggered(state=True)
  5179. def on_toggle_grid_lines(self):
  5180. self.report_usage("on_toggle_grd_lines()")
  5181. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  5182. if tt_settings.contains("theme"):
  5183. theme = tt_settings.value('theme', type=str)
  5184. else:
  5185. theme = 'white'
  5186. if self.toggle_grid_lines is False:
  5187. if self.is_legacy is False:
  5188. if theme == 'white':
  5189. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  5190. else:
  5191. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  5192. else:
  5193. self.plotcanvas.axes.grid(True)
  5194. try:
  5195. self.plotcanvas.canvas.draw()
  5196. except IndexError:
  5197. pass
  5198. pass
  5199. self.toggle_grid_lines = True
  5200. else:
  5201. if self.is_legacy is False:
  5202. if theme == 'white':
  5203. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  5204. else:
  5205. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  5206. else:
  5207. self.plotcanvas.axes.grid(False)
  5208. try:
  5209. self.plotcanvas.canvas.draw()
  5210. except IndexError:
  5211. pass
  5212. self.toggle_grid_lines = False
  5213. if self.is_legacy is False:
  5214. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  5215. # - perhaps is a bug in VisPy implementation
  5216. if self.grid_status() is True:
  5217. self.app_cursor.enabled = False
  5218. self.app_cursor.enabled = True
  5219. else:
  5220. self.app_cursor.enabled = True
  5221. self.app_cursor.enabled = False
  5222. def show_preferences_gui(self):
  5223. """
  5224. Called to initialize and show the Preferences GUI
  5225. :return: None
  5226. """
  5227. self.gen_form = self.ui.general_defaults_form
  5228. self.ger_form = self.ui.gerber_defaults_form
  5229. self.exc_form = self.ui.excellon_defaults_form
  5230. self.geo_form = self.ui.geometry_defaults_form
  5231. self.cnc_form = self.ui.cncjob_defaults_form
  5232. self.tools_form = self.ui.tools_defaults_form
  5233. self.tools2_form = self.ui.tools2_defaults_form
  5234. self.fa_form = self.ui.util_defaults_form
  5235. try:
  5236. self.ui.general_scroll_area.takeWidget()
  5237. except Exception:
  5238. self.log.debug("Nothing to remove")
  5239. self.ui.general_scroll_area.setWidget(self.gen_form)
  5240. self.gen_form.show()
  5241. try:
  5242. self.ui.gerber_scroll_area.takeWidget()
  5243. except Exception:
  5244. self.log.debug("Nothing to remove")
  5245. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5246. self.ger_form.show()
  5247. try:
  5248. self.ui.excellon_scroll_area.takeWidget()
  5249. except Exception:
  5250. self.log.debug("Nothing to remove")
  5251. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5252. self.exc_form.show()
  5253. try:
  5254. self.ui.geometry_scroll_area.takeWidget()
  5255. except Exception:
  5256. self.log.debug("Nothing to remove")
  5257. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5258. self.geo_form.show()
  5259. try:
  5260. self.ui.cncjob_scroll_area.takeWidget()
  5261. except Exception:
  5262. self.log.debug("Nothing to remove")
  5263. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5264. self.cnc_form.show()
  5265. try:
  5266. self.ui.tools_scroll_area.takeWidget()
  5267. except Exception:
  5268. self.log.debug("Nothing to remove")
  5269. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5270. self.tools_form.show()
  5271. try:
  5272. self.ui.tools2_scroll_area.takeWidget()
  5273. except Exception:
  5274. self.log.debug("Nothing to remove")
  5275. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5276. self.tools2_form.show()
  5277. try:
  5278. self.ui.fa_scroll_area.takeWidget()
  5279. except Exception:
  5280. self.log.debug("Nothing to remove")
  5281. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5282. self.fa_form.show()
  5283. self.log.debug("Finished Preferences GUI form initialization.")
  5284. # self.options2form()
  5285. def init_color_pickers_in_preferences_gui(self):
  5286. # Init Gerber Plot Colors
  5287. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_entry.set_value(self.defaults['gerber_plot_fill'])
  5288. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_button.setStyleSheet(
  5289. "background-color:%s;"
  5290. "border-color: dimgray" % str(self.defaults['gerber_plot_fill'])[:7])
  5291. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_spinner.set_value(
  5292. int(self.defaults['gerber_plot_fill'][7:9], 16))
  5293. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.setValue(
  5294. int(self.defaults['gerber_plot_fill'][7:9], 16))
  5295. self.ui.gerber_defaults_form.gerber_gen_group.pl_color_entry.set_value(self.defaults['gerber_plot_line'])
  5296. self.ui.gerber_defaults_form.gerber_gen_group.pl_color_button.setStyleSheet(
  5297. "background-color:%s;"
  5298. "border-color: dimgray" % str(self.defaults['gerber_plot_line'])[:7])
  5299. # Init Excellon Plot Colors
  5300. self.ui.excellon_defaults_form.excellon_gen_group.fill_color_entry.set_value(
  5301. self.defaults['excellon_plot_fill'])
  5302. self.ui.excellon_defaults_form.excellon_gen_group.fill_color_button.setStyleSheet(
  5303. "background-color:%s;"
  5304. "border-color: dimgray" % str(self.defaults['excellon_plot_fill'])[:7])
  5305. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_spinner.set_value(
  5306. int(self.defaults['excellon_plot_fill'][7:9], 16))
  5307. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.setValue(
  5308. int(self.defaults['excellon_plot_fill'][7:9], 16))
  5309. self.ui.excellon_defaults_form.excellon_gen_group.line_color_entry.set_value(
  5310. self.defaults['excellon_plot_line'])
  5311. self.ui.excellon_defaults_form.excellon_gen_group.line_color_button.setStyleSheet(
  5312. "background-color:%s;"
  5313. "border-color: dimgray" % str(self.defaults['excellon_plot_line'])[:7])
  5314. # Init Geometry Plot Colors
  5315. self.ui.geometry_defaults_form.geometry_gen_group.line_color_entry.set_value(
  5316. self.defaults['geometry_plot_line'])
  5317. self.ui.geometry_defaults_form.geometry_gen_group.line_color_button.setStyleSheet(
  5318. "background-color:%s;"
  5319. "border-color: dimgray" % str(self.defaults['geometry_plot_line'])[:7])
  5320. # Init CNCJob Travel Line Colors
  5321. self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_entry.set_value(
  5322. self.defaults['cncjob_travel_fill'])
  5323. self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_button.setStyleSheet(
  5324. "background-color:%s;"
  5325. "border-color: dimgray" % str(self.defaults['cncjob_travel_fill'])[:7])
  5326. self.ui.cncjob_defaults_form.cncjob_gen_group.tcolor_alpha_spinner.set_value(
  5327. int(self.defaults['cncjob_travel_fill'][7:9], 16))
  5328. self.ui.cncjob_defaults_form.cncjob_gen_group.tcolor_alpha_slider.setValue(
  5329. int(self.defaults['cncjob_travel_fill'][7:9], 16))
  5330. self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_entry.set_value(
  5331. self.defaults['cncjob_travel_line'])
  5332. self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_button.setStyleSheet(
  5333. "background-color:%s;"
  5334. "border-color: dimgray" % str(self.defaults['cncjob_travel_line'])[:7])
  5335. # Init CNCJob Plot Colors
  5336. self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_entry.set_value(
  5337. self.defaults['cncjob_plot_fill'])
  5338. self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_button.setStyleSheet(
  5339. "background-color:%s;"
  5340. "border-color: dimgray" % str(self.defaults['cncjob_plot_fill'])[:7])
  5341. self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_entry.set_value(
  5342. self.defaults['cncjob_plot_line'])
  5343. self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_button.setStyleSheet(
  5344. "background-color:%s;"
  5345. "border-color: dimgray" % str(self.defaults['cncjob_plot_line'])[:7])
  5346. # Init Left-Right Selection colors
  5347. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  5348. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5349. "background-color:%s;"
  5350. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  5351. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  5352. int(self.defaults['global_sel_fill'][7:9], 16))
  5353. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  5354. int(self.defaults['global_sel_fill'][7:9], 16))
  5355. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  5356. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5357. "background-color:%s;"
  5358. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  5359. # Init Right-Left Selection colors
  5360. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  5361. self.defaults['global_alt_sel_fill'])
  5362. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5363. "background-color:%s;"
  5364. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  5365. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  5366. int(self.defaults['global_sel_fill'][7:9], 16))
  5367. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  5368. int(self.defaults['global_sel_fill'][7:9], 16))
  5369. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  5370. self.defaults['global_alt_sel_line'])
  5371. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5372. "background-color:%s;"
  5373. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  5374. # Init Draw color and Selection Draw Color
  5375. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  5376. self.defaults['global_draw_color'])
  5377. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5378. "background-color:%s;"
  5379. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  5380. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  5381. self.defaults['global_sel_draw_color'])
  5382. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5383. "background-color:%s;"
  5384. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  5385. # Init Project Items color
  5386. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  5387. self.defaults['global_proj_item_color'])
  5388. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5389. "background-color:%s;"
  5390. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  5391. # Init Project Disabled Items color
  5392. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  5393. self.defaults['global_proj_item_dis_color'])
  5394. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5395. "background-color:%s;"
  5396. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  5397. # Init Project Disabled Items color
  5398. self.ui.general_defaults_form.general_app_set_group.mouse_cursor_entry.set_value(
  5399. self.defaults['global_cursor_color'])
  5400. self.ui.general_defaults_form.general_app_set_group.mouse_cursor_button.setStyleSheet(
  5401. "background-color:%s;"
  5402. "border-color: dimgray" % str(self.defaults['global_cursor_color'])[:7])
  5403. # Init the Annotation CNC Job color
  5404. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  5405. self.defaults['cncjob_annotation_fontcolor'])
  5406. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5407. "background-color:%s;"
  5408. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  5409. # Init the Tool Film color
  5410. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  5411. self.defaults['tools_film_color'])
  5412. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5413. "background-color:%s;"
  5414. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  5415. )
  5416. # Init the Tool QRCode colors
  5417. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  5418. self.defaults['tools_qrcode_fill_color'])
  5419. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5420. "background-color:%s;"
  5421. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  5422. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  5423. self.defaults['tools_qrcode_back_color'])
  5424. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5425. "background-color:%s;"
  5426. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  5427. def on_update_exc_export(self, state):
  5428. """
  5429. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5430. if the update_excellon_cb checkbox is checked
  5431. :param state: state of the checkbox whose signals is tied to his slot
  5432. :return:
  5433. """
  5434. if state:
  5435. # first try to disconnect
  5436. try:
  5437. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5438. disconnect(self.on_excellon_format_changed)
  5439. except TypeError:
  5440. pass
  5441. try:
  5442. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5443. disconnect(self.on_excellon_format_changed)
  5444. except TypeError:
  5445. pass
  5446. try:
  5447. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5448. disconnect(self.on_excellon_format_changed)
  5449. except TypeError:
  5450. pass
  5451. try:
  5452. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5453. disconnect(self.on_excellon_format_changed)
  5454. except TypeError:
  5455. pass
  5456. try:
  5457. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5458. disconnect(self.on_excellon_zeros_changed)
  5459. except TypeError:
  5460. pass
  5461. try:
  5462. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5463. disconnect(self.on_excellon_zeros_changed)
  5464. except TypeError:
  5465. pass
  5466. # the connect them
  5467. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5468. self.on_excellon_format_changed)
  5469. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5470. self.on_excellon_format_changed)
  5471. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5472. self.on_excellon_format_changed)
  5473. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5474. self.on_excellon_format_changed)
  5475. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5476. self.on_excellon_zeros_changed)
  5477. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5478. self.on_excellon_units_changed)
  5479. else:
  5480. # disconnect the signals
  5481. try:
  5482. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5483. disconnect(self.on_excellon_format_changed)
  5484. except TypeError:
  5485. pass
  5486. try:
  5487. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5488. disconnect(self.on_excellon_format_changed)
  5489. except TypeError:
  5490. pass
  5491. try:
  5492. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5493. disconnect(self.on_excellon_format_changed)
  5494. except TypeError:
  5495. pass
  5496. try:
  5497. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5498. disconnect(self.on_excellon_format_changed)
  5499. except TypeError:
  5500. pass
  5501. try:
  5502. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5503. disconnect(self.on_excellon_zeros_changed)
  5504. except TypeError:
  5505. pass
  5506. try:
  5507. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5508. disconnect(self.on_excellon_zeros_changed)
  5509. except TypeError:
  5510. pass
  5511. def on_excellon_format_changed(self):
  5512. """
  5513. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5514. :return: None
  5515. """
  5516. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5517. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5518. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5519. )
  5520. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5521. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5522. )
  5523. else:
  5524. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5525. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5526. )
  5527. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5528. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5529. )
  5530. def on_excellon_zeros_changed(self):
  5531. """
  5532. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5533. :return: None
  5534. """
  5535. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5536. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5537. )
  5538. def on_excellon_units_changed(self):
  5539. """
  5540. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5541. :return: None
  5542. """
  5543. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5544. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5545. )
  5546. self.on_excellon_format_changed()
  5547. def on_film_color_entry(self):
  5548. self.defaults['tools_film_color'] = \
  5549. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5550. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5551. "background-color:%s;"
  5552. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5553. )
  5554. def on_film_color_button(self):
  5555. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5556. c_dialog = QtWidgets.QColorDialog()
  5557. film_color = c_dialog.getColor(initial=current_color)
  5558. if film_color.isValid() is False:
  5559. return
  5560. # if new color is different then mark that the Preferences are changed
  5561. if film_color != current_color:
  5562. self.on_preferences_edited()
  5563. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5564. "background-color:%s;"
  5565. "border-color: dimgray" % str(film_color.name())
  5566. )
  5567. new_val_sel = str(film_color.name())
  5568. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5569. self.defaults['tools_film_color'] = new_val_sel
  5570. def on_qrcode_fill_color_entry(self):
  5571. self.defaults['tools_qrcode_fill_color'] = \
  5572. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5573. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5574. "background-color:%s;"
  5575. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5576. )
  5577. def on_qrcode_fill_color_button(self):
  5578. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5579. c_dialog = QtWidgets.QColorDialog()
  5580. fill_color = c_dialog.getColor(initial=current_color)
  5581. if fill_color.isValid() is False:
  5582. return
  5583. # if new color is different then mark that the Preferences are changed
  5584. if fill_color != current_color:
  5585. self.on_preferences_edited()
  5586. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5587. "background-color:%s;"
  5588. "border-color: dimgray" % str(fill_color.name())
  5589. )
  5590. new_val_sel = str(fill_color.name())
  5591. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5592. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5593. def on_qrcode_back_color_entry(self):
  5594. self.defaults['tools_qrcode_back_color'] = \
  5595. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5596. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5597. "background-color:%s;"
  5598. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5599. )
  5600. def on_qrcode_back_color_button(self):
  5601. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5602. c_dialog = QtWidgets.QColorDialog()
  5603. back_color = c_dialog.getColor(initial=current_color)
  5604. if back_color.isValid() is False:
  5605. return
  5606. # if new color is different then mark that the Preferences are changed
  5607. if back_color != current_color:
  5608. self.on_preferences_edited()
  5609. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5610. "background-color:%s;"
  5611. "border-color: dimgray" % str(back_color.name())
  5612. )
  5613. new_val_sel = str(back_color.name())
  5614. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5615. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5616. def on_tab_rmb_click(self, checked):
  5617. self.ui.notebook.set_detachable(val=checked)
  5618. self.defaults["global_tabs_detachable"] = checked
  5619. self.ui.plot_tab_area.set_detachable(val=checked)
  5620. self.defaults["global_tabs_detachable"] = checked
  5621. def on_tab_setup_context_menu(self):
  5622. initial_checked = self.defaults["global_tabs_detachable"]
  5623. action_name = str(_("Detachable Tabs"))
  5624. action = QtWidgets.QAction(self)
  5625. action.setCheckable(True)
  5626. action.setText(action_name)
  5627. action.setChecked(initial_checked)
  5628. self.ui.notebook.tabBar.addAction(action)
  5629. self.ui.plot_tab_area.tabBar.addAction(action)
  5630. try:
  5631. action.triggered.disconnect()
  5632. except TypeError:
  5633. pass
  5634. action.triggered.connect(self.on_tab_rmb_click)
  5635. def on_deselect_all(self):
  5636. self.collection.set_all_inactive()
  5637. self.delete_selection_shape()
  5638. def on_workspace_modified(self):
  5639. # self.save_defaults(silent=True)
  5640. if self.is_legacy is True:
  5641. self.plotcanvas.delete_workspace()
  5642. self.defaults_read_form()
  5643. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5644. def on_workspace(self):
  5645. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  5646. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5647. else:
  5648. self.plotcanvas.delete_workspace()
  5649. self.defaults_read_form()
  5650. # self.save_defaults(silent=True)
  5651. def on_workspace_toggle(self):
  5652. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  5653. try:
  5654. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  5655. except TypeError:
  5656. pass
  5657. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  5658. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  5659. self.on_workspace()
  5660. def on_layout(self, index=None, lay=None):
  5661. """
  5662. Set the toolbars layout (location)
  5663. :param index:
  5664. :param lay: type of layout to be set on the toolbard
  5665. :return: None
  5666. """
  5667. self.report_usage("on_layout()")
  5668. if lay:
  5669. current_layout = lay
  5670. else:
  5671. current_layout = self.ui.general_defaults_form.general_gui_group.layout_combo.get_value()
  5672. lay_settings = QSettings("Open Source", "FlatCAM")
  5673. lay_settings.setValue('layout', current_layout)
  5674. # This will write the setting to the platform specific storage.
  5675. del lay_settings
  5676. # first remove the toolbars:
  5677. try:
  5678. self.ui.removeToolBar(self.ui.toolbarfile)
  5679. self.ui.removeToolBar(self.ui.toolbargeo)
  5680. self.ui.removeToolBar(self.ui.toolbarview)
  5681. self.ui.removeToolBar(self.ui.toolbarshell)
  5682. self.ui.removeToolBar(self.ui.toolbartools)
  5683. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5684. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5685. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5686. self.ui.removeToolBar(self.ui.snap_toolbar)
  5687. self.ui.removeToolBar(self.ui.toolbarshell)
  5688. except Exception:
  5689. pass
  5690. if current_layout == 'standard':
  5691. # ## TOOLBAR INSTALLATION # ##
  5692. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5693. self.ui.toolbarfile.setObjectName('File_TB')
  5694. self.ui.addToolBar(self.ui.toolbarfile)
  5695. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5696. self.ui.toolbargeo.setObjectName('Edit_TB')
  5697. self.ui.addToolBar(self.ui.toolbargeo)
  5698. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5699. self.ui.toolbarview.setObjectName('View_TB')
  5700. self.ui.addToolBar(self.ui.toolbarview)
  5701. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5702. self.ui.toolbarshell.setObjectName('Shell_TB')
  5703. self.ui.addToolBar(self.ui.toolbarshell)
  5704. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5705. self.ui.toolbartools.setObjectName('Tools_TB')
  5706. self.ui.addToolBar(self.ui.toolbartools)
  5707. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5708. # self.ui.exc_edit_toolbar.setVisible(False)
  5709. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5710. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5711. self.ui.addToolBarBreak()
  5712. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5713. # self.ui.geo_edit_toolbar.setVisible(False)
  5714. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5715. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5716. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5717. # self.ui.grb_edit_toolbar.setVisible(False)
  5718. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5719. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5720. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5721. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5722. # self.ui.snap_toolbar.setMaximumHeight(30)
  5723. self.ui.addToolBar(self.ui.snap_toolbar)
  5724. self.ui.corner_snap_btn.setVisible(False)
  5725. self.ui.snap_magnet.setVisible(False)
  5726. elif current_layout == 'compact':
  5727. # ## TOOLBAR INSTALLATION # ##
  5728. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5729. self.ui.toolbarfile.setObjectName('File_TB')
  5730. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5731. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5732. self.ui.toolbargeo.setObjectName('Edit_TB')
  5733. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5734. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5735. self.ui.toolbarshell.setObjectName('Shell_TB')
  5736. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5737. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5738. self.ui.toolbartools.setObjectName('Tools_TB')
  5739. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5740. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5741. # self.ui.geo_edit_toolbar.setVisible(False)
  5742. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5743. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5744. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5745. self.ui.toolbarview.setObjectName('View_TB')
  5746. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5747. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5748. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5749. # self.ui.grb_edit_toolbar.setVisible(False)
  5750. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5751. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5752. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5753. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5754. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5755. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5756. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5757. self.ui.snap_toolbar.setMaximumHeight(30)
  5758. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5759. self.ui.corner_snap_btn.setVisible(True)
  5760. self.ui.snap_magnet.setVisible(True)
  5761. # add all the actions to the toolbars
  5762. self.ui.populate_toolbars()
  5763. # reconnect all the signals to the toolbar actions
  5764. self.connect_toolbar_signals()
  5765. self.ui.grid_snap_btn.setChecked(True)
  5766. self.on_grid_snap_triggered(state=True)
  5767. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5768. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5769. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5770. self.ui.grid_gap_link_cb.setChecked(True)
  5771. def on_cursor_type(self, val):
  5772. """
  5773. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5774. :return: None
  5775. """
  5776. self.app_cursor.enabled = False
  5777. if val == 'small':
  5778. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  5779. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  5780. self.app_cursor = self.plotcanvas.new_cursor()
  5781. else:
  5782. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  5783. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  5784. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5785. if self.ui.grid_snap_btn.isChecked():
  5786. self.app_cursor.enabled = True
  5787. else:
  5788. self.app_cursor.enabled = False
  5789. def on_save_button(self, save_to_file=True):
  5790. log.debug("App.on_save_button() --> Applying preferences to file.")
  5791. # Preferences saved, update flag
  5792. self.preferences_changed_flag = False
  5793. # Preferences save, update the color of the Preferences Tab text
  5794. for idx in range(self.ui.plot_tab_area.count()):
  5795. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5796. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5797. # restore the default stylesheet by setting a blank one
  5798. self.ui.pref_apply_button.setStyleSheet("")
  5799. self.inform.emit('%s' % _("Preferences applied."))
  5800. # make sure we update the self.current_defaults dict used to undo changes to self.defaults
  5801. self.current_defaults.update(self.defaults)
  5802. if save_to_file:
  5803. self.save_defaults(silent=False)
  5804. # load the defaults so they are updated into the app
  5805. self.load_defaults(filename='current_defaults')
  5806. # Re-fresh project options
  5807. self.on_options_app2project()
  5808. settgs = QSettings("Open Source", "FlatCAM")
  5809. # save the notebook font size
  5810. fsize = self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  5811. settgs.setValue('notebook_font_size', fsize)
  5812. # save the axis font size
  5813. g_fsize = self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  5814. settgs.setValue('axis_font_size', g_fsize)
  5815. # save the textbox font size
  5816. tb_fsize = self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  5817. settgs.setValue('textbox_font_size', tb_fsize)
  5818. settgs.setValue(
  5819. 'machinist',
  5820. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  5821. )
  5822. # This will write the setting to the platform specific storage.
  5823. del settgs
  5824. def on_pref_close_button(self):
  5825. # Preferences saved, update flag
  5826. self.preferences_changed_flag = False
  5827. try:
  5828. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_plot_area_tab_closed)
  5829. except TypeError:
  5830. pass
  5831. try:
  5832. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  5833. except (TypeError, AttributeError):
  5834. pass
  5835. self.defaults_write_form(source_dict=self.current_defaults)
  5836. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  5837. lambda: self.on_toggle_units(no_pref=False))
  5838. self.defaults.update(self.current_defaults)
  5839. # shared_items = {k: self.defaults[k] for k in self.defaults if k in self.current_defaults and
  5840. # self.defaults[k] == self.current_defaults[k]}
  5841. # print(len(self.defaults), len(shared_items))
  5842. # Preferences save, update the color of the Preferences Tab text
  5843. for idx in range(self.ui.plot_tab_area.count()):
  5844. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5845. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5846. self.ui.plot_tab_area.closeTab(idx)
  5847. break
  5848. self.inform.emit('%s' % _("Preferences closed without saving."))
  5849. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  5850. def on_tool_add_keypress(self):
  5851. # ## Current application units in Upper Case
  5852. self.units = self.defaults['units'].upper()
  5853. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5854. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5855. if notebook_widget_name == 'selected_tab':
  5856. if self.collection.get_active().kind == 'geometry':
  5857. # Tool add works for Geometry only if Advanced is True in Preferences
  5858. if self.defaults["global_app_level"] == 'a':
  5859. tool_add_popup = FCInputDialog(title="New Tool ...",
  5860. text='Enter a Tool Diameter:',
  5861. min=0.0000, max=99.9999, decimals=4)
  5862. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  5863. val, ok = tool_add_popup.get_value()
  5864. if ok:
  5865. if float(val) == 0:
  5866. self.inform.emit('[WARNING_NOTCL] %s' %
  5867. _("Please enter a tool diameter with non-zero value, in Float format."))
  5868. return
  5869. self.collection.get_active().on_tool_add(dia=float(val))
  5870. else:
  5871. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  5872. else:
  5873. msgbox = QtWidgets.QMessageBox()
  5874. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5875. "Go to Preferences -> General - Show Advanced Options."))
  5876. msgbox.setWindowTitle("Tool adding ...")
  5877. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  5878. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5879. msgbox.setDefaultButton(bt_ok)
  5880. msgbox.exec_()
  5881. # work only if the notebook tab on focus is the Tools_Tab
  5882. if notebook_widget_name == 'tool_tab':
  5883. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5884. # and only if the tool is NCC Tool
  5885. if tool_widget == self.ncclear_tool.toolName:
  5886. self.ncclear_tool.on_add_tool_by_key()
  5887. # and only if the tool is Paint Area Tool
  5888. elif tool_widget == self.paint_tool.toolName:
  5889. self.paint_tool.on_add_tool_by_key()
  5890. # and only if the tool is Solder Paste Dispensing Tool
  5891. elif tool_widget == self.paste_tool.toolName:
  5892. self.paste_tool.on_add_tool_by_key()
  5893. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5894. # See description bellow.
  5895. def on_delete_keypress(self):
  5896. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5897. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5898. if notebook_widget_name == 'selected_tab':
  5899. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5900. self.collection.get_active().on_tool_delete()
  5901. # work only if the notebook tab on focus is the Tools_Tab
  5902. elif notebook_widget_name == 'tool_tab':
  5903. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5904. # and only if the tool is NCC Tool
  5905. if tool_widget == self.ncclear_tool.toolName:
  5906. self.ncclear_tool.on_tool_delete()
  5907. # and only if the tool is Paint Tool
  5908. elif tool_widget == self.paint_tool.toolName:
  5909. self.paint_tool.on_tool_delete()
  5910. # and only if the tool is Solder Paste Dispensing Tool
  5911. elif tool_widget == self.paste_tool.toolName:
  5912. self.paste_tool.on_tool_delete()
  5913. else:
  5914. self.on_delete()
  5915. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5916. # some screens you have to be careful where you hover with your mouse.
  5917. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5918. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5919. # Complicated, I know :)
  5920. def on_delete(self):
  5921. """
  5922. Delete the currently selected FlatCAMObjs.
  5923. :return: None
  5924. """
  5925. self.report_usage("on_delete()")
  5926. response = None
  5927. bt_ok = None
  5928. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5929. # a geometry object before we update it.
  5930. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5931. and self.grb_editor.editor_active is False:
  5932. if self.defaults["global_delete_confirmation"] is True:
  5933. msgbox = QtWidgets.QMessageBox()
  5934. msgbox.setWindowTitle(_("Delete objects"))
  5935. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  5936. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5937. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5938. "the selected objects?"))
  5939. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5940. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5941. msgbox.setDefaultButton(bt_ok)
  5942. msgbox.exec_()
  5943. response = msgbox.clickedButton()
  5944. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5945. if self.collection.get_active():
  5946. self.log.debug("App.on_delete()")
  5947. while self.collection.get_active():
  5948. obj_active = self.collection.get_active()
  5949. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5950. if isinstance(obj_active, FlatCAMGerber):
  5951. for el in obj_active.mark_shapes:
  5952. obj_active.mark_shapes[el].clear(update=True)
  5953. obj_active.mark_shapes[el].enabled = False
  5954. # obj_active.mark_shapes[el] = None
  5955. del el
  5956. elif isinstance(obj_active, FlatCAMCNCjob):
  5957. try:
  5958. obj_active.annotation.clear(update=True)
  5959. obj_active.annotation.enabled = False
  5960. except AttributeError:
  5961. pass
  5962. self.delete_first_selected()
  5963. self.inform.emit('%s...' %
  5964. _("Object(s) deleted"))
  5965. # make sure that the selection shape is deleted, too
  5966. self.delete_selection_shape()
  5967. else:
  5968. self.inform.emit(_("Failed. No object(s) selected..."))
  5969. else:
  5970. self.inform.emit(_("Save the work in Editor and try again ..."))
  5971. def delete_first_selected(self):
  5972. # Keep this for later
  5973. try:
  5974. sel_obj = self.collection.get_active()
  5975. name = sel_obj.options["name"]
  5976. isPlotted = sel_obj.options["plot"]
  5977. except AttributeError:
  5978. self.log.debug("Nothing selected for deletion")
  5979. return
  5980. if self.is_legacy is True:
  5981. # Remove plot only if the object was plotted otherwise delaxes will fail
  5982. if isPlotted:
  5983. try:
  5984. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5985. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5986. except Exception as e:
  5987. log.debug("App.delete_first_selected() --> %s" % str(e))
  5988. self.plotcanvas.auto_adjust_axes()
  5989. # Remove from dictionary
  5990. self.collection.delete_active()
  5991. # Clear form
  5992. self.setup_component_editor()
  5993. self.inform.emit('%s: %s' %
  5994. (_("Object deleted"), name))
  5995. def on_set_origin(self):
  5996. """
  5997. Set the origin to the left mouse click position
  5998. :return: None
  5999. """
  6000. # display the message for the user
  6001. # and ask him to click on the desired position
  6002. self.report_usage("on_set_origin()")
  6003. def origin_replot():
  6004. def worker_task():
  6005. with self.proc_container.new('%s...' % _("Plotting")):
  6006. for obj in self.collection.get_list():
  6007. obj.plot()
  6008. self.plotcanvas.fit_view()
  6009. if self.is_legacy:
  6010. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  6011. else:
  6012. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  6013. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6014. self.inform.emit(_('Click to set the origin ...'))
  6015. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  6016. # first disconnect it as it may have been used by something else
  6017. try:
  6018. self.replot_signal.disconnect()
  6019. except TypeError:
  6020. pass
  6021. self.replot_signal[list].connect(origin_replot)
  6022. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  6023. """
  6024. :param event:
  6025. :param location:
  6026. :param noplot:
  6027. :param use_thread:
  6028. :return:
  6029. """
  6030. noplot_sig = noplot
  6031. def worker_task():
  6032. with self.proc_container.new(_("Setting Origin...")):
  6033. for obj in self.collection.get_list():
  6034. obj.offset((x, y))
  6035. self.object_changed.emit(obj)
  6036. # Update the object bounding box options
  6037. a, b, c, d = obj.bounds()
  6038. obj.options['xmin'] = a
  6039. obj.options['ymin'] = b
  6040. obj.options['xmax'] = c
  6041. obj.options['ymax'] = d
  6042. self.inform.emit('[success] %s...' % _('Origin set'))
  6043. if noplot_sig is False:
  6044. self.replot_signal.emit([])
  6045. if location is not None:
  6046. if len(location) != 2:
  6047. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  6048. return 'fail'
  6049. x, y = location
  6050. if use_thread is True:
  6051. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6052. else:
  6053. worker_task()
  6054. self.should_we_save = True
  6055. return
  6056. if event.button == 1:
  6057. if self.is_legacy is False:
  6058. event_pos = event.pos
  6059. else:
  6060. event_pos = (event.xdata, event.ydata)
  6061. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6062. if self.grid_status() == True:
  6063. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6064. else:
  6065. pos = pos_canvas
  6066. x = 0 - pos[0]
  6067. y = 0 - pos[1]
  6068. if use_thread is True:
  6069. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6070. else:
  6071. worker_task()
  6072. self.should_we_save = True
  6073. def on_jump_to(self, custom_location=None, fit_center=True):
  6074. """
  6075. Jump to a location by setting the mouse cursor location
  6076. :return:
  6077. """
  6078. self.report_usage("on_jump_to()")
  6079. if not custom_location:
  6080. dia_box_location = None
  6081. try:
  6082. dia_box_location = eval(self.clipboard.text())
  6083. except Exception:
  6084. pass
  6085. if type(dia_box_location) == tuple:
  6086. dia_box_location = str(dia_box_location)
  6087. else:
  6088. dia_box_location = None
  6089. # dia_box = Dialog_box(title=_("Jump to ..."),
  6090. # label=_("Enter the coordinates in format X,Y:"),
  6091. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6092. # initial_text=dia_box_location)
  6093. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  6094. label=_("Enter the coordinates in format X,Y:"),
  6095. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6096. initial_text=dia_box_location,
  6097. reference=self.defaults['global_jump_ref'])
  6098. if dia_box.ok is True:
  6099. try:
  6100. location = eval(dia_box.location)
  6101. if not isinstance(location, tuple):
  6102. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6103. return
  6104. if dia_box.reference == 'rel':
  6105. rel_x = self.mouse[0] + location[0]
  6106. rel_y = self.mouse[1] + location[1]
  6107. location = (rel_x, rel_y)
  6108. self.defaults['global_jump_ref'] = dia_box.reference
  6109. except Exception:
  6110. return
  6111. else:
  6112. return
  6113. else:
  6114. location = custom_location
  6115. self.jump_signal.emit(location)
  6116. if fit_center:
  6117. self.plotcanvas.fit_center(loc=location)
  6118. cursor = QtGui.QCursor()
  6119. if self.is_legacy is False:
  6120. # I don't know where those differences come from but they are constant for the current
  6121. # execution of the application and they are multiples of a value around 0.0263mm.
  6122. # In a random way sometimes they are more sometimes they are less
  6123. # if units == 'MM':
  6124. # cal_factor = 0.0263
  6125. # else:
  6126. # cal_factor = 0.0263 / 25.4
  6127. cal_location = (location[0], location[1])
  6128. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6129. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  6130. j_pos = (
  6131. int(canvas_origin.x() + round(jump_loc[0])),
  6132. int(canvas_origin.y() + round(jump_loc[1]))
  6133. )
  6134. cursor.setPos(j_pos[0], j_pos[1])
  6135. else:
  6136. # find the canvas origin which is in the top left corner
  6137. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6138. # determine the coordinates for the lowest left point of the canvas
  6139. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6140. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6141. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6142. # canvas) and the point (width, height) is in the top-right location
  6143. loc = self.plotcanvas.axes.transData.transform_point(location)
  6144. j_pos = (
  6145. int(x0 + loc[0]),
  6146. int(y0 - loc[1])
  6147. )
  6148. cursor.setPos(j_pos[0], j_pos[1])
  6149. self.plotcanvas.mouse = [location[0], location[1]]
  6150. if self.defaults["global_cursor_color_enabled"] is True:
  6151. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  6152. else:
  6153. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  6154. if self.grid_status():
  6155. # Update cursor
  6156. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6157. symbol='++', edge_color=self.cursor_color_3D,
  6158. edge_width=self.defaults["global_cursor_width"],
  6159. size=self.defaults["global_cursor_size"])
  6160. # Set the position label
  6161. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6162. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6163. # Set the relative position label
  6164. dx = location[0] - float(self.rel_point1[0])
  6165. dy = location[1] - float(self.rel_point1[1])
  6166. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6167. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6168. self.inform.emit('[success] %s' % _("Done."))
  6169. return location
  6170. def on_locate(self, obj, fit_center=True):
  6171. """
  6172. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  6173. :return:
  6174. """
  6175. self.report_usage("on_locate()")
  6176. if obj is None:
  6177. self.inform.emit('[WARNING_NOTCL] %s' % _("There is no object selected..."))
  6178. return 'fail'
  6179. class DialogBoxChoice(QtWidgets.QDialog):
  6180. def __init__(self, title=None, icon=None, choice='bl'):
  6181. """
  6182. :param title: string with the window title
  6183. """
  6184. super(DialogBoxChoice, self).__init__()
  6185. self.ok = False
  6186. self.setWindowIcon(icon)
  6187. self.setWindowTitle(str(title))
  6188. self.form = QtWidgets.QFormLayout(self)
  6189. self.ref_radio = RadioSet([
  6190. {"label": _("Bottom-Left"), "value": "bl"},
  6191. {"label": _("Top-Left"), "value": "tl"},
  6192. {"label": _("Bottom-Right"), "value": "br"},
  6193. {"label": _("Top-Right"), "value": "tr"},
  6194. {"label": _("Center"), "value": "c"}
  6195. ], orientation='vertical', stretch=False)
  6196. self.ref_radio.set_value(choice)
  6197. self.form.addRow(self.ref_radio)
  6198. self.button_box = QtWidgets.QDialogButtonBox(
  6199. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  6200. Qt.Horizontal, parent=self)
  6201. self.form.addRow(self.button_box)
  6202. self.button_box.accepted.connect(self.accept)
  6203. self.button_box.rejected.connect(self.reject)
  6204. if self.exec_() == QtWidgets.QDialog.Accepted:
  6205. self.ok = True
  6206. self.location_point = self.ref_radio.get_value()
  6207. else:
  6208. self.ok = False
  6209. self.location_point = None
  6210. dia_box = DialogBoxChoice(title=_("Locate ..."),
  6211. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  6212. choice=self.defaults['global_locate_pt'])
  6213. if dia_box.ok is True:
  6214. try:
  6215. location_point = dia_box.location_point
  6216. self.defaults['global_locate_pt'] = dia_box.location_point
  6217. except Exception:
  6218. return
  6219. else:
  6220. return
  6221. loc_b = obj.bounds()
  6222. if location_point == 'bl':
  6223. location = (loc_b[0], loc_b[1])
  6224. elif location_point == 'tl':
  6225. location = (loc_b[0], loc_b[3])
  6226. elif location_point == 'br':
  6227. location = (loc_b[2], loc_b[1])
  6228. elif location_point == 'tr':
  6229. location = (loc_b[2], loc_b[3])
  6230. else:
  6231. # center
  6232. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  6233. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  6234. location = (cx, cy)
  6235. self.locate_signal.emit(location, location_point)
  6236. if fit_center:
  6237. self.plotcanvas.fit_center(loc=location)
  6238. cursor = QtGui.QCursor()
  6239. if self.is_legacy is False:
  6240. # I don't know where those differences come from but they are constant for the current
  6241. # execution of the application and they are multiples of a value around 0.0263mm.
  6242. # In a random way sometimes they are more sometimes they are less
  6243. # if units == 'MM':
  6244. # cal_factor = 0.0263
  6245. # else:
  6246. # cal_factor = 0.0263 / 25.4
  6247. cal_location = (location[0], location[1])
  6248. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6249. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  6250. j_pos = (
  6251. int(canvas_origin.x() + round(jump_loc[0])),
  6252. int(canvas_origin.y() + round(jump_loc[1]))
  6253. )
  6254. cursor.setPos(j_pos[0], j_pos[1])
  6255. else:
  6256. # find the canvas origin which is in the top left corner
  6257. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6258. # determine the coordinates for the lowest left point of the canvas
  6259. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6260. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6261. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6262. # canvas) and the point (width, height) is in the top-right location
  6263. loc = self.plotcanvas.axes.transData.transform_point(location)
  6264. j_pos = (
  6265. int(x0 + loc[0]),
  6266. int(y0 - loc[1])
  6267. )
  6268. cursor.setPos(j_pos[0], j_pos[1])
  6269. self.plotcanvas.mouse = [location[0], location[1]]
  6270. if self.defaults["global_cursor_color_enabled"] is True:
  6271. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  6272. else:
  6273. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  6274. if self.grid_status():
  6275. # Update cursor
  6276. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6277. symbol='++', edge_color=self.cursor_color_3D,
  6278. edge_width=self.defaults["global_cursor_width"],
  6279. size=self.defaults["global_cursor_size"])
  6280. # Set the position label
  6281. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6282. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6283. # Set the relative position label
  6284. dx = location[0] - float(self.rel_point1[0])
  6285. dy = location[1] - float(self.rel_point1[1])
  6286. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6287. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6288. self.inform.emit('[success] %s' % _("Done."))
  6289. return location
  6290. def on_copy_object(self):
  6291. self.report_usage("on_copy_object()")
  6292. def initialize(obj_init, app):
  6293. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6294. try:
  6295. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6296. except AttributeError:
  6297. pass
  6298. try:
  6299. obj_init.apertures = deepcopy(obj.apertures)
  6300. except AttributeError:
  6301. pass
  6302. try:
  6303. if obj.tools:
  6304. obj_init.tools = deepcopy(obj.tools)
  6305. except Exception as e:
  6306. log.debug("App.on_copy_object() --> %s" % str(e))
  6307. try:
  6308. obj_init.source_file = deepcopy(obj.source_file)
  6309. except (AttributeError, TypeError):
  6310. pass
  6311. def initialize_excellon(obj_init, app):
  6312. obj_init.source_file = deepcopy(obj.source_file)
  6313. obj_init.tools = deepcopy(obj.tools)
  6314. # drills are offset, so they need to be deep copied
  6315. obj_init.drills = deepcopy(obj.drills)
  6316. # slots are offset, so they need to be deep copied
  6317. obj_init.slots = deepcopy(obj.slots)
  6318. obj_init.create_geometry()
  6319. def initialize_script(obj_init, app_obj):
  6320. obj_init.source_file = deepcopy(obj.source_file)
  6321. def initialize_document(obj_init, app_obj):
  6322. obj_init.source_file = deepcopy(obj.source_file)
  6323. for obj in self.collection.get_selected():
  6324. obj_name = obj.options["name"]
  6325. try:
  6326. if isinstance(obj, FlatCAMExcellon):
  6327. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6328. elif isinstance(obj, FlatCAMGerber):
  6329. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6330. elif isinstance(obj, FlatCAMGeometry):
  6331. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6332. elif isinstance(obj, FlatCAMScript):
  6333. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6334. elif isinstance(obj, FlatCAMDocument):
  6335. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6336. except Exception as e:
  6337. return "Operation failed: %s" % str(e)
  6338. def on_copy_object2(self, custom_name):
  6339. def initialize_geometry(obj_init, app):
  6340. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6341. try:
  6342. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6343. except AttributeError:
  6344. pass
  6345. try:
  6346. obj_init.apertures = deepcopy(obj.apertures)
  6347. except AttributeError:
  6348. pass
  6349. try:
  6350. if obj.tools:
  6351. obj_init.tools = deepcopy(obj.tools)
  6352. except Exception as ee:
  6353. log.debug("on_copy_object2() --> %s" % str(ee))
  6354. def initialize_gerber(obj_init, app):
  6355. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6356. obj_init.apertures = deepcopy(obj.apertures)
  6357. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6358. def initialize_excellon(obj_init, app):
  6359. obj_init.tools = deepcopy(obj.tools)
  6360. # drills are offset, so they need to be deep copied
  6361. obj_init.drills = deepcopy(obj.drills)
  6362. # slots are offset, so they need to be deep copied
  6363. obj_init.slots = deepcopy(obj.slots)
  6364. obj_init.create_geometry()
  6365. for obj in self.collection.get_selected():
  6366. obj_name = obj.options["name"]
  6367. try:
  6368. if isinstance(obj, FlatCAMExcellon):
  6369. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6370. elif isinstance(obj, FlatCAMGerber):
  6371. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6372. elif isinstance(obj, FlatCAMGeometry):
  6373. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6374. except Exception as e:
  6375. return "Operation failed: %s" % str(e)
  6376. def on_rename_object(self, text):
  6377. self.report_usage("on_rename_object()")
  6378. named_obj = self.collection.get_active()
  6379. for obj in named_obj:
  6380. if obj is list:
  6381. self.on_rename_object(text)
  6382. else:
  6383. try:
  6384. obj.options['name'] = text
  6385. except Exception as e:
  6386. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6387. def convert_any2geo(self):
  6388. self.report_usage("convert_any2geo()")
  6389. def initialize(obj_init, app):
  6390. obj_init.solid_geometry = obj.solid_geometry
  6391. try:
  6392. obj_init.follow_geometry = obj.follow_geometry
  6393. except AttributeError:
  6394. pass
  6395. try:
  6396. obj_init.apertures = obj.apertures
  6397. except AttributeError:
  6398. pass
  6399. try:
  6400. if obj.tools:
  6401. obj_init.tools = obj.tools
  6402. except AttributeError:
  6403. pass
  6404. def initialize_excellon(obj_init, app):
  6405. # objs = self.collection.get_selected()
  6406. # FlatCAMGeometry.merge(objs, obj)
  6407. solid_geo = []
  6408. for tool in obj.tools:
  6409. for geo in obj.tools[tool]['solid_geometry']:
  6410. solid_geo.append(geo)
  6411. obj_init.solid_geometry = deepcopy(solid_geo)
  6412. if not self.collection.get_selected():
  6413. log.warning("App.convert_any2geo --> No object selected")
  6414. self.inform.emit('[WARNING_NOTCL] %s' %
  6415. _("No object is selected. Select an object and try again."))
  6416. return
  6417. for obj in self.collection.get_selected():
  6418. obj_name = obj.options["name"]
  6419. try:
  6420. if isinstance(obj, FlatCAMExcellon):
  6421. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6422. else:
  6423. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6424. except Exception as e:
  6425. return "Operation failed: %s" % str(e)
  6426. def convert_any2gerber(self):
  6427. self.report_usage("convert_any2gerber()")
  6428. def initialize_geometry(obj_init, app):
  6429. apertures = {}
  6430. apid = 0
  6431. apertures[str(apid)] = {}
  6432. apertures[str(apid)]['geometry'] = []
  6433. for obj_orig in obj.solid_geometry:
  6434. new_elem = dict()
  6435. new_elem['solid'] = obj_orig
  6436. try:
  6437. new_elem['follow'] = obj_orig.exterior
  6438. except AttributeError:
  6439. pass
  6440. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6441. apertures[str(apid)]['size'] = 0.0
  6442. apertures[str(apid)]['type'] = 'C'
  6443. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6444. obj_init.apertures = deepcopy(apertures)
  6445. def initialize_excellon(obj_init, app):
  6446. apertures = {}
  6447. apid = 10
  6448. for tool in obj.tools:
  6449. apertures[str(apid)] = {}
  6450. apertures[str(apid)]['geometry'] = []
  6451. for geo in obj.tools[tool]['solid_geometry']:
  6452. new_el = dict()
  6453. new_el['solid'] = geo
  6454. new_el['follow'] = geo.exterior
  6455. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6456. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6457. apertures[str(apid)]['type'] = 'C'
  6458. apid += 1
  6459. # create solid_geometry
  6460. solid_geometry = []
  6461. for apid in apertures:
  6462. for geo_el in apertures[apid]['geometry']:
  6463. solid_geometry.append(geo_el['solid'])
  6464. solid_geometry = MultiPolygon(solid_geometry)
  6465. solid_geometry = solid_geometry.buffer(0.0000001)
  6466. obj_init.solid_geometry = deepcopy(solid_geometry)
  6467. obj_init.apertures = deepcopy(apertures)
  6468. # clear the working objects (perhaps not necessary due of Python GC)
  6469. apertures.clear()
  6470. if not self.collection.get_selected():
  6471. log.warning("App.convert_any2gerber --> No object selected")
  6472. self.inform.emit('[WARNING_NOTCL] %s' %
  6473. _("No object is selected. Select an object and try again."))
  6474. return
  6475. for obj in self.collection.get_selected():
  6476. obj_name = obj.options["name"]
  6477. try:
  6478. if isinstance(obj, FlatCAMExcellon):
  6479. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6480. elif isinstance(obj, FlatCAMGeometry):
  6481. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6482. else:
  6483. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6484. except Exception as e:
  6485. return "Operation failed: %s" % str(e)
  6486. def abort_all_tasks(self):
  6487. if self.abort_flag is False:
  6488. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6489. self.abort_flag = True
  6490. def app_is_idle(self):
  6491. if self.abort_flag:
  6492. self.inform.emit('[WARNING_NOTCL] %s' %
  6493. _("The current task was gracefully closed on user request..."))
  6494. self.abort_flag = False
  6495. def on_selectall(self):
  6496. self.report_usage("on_selectall()")
  6497. # delete the possible selection box around a possible selected object
  6498. self.delete_selection_shape()
  6499. for name in self.collection.get_names():
  6500. self.collection.set_active(name)
  6501. curr_sel_obj = self.collection.get_by_name(name)
  6502. # create the selection box around the selected object
  6503. if self.defaults['global_selection_shape'] is True:
  6504. self.draw_selection_shape(curr_sel_obj)
  6505. def on_preferences(self):
  6506. """
  6507. Adds the Preferences in a Tab in Plot Area
  6508. :return:
  6509. """
  6510. # add the tab if it was closed
  6511. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6512. # delete the absolute and relative position and messages in the infobar
  6513. self.ui.position_label.setText("")
  6514. self.ui.rel_position_label.setText("")
  6515. # Switch plot_area to preferences page
  6516. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6517. # self.ui.show()
  6518. # detect changes in the preferences
  6519. for idx in range(self.ui.pref_tab_area.count()):
  6520. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6521. try:
  6522. try:
  6523. tb.textEdited.disconnect(self.on_preferences_edited)
  6524. except (TypeError, AttributeError):
  6525. pass
  6526. tb.textEdited.connect(self.on_preferences_edited)
  6527. except AttributeError:
  6528. pass
  6529. try:
  6530. try:
  6531. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6532. except (TypeError, AttributeError):
  6533. pass
  6534. tb.modificationChanged.connect(self.on_preferences_edited)
  6535. except AttributeError:
  6536. pass
  6537. try:
  6538. try:
  6539. tb.toggled.disconnect(self.on_preferences_edited)
  6540. except (TypeError, AttributeError):
  6541. pass
  6542. tb.toggled.connect(self.on_preferences_edited)
  6543. except AttributeError:
  6544. pass
  6545. try:
  6546. try:
  6547. tb.valueChanged.disconnect(self.on_preferences_edited)
  6548. except (TypeError, AttributeError):
  6549. pass
  6550. tb.valueChanged.connect(self.on_preferences_edited)
  6551. except AttributeError:
  6552. pass
  6553. try:
  6554. try:
  6555. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6556. except (TypeError, AttributeError):
  6557. pass
  6558. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6559. except AttributeError:
  6560. pass
  6561. def on_preferences_edited(self):
  6562. if self.preferences_changed_flag is False:
  6563. self.inform.emit('[WARNING_NOTCL] %s' % _("Preferences edited but not saved."))
  6564. for idx in range(self.ui.plot_tab_area.count()):
  6565. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  6566. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6567. self.ui.pref_apply_button.setStyleSheet("QPushButton {color: red;}")
  6568. self.preferences_changed_flag = True
  6569. def on_tools_database(self):
  6570. """
  6571. Adds the Tools Database in a Tab in Plot Area
  6572. :return:
  6573. """
  6574. for idx in range(self.ui.plot_tab_area.count()):
  6575. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6576. # there can be only one instance of Tools Database at one time
  6577. return
  6578. self.tools_db_tab = ToolsDB(
  6579. app=self,
  6580. parent=self.ui,
  6581. callback_on_edited=self.on_tools_db_edited,
  6582. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  6583. )
  6584. # add the tab if it was closed
  6585. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  6586. self.tools_db_tab.setObjectName("database_tab")
  6587. # delete the absolute and relative position and messages in the infobar
  6588. self.ui.position_label.setText("")
  6589. self.ui.rel_position_label.setText("")
  6590. # Switch plot_area to preferences page
  6591. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  6592. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  6593. self.tools_db_tab.ui_connect()
  6594. def on_tools_db_edited(self):
  6595. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  6596. for idx in range(self.ui.plot_tab_area.count()):
  6597. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6598. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6599. self.tools_db_changed_flag = True
  6600. def on_geometry_tool_add_from_db_executed(self, tool):
  6601. """
  6602. Here add the tool from DB in the selected geometry object
  6603. :return:
  6604. """
  6605. tool_from_db = deepcopy(tool)
  6606. obj = self.collection.get_active()
  6607. if isinstance(obj, FlatCAMGeometry):
  6608. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6609. for idx in range(self.ui.plot_tab_area.count()):
  6610. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6611. wdg = self.ui.plot_tab_area.widget(idx)
  6612. wdg.deleteLater()
  6613. self.ui.plot_tab_area.removeTab(idx)
  6614. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6615. else:
  6616. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6617. def on_plot_area_tab_closed(self, title):
  6618. if title == _("Preferences"):
  6619. # disconnect
  6620. for idx in range(self.ui.pref_tab_area.count()):
  6621. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6622. try:
  6623. tb.textEdited.disconnect(self.on_preferences_edited)
  6624. except (TypeError, AttributeError):
  6625. pass
  6626. try:
  6627. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6628. except (TypeError, AttributeError):
  6629. pass
  6630. try:
  6631. tb.toggled.disconnect(self.on_preferences_edited)
  6632. except (TypeError, AttributeError):
  6633. pass
  6634. try:
  6635. tb.valueChanged.disconnect(self.on_preferences_edited)
  6636. except (TypeError, AttributeError):
  6637. pass
  6638. try:
  6639. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6640. except (TypeError, AttributeError):
  6641. pass
  6642. if self.preferences_changed_flag is True:
  6643. msgbox = QtWidgets.QMessageBox()
  6644. msgbox.setText(_("One or more values are changed.\n"
  6645. "Do you want to save the Preferences?"))
  6646. msgbox.setWindowTitle(_("Save Preferences"))
  6647. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6648. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6649. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6650. msgbox.setDefaultButton(bt_yes)
  6651. msgbox.exec_()
  6652. response = msgbox.clickedButton()
  6653. if response == bt_yes:
  6654. self.on_save_button(save_to_file=True)
  6655. self.inform.emit('[success] %s' % _("Preferences saved."))
  6656. else:
  6657. self.preferences_changed_flag = False
  6658. self.inform.emit('')
  6659. return
  6660. if title == _("Tools Database"):
  6661. # disconnect the signals from the table widget in tab
  6662. self.tools_db_tab.ui_disconnect()
  6663. if self.tools_db_changed_flag is True:
  6664. msgbox = QtWidgets.QMessageBox()
  6665. msgbox.setText(_("One or more Tools are edited.\n"
  6666. "Do you want to update the Tools Database?"))
  6667. msgbox.setWindowTitle(_("Save Tools Database"))
  6668. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6669. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6670. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6671. msgbox.setDefaultButton(bt_yes)
  6672. msgbox.exec_()
  6673. response = msgbox.clickedButton()
  6674. if response == bt_yes:
  6675. self.tools_db_tab.on_save_tools_db()
  6676. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6677. else:
  6678. self.tools_db_changed_flag = False
  6679. self.inform.emit('')
  6680. return
  6681. self.tools_db_tab.deleteLater()
  6682. if title == _("Code Editor"):
  6683. self.toggle_codeeditor = False
  6684. if title == _("Bookmarks Manager"):
  6685. self.book_dialog_tab.rebuild_actions()
  6686. self.book_dialog_tab.deleteLater()
  6687. def on_flipy(self):
  6688. self.report_usage("on_flipy()")
  6689. obj_list = self.collection.get_selected()
  6690. xminlist = []
  6691. yminlist = []
  6692. xmaxlist = []
  6693. ymaxlist = []
  6694. if not obj_list:
  6695. self.inform.emit('[WARNING_NOTCL] %s' %
  6696. _("No object selected to Flip on Y axis."))
  6697. else:
  6698. try:
  6699. # first get a bounding box to fit all
  6700. for obj in obj_list:
  6701. xmin, ymin, xmax, ymax = obj.bounds()
  6702. xminlist.append(xmin)
  6703. yminlist.append(ymin)
  6704. xmaxlist.append(xmax)
  6705. ymaxlist.append(ymax)
  6706. # get the minimum x,y and maximum x,y for all objects selected
  6707. xminimal = min(xminlist)
  6708. yminimal = min(yminlist)
  6709. xmaximal = max(xmaxlist)
  6710. ymaximal = max(ymaxlist)
  6711. px = 0.5 * (xminimal + xmaximal)
  6712. py = 0.5 * (yminimal + ymaximal)
  6713. # execute mirroring
  6714. for obj in obj_list:
  6715. obj.mirror('X', [px, py])
  6716. obj.plot()
  6717. self.object_changed.emit(obj)
  6718. self.inform.emit('[success] %s' %
  6719. _("Flip on Y axis done."))
  6720. except Exception as e:
  6721. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6722. return
  6723. def on_flipx(self):
  6724. self.report_usage("on_flipx()")
  6725. obj_list = self.collection.get_selected()
  6726. xminlist = []
  6727. yminlist = []
  6728. xmaxlist = []
  6729. ymaxlist = []
  6730. if not obj_list:
  6731. self.inform.emit('[WARNING_NOTCL] %s' %
  6732. _("No object selected to Flip on X axis."))
  6733. else:
  6734. try:
  6735. # first get a bounding box to fit all
  6736. for obj in obj_list:
  6737. xmin, ymin, xmax, ymax = obj.bounds()
  6738. xminlist.append(xmin)
  6739. yminlist.append(ymin)
  6740. xmaxlist.append(xmax)
  6741. ymaxlist.append(ymax)
  6742. # get the minimum x,y and maximum x,y for all objects selected
  6743. xminimal = min(xminlist)
  6744. yminimal = min(yminlist)
  6745. xmaximal = max(xmaxlist)
  6746. ymaximal = max(ymaxlist)
  6747. px = 0.5 * (xminimal + xmaximal)
  6748. py = 0.5 * (yminimal + ymaximal)
  6749. # execute mirroring
  6750. for obj in obj_list:
  6751. obj.mirror('Y', [px, py])
  6752. obj.plot()
  6753. self.object_changed.emit(obj)
  6754. self.inform.emit('[success] %s' %
  6755. _("Flip on X axis done."))
  6756. except Exception as e:
  6757. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6758. return
  6759. def on_rotate(self, silent=False, preset=None):
  6760. self.report_usage("on_rotate()")
  6761. obj_list = self.collection.get_selected()
  6762. xminlist = []
  6763. yminlist = []
  6764. xmaxlist = []
  6765. ymaxlist = []
  6766. if not obj_list:
  6767. self.inform.emit('[WARNING_NOTCL] %s' %
  6768. _("No object selected to Rotate."))
  6769. else:
  6770. if silent is False:
  6771. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6772. min=-360, max=360, decimals=4,
  6773. init_val=float(self.defaults['tools_transform_rotate']))
  6774. num, ok = rotatebox.get_value()
  6775. else:
  6776. num = preset
  6777. ok = True
  6778. if ok:
  6779. try:
  6780. # first get a bounding box to fit all
  6781. for obj in obj_list:
  6782. xmin, ymin, xmax, ymax = obj.bounds()
  6783. xminlist.append(xmin)
  6784. yminlist.append(ymin)
  6785. xmaxlist.append(xmax)
  6786. ymaxlist.append(ymax)
  6787. # get the minimum x,y and maximum x,y for all objects selected
  6788. xminimal = min(xminlist)
  6789. yminimal = min(yminlist)
  6790. xmaximal = max(xmaxlist)
  6791. ymaximal = max(ymaxlist)
  6792. px = 0.5 * (xminimal + xmaximal)
  6793. py = 0.5 * (yminimal + ymaximal)
  6794. for sel_obj in obj_list:
  6795. sel_obj.rotate(-float(num), point=(px, py))
  6796. sel_obj.plot()
  6797. self.object_changed.emit(sel_obj)
  6798. self.inform.emit('[success] %s' %
  6799. _("Rotation done."))
  6800. except Exception as e:
  6801. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6802. return
  6803. def on_skewx(self):
  6804. self.report_usage("on_skewx()")
  6805. obj_list = self.collection.get_selected()
  6806. xminlist = []
  6807. yminlist = []
  6808. if not obj_list:
  6809. self.inform.emit('[WARNING_NOTCL] %s' %
  6810. _("No object selected to Skew/Shear on X axis."))
  6811. else:
  6812. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6813. min=-360, max=360, decimals=4,
  6814. init_val=float(self.defaults['tools_transform_skew_x']))
  6815. num, ok = skewxbox.get_value()
  6816. if ok:
  6817. # first get a bounding box to fit all
  6818. for obj in obj_list:
  6819. xmin, ymin, xmax, ymax = obj.bounds()
  6820. xminlist.append(xmin)
  6821. yminlist.append(ymin)
  6822. # get the minimum x,y and maximum x,y for all objects selected
  6823. xminimal = min(xminlist)
  6824. yminimal = min(yminlist)
  6825. for obj in obj_list:
  6826. obj.skew(num, 0, point=(xminimal, yminimal))
  6827. obj.plot()
  6828. self.object_changed.emit(obj)
  6829. self.inform.emit('[success] %s' %
  6830. _("Skew on X axis done."))
  6831. def on_skewy(self):
  6832. self.report_usage("on_skewy()")
  6833. obj_list = self.collection.get_selected()
  6834. xminlist = []
  6835. yminlist = []
  6836. if not obj_list:
  6837. self.inform.emit('[WARNING_NOTCL] %s' %
  6838. _("No object selected to Skew/Shear on Y axis."))
  6839. else:
  6840. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6841. min=-360, max=360, decimals=4,
  6842. init_val=float(self.defaults['tools_transform_skew_y']))
  6843. num, ok = skewybox.get_value()
  6844. if ok:
  6845. # first get a bounding box to fit all
  6846. for obj in obj_list:
  6847. xmin, ymin, xmax, ymax = obj.bounds()
  6848. xminlist.append(xmin)
  6849. yminlist.append(ymin)
  6850. # get the minimum x,y and maximum x,y for all objects selected
  6851. xminimal = min(xminlist)
  6852. yminimal = min(yminlist)
  6853. for obj in obj_list:
  6854. obj.skew(0, num, point=(xminimal, yminimal))
  6855. obj.plot()
  6856. self.object_changed.emit(obj)
  6857. self.inform.emit('[success] %s' %
  6858. _("Skew on Y axis done."))
  6859. def on_plots_updated(self):
  6860. """
  6861. Callback used to report when the plots have changed.
  6862. Adjust axes and zooms to fit.
  6863. :return: None
  6864. """
  6865. if self.is_legacy is False:
  6866. self.plotcanvas.update() # TODO: Need update canvas?
  6867. else:
  6868. self.plotcanvas.auto_adjust_axes()
  6869. self.on_zoom_fit(None)
  6870. self.collection.update_view()
  6871. # self.inform.emit(_("Plots updated ..."))
  6872. # TODO: Rework toolbar 'clear', 'replot' functions
  6873. def on_toolbar_replot(self):
  6874. """
  6875. Callback for toolbar button. Re-plots all objects.
  6876. :return: None
  6877. """
  6878. self.report_usage("on_toolbar_replot")
  6879. self.log.debug("on_toolbar_replot()")
  6880. try:
  6881. self.collection.get_active().read_form()
  6882. except AttributeError:
  6883. self.log.debug("on_toolbar_replot(): AttributeError")
  6884. pass
  6885. self.plot_all()
  6886. def on_row_activated(self, index):
  6887. if index.isValid():
  6888. if index.internalPointer().parent_item != self.collection.root_item:
  6889. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6890. self.collection.on_item_activated(index)
  6891. def on_row_selected(self, obj_name):
  6892. # this is a special string; when received it will make all entries unchecked
  6893. # it mean we clicked outside of the items and deselected all
  6894. if obj_name == 'none':
  6895. for act in self.ui.menuobjects.actions():
  6896. act.setChecked(False)
  6897. return
  6898. # get the name of the selected objects and add them to a list
  6899. name_list = list()
  6900. for obj in self.collection.get_selected():
  6901. name_list.append(obj.options['name'])
  6902. # set all actions as unchecked but the ones selected make them checked
  6903. for act in self.ui.menuobjects.actions():
  6904. act.setChecked(False)
  6905. if act.text() in name_list:
  6906. act.setChecked(True)
  6907. def on_collection_updated(self, obj, state, old_name):
  6908. """
  6909. Create a menu from the object loaded in the collection.
  6910. TODO: should use the collection model to do this
  6911. :param obj: object that was changd (added, deleted, renamed)
  6912. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6913. :param old_name: the old name of the object before the action that triggered this slot happened
  6914. :return: None
  6915. """
  6916. icon_files = {
  6917. "gerber": self.resource_location + "/flatcam_icon16.png",
  6918. "excellon": self.resource_location + "/drill16.png",
  6919. "cncjob": self.resource_location + "/cnc16.png",
  6920. "geometry": self.resource_location + "/geometry16.png",
  6921. "script": self.resource_location + "/script_new16.png",
  6922. "document": self.resource_location + "/notes16_1.png"
  6923. }
  6924. if state == 'append':
  6925. for act in self.ui.menuobjects.actions():
  6926. try:
  6927. act.triggered.disconnect()
  6928. except TypeError:
  6929. pass
  6930. self.ui.menuobjects.clear()
  6931. gerber_list = list()
  6932. exc_list = list()
  6933. cncjob_list = list()
  6934. geo_list = list()
  6935. script_list = list()
  6936. doc_list = list()
  6937. for name in self.collection.get_names():
  6938. obj_named = self.collection.get_by_name(name)
  6939. if obj_named.kind == 'gerber':
  6940. gerber_list.append(name)
  6941. elif obj_named.kind == 'excellon':
  6942. exc_list.append(name)
  6943. elif obj_named.kind == 'cncjob':
  6944. cncjob_list.append(name)
  6945. elif obj_named.kind == 'geometry':
  6946. geo_list.append(name)
  6947. elif obj_named.kind == 'script':
  6948. script_list.append(name)
  6949. elif obj_named.kind == 'document':
  6950. doc_list.append(name)
  6951. def add_act(o_name):
  6952. obj_for_icon = self.collection.get_by_name(o_name)
  6953. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6954. add_action.setCheckable(True)
  6955. add_action.setText(o_name)
  6956. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6957. add_action.triggered.connect(
  6958. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  6959. self.collection.set_inactive(o_name))
  6960. self.ui.menuobjects.addAction(add_action)
  6961. for name in gerber_list:
  6962. add_act(name)
  6963. self.ui.menuobjects.addSeparator()
  6964. for name in exc_list:
  6965. add_act(name)
  6966. self.ui.menuobjects.addSeparator()
  6967. for name in cncjob_list:
  6968. add_act(name)
  6969. self.ui.menuobjects.addSeparator()
  6970. for name in geo_list:
  6971. add_act(name)
  6972. self.ui.menuobjects.addSeparator()
  6973. for name in script_list:
  6974. add_act(name)
  6975. self.ui.menuobjects.addSeparator()
  6976. for name in doc_list:
  6977. add_act(name)
  6978. self.ui.menuobjects.addSeparator()
  6979. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6980. QtGui.QIcon(self.resource_location + '/select_all.png'),
  6981. _('Select All')
  6982. )
  6983. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6984. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  6985. _('Deselect All')
  6986. )
  6987. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6988. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6989. elif state == 'delete':
  6990. for act in self.ui.menuobjects.actions():
  6991. if act.text() == obj.options['name']:
  6992. try:
  6993. act.triggered.disconnect()
  6994. except TypeError:
  6995. pass
  6996. self.ui.menuobjects.removeAction(act)
  6997. break
  6998. elif state == 'rename':
  6999. for act in self.ui.menuobjects.actions():
  7000. if act.text() == old_name:
  7001. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  7002. add_action.setText(obj.options['name'])
  7003. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  7004. add_action.triggered.connect(
  7005. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  7006. self.collection.set_inactive(obj.options['name']))
  7007. self.ui.menuobjects.insertAction(act, add_action)
  7008. try:
  7009. act.triggered.disconnect()
  7010. except TypeError:
  7011. pass
  7012. self.ui.menuobjects.removeAction(act)
  7013. break
  7014. elif state == 'delete_all':
  7015. for act in self.ui.menuobjects.actions():
  7016. try:
  7017. act.triggered.disconnect()
  7018. except TypeError:
  7019. pass
  7020. self.ui.menuobjects.clear()
  7021. self.ui.menuobjects.addSeparator()
  7022. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  7023. QtGui.QIcon(self.resource_location + '/select_all.png'),
  7024. _('Select All')
  7025. )
  7026. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  7027. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  7028. _('Deselect All')
  7029. )
  7030. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  7031. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  7032. def on_objects_selection(self, on_off):
  7033. obj_list = self.collection.get_names()
  7034. if on_off is True:
  7035. self.collection.set_all_active()
  7036. for act in self.ui.menuobjects.actions():
  7037. try:
  7038. act.setChecked(True)
  7039. except Exception:
  7040. pass
  7041. if obj_list:
  7042. self.inform.emit('[selected] %s' % _("All objects are selected."))
  7043. else:
  7044. self.collection.set_all_inactive()
  7045. for act in self.ui.menuobjects.actions():
  7046. try:
  7047. act.setChecked(False)
  7048. except Exception:
  7049. pass
  7050. if obj_list:
  7051. self.inform.emit('%s' % _("Objects selection is cleared."))
  7052. else:
  7053. self.inform.emit('')
  7054. def grid_status(self):
  7055. if self.ui.grid_snap_btn.isChecked():
  7056. return True
  7057. else:
  7058. return False
  7059. def populate_cmenu_grids(self):
  7060. units = self.defaults['units'].lower()
  7061. for act in self.ui.cmenu_gridmenu.actions():
  7062. act.triggered.disconnect()
  7063. self.ui.cmenu_gridmenu.clear()
  7064. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  7065. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  7066. _("Grid On/Off"))
  7067. grid_toggle.setCheckable(True)
  7068. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  7069. self.ui.cmenu_gridmenu.addSeparator()
  7070. for grid in sorted_list:
  7071. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  7072. "%s" % str(grid))
  7073. action.triggered.connect(self.set_grid)
  7074. self.ui.cmenu_gridmenu.addSeparator()
  7075. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  7076. _("Add"))
  7077. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  7078. _("Delete"))
  7079. grid_add.triggered.connect(self.on_grid_add)
  7080. grid_delete.triggered.connect(self.on_grid_delete)
  7081. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  7082. def set_grid(self):
  7083. self.ui.grid_gap_x_entry.setText(self.sender().text())
  7084. self.ui.grid_gap_y_entry.setText(self.sender().text())
  7085. def on_grid_add(self):
  7086. # ## Current application units in lower Case
  7087. units = self.defaults['units'].lower()
  7088. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  7089. text=_('Enter a Grid Value:'),
  7090. min=0.0000, max=99.9999, decimals=4)
  7091. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  7092. val, ok = grid_add_popup.get_value()
  7093. if ok:
  7094. if float(val) == 0:
  7095. self.inform.emit('[WARNING_NOTCL] %s' %
  7096. _("Please enter a grid value with non-zero value, in Float format."))
  7097. return
  7098. else:
  7099. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  7100. self.defaults["global_grid_context_menu"][str(units)].append(val)
  7101. self.inform.emit('[success] %s...' %
  7102. _("New Grid added"))
  7103. else:
  7104. self.inform.emit('[WARNING_NOTCL] %s...' %
  7105. _("Grid already exists"))
  7106. else:
  7107. self.inform.emit('[WARNING_NOTCL] %s...' %
  7108. _("Adding New Grid cancelled"))
  7109. def on_grid_delete(self):
  7110. # ## Current application units in lower Case
  7111. units = self.defaults['units'].lower()
  7112. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  7113. text='Enter a Grid Value:',
  7114. min=0.0000, max=99.9999, decimals=4)
  7115. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  7116. val, ok = grid_del_popup.get_value()
  7117. if ok:
  7118. if float(val) == 0:
  7119. self.inform.emit('[WARNING_NOTCL] %s' %
  7120. _("Please enter a grid value with non-zero value, in Float format."))
  7121. return
  7122. else:
  7123. try:
  7124. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  7125. except ValueError:
  7126. self.inform.emit('[ERROR_NOTCL]%s...' %
  7127. _(" Grid Value does not exist"))
  7128. return
  7129. self.inform.emit('[success] %s...' %
  7130. _("Grid Value deleted"))
  7131. else:
  7132. self.inform.emit('[WARNING_NOTCL] %s...' %
  7133. _("Delete Grid value cancelled"))
  7134. def on_shortcut_list(self):
  7135. self.report_usage("on_shortcut_list()")
  7136. # add the tab if it was closed
  7137. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  7138. # delete the absolute and relative position and messages in the infobar
  7139. self.ui.position_label.setText("")
  7140. self.ui.rel_position_label.setText("")
  7141. # Switch plot_area to preferences page
  7142. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  7143. # self.ui.show()
  7144. def on_select_tab(self, name):
  7145. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  7146. if self.ui.splitter.sizes()[0] == 0:
  7147. self.ui.splitter.setSizes([1, 1])
  7148. else:
  7149. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  7150. self.ui.splitter.setSizes([0, 1])
  7151. if name == 'project':
  7152. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7153. elif name == 'selected':
  7154. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7155. elif name == 'tool':
  7156. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  7157. def on_copy_name(self):
  7158. self.report_usage("on_copy_name()")
  7159. obj = self.collection.get_active()
  7160. try:
  7161. name = obj.options["name"]
  7162. except AttributeError:
  7163. log.debug("on_copy_name() --> No object selected to copy it's name")
  7164. self.inform.emit('[WARNING_NOTCL]%s' %
  7165. _(" No object selected to copy it's name"))
  7166. return
  7167. self.clipboard.setText(name)
  7168. self.inform.emit(_("Name copied on clipboard ..."))
  7169. def on_mouse_click_over_plot(self, event):
  7170. """
  7171. Default actions are:
  7172. :param event: Contains information about the event, like which button
  7173. was clicked, the pixel coordinates and the axes coordinates.
  7174. :return: None
  7175. """
  7176. self.pos = list()
  7177. if self.is_legacy is False:
  7178. event_pos = event.pos
  7179. pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  7180. # Set the mouse button for panning
  7181. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7182. else:
  7183. event_pos = (event.xdata, event.ydata)
  7184. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7185. pan_button = 3 if self.defaults["global_pan_button"] == '2'else 2
  7186. # So it can receive key presses
  7187. self.plotcanvas.native.setFocus()
  7188. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7189. if self.grid_status() == True:
  7190. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  7191. else:
  7192. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  7193. try:
  7194. if event.button == 1:
  7195. # Reset here the relative coordinates so there is a new reference on the click position
  7196. if self.rel_point1 is None:
  7197. self.rel_point1 = self.pos
  7198. else:
  7199. self.rel_point2 = copy(self.rel_point1)
  7200. self.rel_point1 = self.pos
  7201. self.on_mouse_move_over_plot(event, origin_click=True)
  7202. except Exception as e:
  7203. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  7204. def on_mouse_double_click_over_plot(self, event):
  7205. if event.button == 1:
  7206. self.doubleclick = True
  7207. def on_mouse_move_over_plot(self, event, origin_click=None):
  7208. """
  7209. Callback for the mouse motion event over the plot.
  7210. :param event: Contains information about the event.
  7211. :param origin_click
  7212. :return: None
  7213. """
  7214. if self.is_legacy is False:
  7215. event_pos = event.pos
  7216. if self.defaults["global_pan_button"] == '2':
  7217. pan_button = 2
  7218. else:
  7219. pan_button = 3
  7220. self.event_is_dragging = event.is_dragging
  7221. else:
  7222. event_pos = (event.xdata, event.ydata)
  7223. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7224. if self.defaults["global_pan_button"] == '2':
  7225. pan_button = 3
  7226. else:
  7227. pan_button = 2
  7228. self.event_is_dragging = self.plotcanvas.is_dragging
  7229. # So it can receive key presses
  7230. self.plotcanvas.native.setFocus()
  7231. self.pos_jump = event_pos
  7232. self.ui.popMenu.mouse_is_panning = False
  7233. if not origin_click:
  7234. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7235. if event.button == pan_button and self.event_is_dragging == 1:
  7236. self.ui.popMenu.mouse_is_panning = True
  7237. return
  7238. if self.rel_point1 is not None:
  7239. try: # May fail in case mouse not within axes
  7240. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7241. if self.grid_status() == True:
  7242. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7243. # Update cursor
  7244. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7245. symbol='++', edge_color=self.cursor_color_3D,
  7246. edge_width=self.defaults["global_cursor_width"],
  7247. size=self.defaults["global_cursor_size"])
  7248. else:
  7249. pos = (pos_canvas[0], pos_canvas[1])
  7250. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7251. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7252. dx = pos[0] - float(self.rel_point1[0])
  7253. dy = pos[1] - float(self.rel_point1[1])
  7254. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7255. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  7256. self.mouse = [pos[0], pos[1]]
  7257. # if the mouse is moved and the LMB is clicked then the action is a selection
  7258. if self.event_is_dragging == 1 and event.button == 1:
  7259. self.delete_selection_shape()
  7260. if dx < 0:
  7261. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7262. face_color=self.defaults['global_alt_sel_fill'])
  7263. self.selection_type = False
  7264. elif dx >= 0:
  7265. self.draw_moving_selection_shape(self.pos, pos)
  7266. self.selection_type = True
  7267. else:
  7268. self.selection_type = None
  7269. # hover effect - enabled in Preferences -> General -> GUI Settings
  7270. if self.defaults['global_hover']:
  7271. for obj in self.collection.get_list():
  7272. try:
  7273. # select the object(s) only if it is enabled (plotted)
  7274. if obj.options['plot']:
  7275. if obj not in self.collection.get_selected():
  7276. poly_obj = Polygon(
  7277. [(obj.options['xmin'], obj.options['ymin']),
  7278. (obj.options['xmax'], obj.options['ymin']),
  7279. (obj.options['xmax'], obj.options['ymax']),
  7280. (obj.options['xmin'], obj.options['ymax'])]
  7281. )
  7282. if Point(pos).within(poly_obj):
  7283. if obj.isHovering is False:
  7284. obj.isHovering = True
  7285. obj.notHovering = True
  7286. # create the selection box around the selected object
  7287. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7288. else:
  7289. if obj.notHovering is True:
  7290. obj.notHovering = False
  7291. obj.isHovering = False
  7292. self.delete_hover_shape()
  7293. except Exception:
  7294. # the Exception here will happen if we try to select on screen and we have an
  7295. # newly (and empty) just created Geometry or Excellon object that do not have the
  7296. # xmin, xmax, ymin, ymax options.
  7297. # In this case poly_obj creation (see above) will fail
  7298. pass
  7299. except Exception:
  7300. self.ui.position_label.setText("")
  7301. self.ui.rel_position_label.setText("")
  7302. self.mouse = None
  7303. def on_mouse_click_release_over_plot(self, event):
  7304. """
  7305. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7306. and has been registered in ''self.__init__()''.
  7307. :param event: contains information about the event.
  7308. :return:
  7309. """
  7310. if self.is_legacy is False:
  7311. event_pos = event.pos
  7312. right_button = 2
  7313. else:
  7314. event_pos = (event.xdata, event.ydata)
  7315. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7316. right_button = 3
  7317. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7318. if self.grid_status() == True:
  7319. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7320. else:
  7321. pos = (pos_canvas[0], pos_canvas[1])
  7322. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7323. # canvas menu
  7324. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  7325. self.cursor = QtGui.QCursor()
  7326. self.populate_cmenu_grids()
  7327. self.ui.popMenu.popup(self.cursor.pos())
  7328. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7329. # selection and then select a type of selection ("enclosing" or "touching")
  7330. if event.button == 1: # left click
  7331. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7332. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7333. if modifiers == QtCore.Qt.ShiftModifier:
  7334. # do not auto open the Project Tab
  7335. self.click_noproject = True
  7336. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  7337. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  7338. return
  7339. if self.doubleclick is True:
  7340. self.doubleclick = False
  7341. if self.collection.get_selected():
  7342. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7343. if self.ui.splitter.sizes()[0] == 0:
  7344. self.ui.splitter.setSizes([1, 1])
  7345. try:
  7346. # delete the selection shape(S) as it may be in the way
  7347. self.delete_selection_shape()
  7348. self.delete_hover_shape()
  7349. except Exception as e:
  7350. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  7351. return
  7352. else:
  7353. if self.selection_type is not None:
  7354. try:
  7355. self.selection_area_handler(self.pos, pos, self.selection_type)
  7356. self.selection_type = None
  7357. except Exception as e:
  7358. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  7359. return
  7360. else:
  7361. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7362. if key_modifier == QtCore.Qt.ShiftModifier:
  7363. mod_key = 'Shift'
  7364. elif key_modifier == QtCore.Qt.ControlModifier:
  7365. mod_key = 'Control'
  7366. else:
  7367. mod_key = None
  7368. try:
  7369. if mod_key == self.defaults["global_mselect_key"]:
  7370. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7371. # deselect, and if it's not selected then it will be selected
  7372. # If there is no active command (self.command_active is None) then we check if we clicked
  7373. # on a object by checking the bounding limits against mouse click position
  7374. if self.command_active is None:
  7375. self.select_objects(key='CTRL')
  7376. self.delete_hover_shape()
  7377. else:
  7378. # If there is no active command (self.command_active is None) then we check if we clicked
  7379. # on a object by checking the bounding limits against mouse click position
  7380. if self.command_active is None:
  7381. self.select_objects()
  7382. self.delete_hover_shape()
  7383. except Exception as e:
  7384. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  7385. return
  7386. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7387. """
  7388. :param start_pos: mouse position when the selection LMB click was done
  7389. :param end_pos: mouse position when the left mouse button is released
  7390. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7391. :return:
  7392. """
  7393. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7394. # delete previous selection shape
  7395. self.delete_selection_shape()
  7396. # make all objects inactive
  7397. self.collection.set_all_inactive()
  7398. for obj in self.collection.get_list():
  7399. try:
  7400. # select the object(s) only if it is enabled (plotted)
  7401. if obj.options['plot']:
  7402. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7403. (obj.options['xmax'], obj.options['ymin']),
  7404. (obj.options['xmax'], obj.options['ymax']),
  7405. (obj.options['xmin'], obj.options['ymax'])])
  7406. if sel_type is True:
  7407. if poly_obj.within(poly_selection):
  7408. # create the selection box around the selected object
  7409. if self.defaults['global_selection_shape'] is True:
  7410. self.draw_selection_shape(obj)
  7411. self.collection.set_active(obj.options['name'])
  7412. else:
  7413. if poly_selection.intersects(poly_obj):
  7414. # create the selection box around the selected object
  7415. if self.defaults['global_selection_shape'] is True:
  7416. self.draw_selection_shape(obj)
  7417. self.collection.set_active(obj.options['name'])
  7418. obj.selection_shape_drawn = True
  7419. except Exception as e:
  7420. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7421. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7422. # In this case poly_obj creation (see above) will fail
  7423. log.debug("App.selection_area_handler() --> %s" % str(e))
  7424. def select_objects(self, key=None):
  7425. """
  7426. Will select objects clicked on canvas
  7427. :param key: for future use in cumulative selection
  7428. :return:
  7429. """
  7430. # list where we store the overlapped objects under our mouse left click position
  7431. objects_under_the_click_list = []
  7432. # Populate the list with the overlapped objects on the click position
  7433. curr_x, curr_y = self.pos
  7434. for obj in self.all_objects_list:
  7435. # FlatCAMScript and FlatCAMDocument objects can't be selected
  7436. if isinstance(obj, FlatCAMScript) or isinstance(obj, FlatCAMDocument):
  7437. continue
  7438. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7439. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7440. if obj.options['name'] not in objects_under_the_click_list:
  7441. if obj.options['plot']:
  7442. # add objects to the objects_under_the_click list only if the object is plotted
  7443. # (active and not disabled)
  7444. objects_under_the_click_list.append(obj.options['name'])
  7445. try:
  7446. if objects_under_the_click_list:
  7447. curr_sel_obj = self.collection.get_active()
  7448. # case when there is only an object under the click and we toggle it
  7449. if len(objects_under_the_click_list) == 1:
  7450. if curr_sel_obj is None:
  7451. self.collection.set_active(objects_under_the_click_list[0])
  7452. curr_sel_obj = self.collection.get_active()
  7453. # create the selection box around the selected object
  7454. if self.defaults['global_selection_shape'] is True:
  7455. self.draw_selection_shape(curr_sel_obj)
  7456. curr_sel_obj.selection_shape_drawn = True
  7457. elif curr_sel_obj.options['name'] not in objects_under_the_click_list:
  7458. self.on_objects_selection(False)
  7459. self.delete_selection_shape()
  7460. curr_sel_obj.selection_shape_drawn = False
  7461. self.collection.set_active(objects_under_the_click_list[0])
  7462. curr_sel_obj = self.collection.get_active()
  7463. # create the selection box around the selected object
  7464. if self.defaults['global_selection_shape'] is True:
  7465. self.draw_selection_shape(curr_sel_obj)
  7466. curr_sel_obj.selection_shape_drawn = True
  7467. self.selected_message(curr_sel_obj=curr_sel_obj)
  7468. elif curr_sel_obj.selection_shape_drawn is False:
  7469. if self.defaults['global_selection_shape'] is True:
  7470. self.draw_selection_shape(curr_sel_obj)
  7471. curr_sel_obj.selection_shape_drawn = True
  7472. else:
  7473. self.on_objects_selection(False)
  7474. self.delete_selection_shape()
  7475. if self.call_source != 'app':
  7476. self.call_source = 'app'
  7477. self.selected_message(curr_sel_obj=curr_sel_obj)
  7478. else:
  7479. # If there is no selected object
  7480. # make active the first element of the overlapped objects list
  7481. if self.collection.get_active() is None:
  7482. self.collection.set_active(objects_under_the_click_list[0])
  7483. self.collection.get_by_name(objects_under_the_click_list[0]).selection_shape_drawn = True
  7484. name_sel_obj = self.collection.get_active().options['name']
  7485. # In case that there is a selected object but it is not in the overlapped object list
  7486. # make that object inactive and activate the first element in the overlapped object list
  7487. if name_sel_obj not in objects_under_the_click_list:
  7488. self.collection.set_inactive(name_sel_obj)
  7489. name_sel_obj = objects_under_the_click_list[0]
  7490. self.collection.set_active(name_sel_obj)
  7491. else:
  7492. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7493. self.collection.set_all_inactive()
  7494. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7495. len(objects_under_the_click_list)])
  7496. curr_sel_obj = self.collection.get_active()
  7497. # delete the possible selection box around a possible selected object
  7498. self.delete_selection_shape()
  7499. curr_sel_obj.selection_shape_drawn = False
  7500. # create the selection box around the selected object
  7501. if self.defaults['global_selection_shape'] is True:
  7502. self.draw_selection_shape(curr_sel_obj)
  7503. curr_sel_obj.selection_shape_drawn = True
  7504. self.selected_message(curr_sel_obj=curr_sel_obj)
  7505. else:
  7506. # deselect everything
  7507. self.on_objects_selection(False)
  7508. # delete the possible selection box around a possible selected object
  7509. self.delete_selection_shape()
  7510. for o in self.collection.get_list():
  7511. o.selection_shape_drawn = False
  7512. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7513. # only when working on App
  7514. if self.call_source == 'app':
  7515. if self.click_noproject is False:
  7516. # if the Tool Tab is in focus don't change focus to Project Tab
  7517. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  7518. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7519. else:
  7520. # restore auto open the Project Tab
  7521. self.click_noproject = False
  7522. # delete any text in the status bar, implicitly the last object name that was selected
  7523. # self.inform.emit("")
  7524. else:
  7525. self.call_source = 'app'
  7526. except Exception as e:
  7527. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7528. def selected_message(self, curr_sel_obj):
  7529. if curr_sel_obj:
  7530. if curr_sel_obj.kind == 'gerber':
  7531. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7532. color='green',
  7533. name=str(curr_sel_obj.options['name']),
  7534. tx=_("selected"))
  7535. )
  7536. elif curr_sel_obj.kind == 'excellon':
  7537. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7538. color='brown',
  7539. name=str(curr_sel_obj.options['name']),
  7540. tx=_("selected"))
  7541. )
  7542. elif curr_sel_obj.kind == 'cncjob':
  7543. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7544. color='blue',
  7545. name=str(curr_sel_obj.options['name']),
  7546. tx=_("selected"))
  7547. )
  7548. elif curr_sel_obj.kind == 'geometry':
  7549. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7550. color='red',
  7551. name=str(curr_sel_obj.options['name']),
  7552. tx=_("selected"))
  7553. )
  7554. def delete_hover_shape(self):
  7555. self.hover_shapes.clear()
  7556. self.hover_shapes.redraw()
  7557. def draw_hover_shape(self, sel_obj, color=None):
  7558. """
  7559. :param sel_obj: the object for which the hover shape must be drawn
  7560. :return:
  7561. """
  7562. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7563. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7564. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7565. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7566. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7567. if self.defaults['units'].upper() == 'MM':
  7568. hover_rect = hover_rect.buffer(-0.1)
  7569. hover_rect = hover_rect.buffer(0.2)
  7570. else:
  7571. hover_rect = hover_rect.buffer(-0.00393)
  7572. hover_rect = hover_rect.buffer(0.00787)
  7573. # if color:
  7574. # face = Color(color)
  7575. # face.alpha = 0.2
  7576. # outline = Color(color, alpha=0.8)
  7577. # else:
  7578. # face = Color(self.defaults['global_sel_fill'])
  7579. # face.alpha = 0.2
  7580. # outline = self.defaults['global_sel_line']
  7581. if color:
  7582. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7583. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7584. else:
  7585. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7586. outline = self.defaults['global_sel_line']
  7587. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7588. if self.is_legacy is True:
  7589. self.hover_shapes.redraw()
  7590. def delete_selection_shape(self):
  7591. self.move_tool.sel_shapes.clear()
  7592. self.move_tool.sel_shapes.redraw()
  7593. def draw_selection_shape(self, sel_obj, color=None):
  7594. """
  7595. :param sel_obj: the object for which the selection shape must be drawn
  7596. :return:
  7597. """
  7598. if sel_obj is None:
  7599. return
  7600. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7601. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7602. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7603. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7604. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7605. if self.defaults['units'].upper() == 'MM':
  7606. sel_rect = sel_rect.buffer(-0.1)
  7607. sel_rect = sel_rect.buffer(0.2)
  7608. else:
  7609. sel_rect = sel_rect.buffer(-0.00393)
  7610. sel_rect = sel_rect.buffer(0.00787)
  7611. if color:
  7612. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7613. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7614. else:
  7615. if self.is_legacy is False:
  7616. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7617. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7618. else:
  7619. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7620. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7621. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7622. color=outline,
  7623. face_color=face,
  7624. update=True,
  7625. layer=0,
  7626. tolerance=None))
  7627. if self.is_legacy is True:
  7628. self.move_tool.sel_shapes.redraw()
  7629. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7630. """
  7631. :param old_coords: old coordinates
  7632. :param coords: new coordinates
  7633. :return:
  7634. """
  7635. if 'color' in kwargs:
  7636. color = kwargs['color']
  7637. else:
  7638. color = self.defaults['global_sel_line']
  7639. if 'face_color' in kwargs:
  7640. face_color = kwargs['face_color']
  7641. else:
  7642. face_color = self.defaults['global_sel_fill']
  7643. if 'face_alpha' in kwargs:
  7644. face_alpha = kwargs['face_alpha']
  7645. else:
  7646. face_alpha = 0.3
  7647. x0, y0 = old_coords
  7648. x1, y1 = coords
  7649. pt1 = (x0, y0)
  7650. pt2 = (x1, y0)
  7651. pt3 = (x1, y1)
  7652. pt4 = (x0, y1)
  7653. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7654. # color_t = Color(face_color)
  7655. # color_t.alpha = face_alpha
  7656. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7657. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7658. layer=0, tolerance=None)
  7659. if self.is_legacy is True:
  7660. self.move_tool.sel_shapes.redraw()
  7661. def on_file_new_click(self):
  7662. if self.collection.get_list() and self.should_we_save:
  7663. msgbox = QtWidgets.QMessageBox()
  7664. # msgbox.setText("<B>Save changes ...</B>")
  7665. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7666. "Creating a New project will delete them.\n"
  7667. "Do you want to Save the project?"))
  7668. msgbox.setWindowTitle(_("Save changes"))
  7669. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  7670. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7671. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7672. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7673. msgbox.setDefaultButton(bt_yes)
  7674. msgbox.exec_()
  7675. response = msgbox.clickedButton()
  7676. if response == bt_yes:
  7677. self.on_file_saveprojectas()
  7678. elif response == bt_cancel:
  7679. return
  7680. elif response == bt_no:
  7681. self.on_file_new()
  7682. else:
  7683. self.on_file_new()
  7684. self.inform.emit('[success] %s...' %
  7685. _("New Project created"))
  7686. def on_file_new(self, cli=None):
  7687. """
  7688. Callback for menu item File -> New. Returns the application to its
  7689. startup state. This method is thread-safe.
  7690. :return: None
  7691. """
  7692. self.report_usage("on_file_new")
  7693. # Remove everything from memory
  7694. App.log.debug("on_file_new()")
  7695. if self.call_source != 'app':
  7696. self.editor2object(cleanup=True)
  7697. # ## EDITOR section
  7698. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7699. self.exc_editor = FlatCAMExcEditor(self)
  7700. self.grb_editor = FlatCAMGrbEditor(self)
  7701. # Clear pool
  7702. self.clear_pool()
  7703. for obj in self.collection.get_list():
  7704. # delete shapes left drawn from mark shape_collections, if any
  7705. if isinstance(obj, FlatCAMGerber):
  7706. try:
  7707. obj.mark_shapes.enabled = False
  7708. obj.mark_shapes.clear(update=True)
  7709. except AttributeError:
  7710. pass
  7711. # also delete annotation shapes, if any
  7712. elif isinstance(obj, FlatCAMCNCjob):
  7713. try:
  7714. obj.annotation.enabled = False
  7715. obj.annotation.clear(update=True)
  7716. except AttributeError:
  7717. pass
  7718. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7719. self.init_tcl()
  7720. self.delete_selection_shape()
  7721. self.collection.delete_all()
  7722. self.setup_component_editor()
  7723. # Clear project filename
  7724. self.project_filename = None
  7725. # Load the application defaults
  7726. self.load_defaults(filename='current_defaults')
  7727. # Re-fresh project options
  7728. self.on_options_app2project()
  7729. # Init Tools
  7730. self.init_tools()
  7731. if cli is None:
  7732. # Close any Tabs opened in the Plot Tab Area section
  7733. for index in range(self.ui.plot_tab_area.count()):
  7734. self.ui.plot_tab_area.closeTab(index)
  7735. # for whatever reason previous command does not close the last tab so I do it manually
  7736. self.ui.plot_tab_area.closeTab(0)
  7737. # # And then add again the Plot Area
  7738. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7739. self.ui.plot_tab_area.protectTab(0)
  7740. # take the focus of the Notebook on Project Tab.
  7741. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7742. self.set_ui_title(name=_("New Project - Not saved"))
  7743. def obj_properties(self):
  7744. """
  7745. Will launch the object Properties Tool
  7746. :return:
  7747. """
  7748. self.report_usage("obj_properties()")
  7749. self.properties_tool.run(toggle=False)
  7750. def on_project_context_save(self):
  7751. """
  7752. Wrapper, will save the object function of it's type
  7753. :return:
  7754. """
  7755. obj = self.collection.get_active()
  7756. if type(obj) == FlatCAMGeometry:
  7757. self.on_file_exportdxf()
  7758. elif type(obj) == FlatCAMExcellon:
  7759. self.on_file_saveexcellon()
  7760. elif type(obj) == FlatCAMCNCjob:
  7761. obj.on_exportgcode_button_click()
  7762. elif type(obj) == FlatCAMGerber:
  7763. self.on_file_savegerber()
  7764. elif type(obj) == FlatCAMScript:
  7765. self.on_file_savescript()
  7766. elif type(obj) == FlatCAMDocument:
  7767. self.on_file_savedocument()
  7768. def obj_move(self):
  7769. self.report_usage("obj_move()")
  7770. self.move_tool.run(toggle=False)
  7771. def on_fileopengerber(self, signal: bool = None, name=None):
  7772. """
  7773. File menu callback for opening a Gerber.
  7774. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7775. :return: None
  7776. """
  7777. self.report_usage("on_fileopengerber")
  7778. App.log.debug("on_fileopengerber()")
  7779. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7780. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7781. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7782. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7783. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7784. "*.mil);;" \
  7785. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7786. "Allegro Files (*.art);;" \
  7787. "Mentor Files (*.pho *.gdo);;" \
  7788. "All Files (*.*)"
  7789. if name is None:
  7790. try:
  7791. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7792. directory=self.get_last_folder(),
  7793. filter=_filter_)
  7794. except TypeError:
  7795. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7796. filenames = [str(filename) for filename in filenames]
  7797. else:
  7798. filenames = [name]
  7799. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7800. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7801. _("Opening Gerber file.")),
  7802. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7803. color=QtGui.QColor("gray"))
  7804. if len(filenames) == 0:
  7805. self.inform.emit('[WARNING_NOTCL] %s' %
  7806. _("Open Gerber cancelled."))
  7807. else:
  7808. for filename in filenames:
  7809. if filename != '':
  7810. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7811. def on_fileopenexcellon(self, signal: bool = None, name=None):
  7812. """
  7813. File menu callback for opening an Excellon file.
  7814. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7815. :return: None
  7816. """
  7817. self.report_usage("on_fileopenexcellon")
  7818. App.log.debug("on_fileopenexcellon()")
  7819. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7820. "All Files (*.*)"
  7821. if name is None:
  7822. try:
  7823. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7824. directory=self.get_last_folder(),
  7825. filter=_filter_)
  7826. except TypeError:
  7827. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7828. filenames = [str(filename) for filename in filenames]
  7829. else:
  7830. filenames = [str(name)]
  7831. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7832. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7833. _("Opening Excellon file.")),
  7834. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7835. color=QtGui.QColor("gray"))
  7836. if len(filenames) == 0:
  7837. self.inform.emit('[WARNING_NOTCL]%s' %
  7838. _(" Open Excellon cancelled."))
  7839. else:
  7840. for filename in filenames:
  7841. if filename != '':
  7842. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7843. def on_fileopengcode(self, signal: bool = None, name=None):
  7844. """
  7845. File menu call back for opening gcode.
  7846. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7847. :return: None
  7848. """
  7849. self.report_usage("on_fileopengcode")
  7850. App.log.debug("on_fileopengcode()")
  7851. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7852. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7853. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  7854. "All Files (*.*)"
  7855. if name is None:
  7856. try:
  7857. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7858. directory=self.get_last_folder(),
  7859. filter=_filter_)
  7860. except TypeError:
  7861. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7862. filenames = [str(filename) for filename in filenames]
  7863. else:
  7864. filenames = [name]
  7865. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7866. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7867. _("Opening G-Code file.")),
  7868. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7869. color=QtGui.QColor("gray"))
  7870. if len(filenames) == 0:
  7871. self.inform.emit('[WARNING_NOTCL] %s' %
  7872. _("Open G-Code cancelled."))
  7873. else:
  7874. for filename in filenames:
  7875. if filename != '':
  7876. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7877. def on_file_openproject(self, signal: bool = None):
  7878. """
  7879. File menu callback for opening a project.
  7880. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7881. :return: None
  7882. """
  7883. self.report_usage("on_file_openproject")
  7884. App.log.debug("on_file_openproject()")
  7885. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7886. try:
  7887. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7888. directory=self.get_last_folder(), filter=_filter_)
  7889. except TypeError:
  7890. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7891. # The Qt methods above will return a QString which can cause problems later.
  7892. # So far json.dump() will fail to serialize it.
  7893. # TODO: Improve the serialization methods and remove this fix.
  7894. filename = str(filename)
  7895. if filename == "":
  7896. self.inform.emit('[WARNING_NOTCL] %s' %
  7897. _("Open Project cancelled."))
  7898. else:
  7899. # self.worker_task.emit({'fcn': self.open_project,
  7900. # 'params': [filename]})
  7901. # The above was failing because open_project() is not
  7902. # thread safe. The new_project()
  7903. self.open_project(filename)
  7904. def on_fileopenhpgl2(self, signal: bool = None, name=None):
  7905. """
  7906. File menu callback for opening a HPGL2.
  7907. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7908. :return: None
  7909. """
  7910. self.report_usage("on_fileopenhpgl2")
  7911. App.log.debug("on_fileopenhpgl2()")
  7912. _filter_ = "HPGL2 Files (*.plt);;" \
  7913. "All Files (*.*)"
  7914. if name is None:
  7915. try:
  7916. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  7917. directory=self.get_last_folder(),
  7918. filter=_filter_)
  7919. except TypeError:
  7920. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  7921. filenames = [str(filename) for filename in filenames]
  7922. else:
  7923. filenames = [name]
  7924. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7925. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7926. _("Opening HPGL2 file.")),
  7927. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7928. color=QtGui.QColor("gray"))
  7929. if len(filenames) == 0:
  7930. self.inform.emit('[WARNING_NOTCL] %s' % _("Open HPGL2 file cancelled."))
  7931. else:
  7932. for filename in filenames:
  7933. if filename != '':
  7934. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  7935. def on_file_openconfig(self, signal: bool = None):
  7936. """
  7937. File menu callback for opening a config file.
  7938. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7939. :return: None
  7940. """
  7941. self.report_usage("on_file_openconfig")
  7942. App.log.debug("on_file_openconfig()")
  7943. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7944. try:
  7945. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7946. directory=self.data_path, filter=_filter_)
  7947. except TypeError:
  7948. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7949. filter=_filter_)
  7950. if filename == "":
  7951. self.inform.emit('[WARNING_NOTCL] %s' %
  7952. _("Open Config cancelled."))
  7953. else:
  7954. self.open_config_file(filename)
  7955. def on_file_exportsvg(self):
  7956. """
  7957. Callback for menu item File->Export SVG.
  7958. :return: None
  7959. """
  7960. self.report_usage("on_file_exportsvg")
  7961. App.log.debug("on_file_exportsvg()")
  7962. obj = self.collection.get_active()
  7963. if obj is None:
  7964. self.inform.emit('[WARNING_NOTCL] %s' %
  7965. _("No object selected."))
  7966. msg = _("Please Select a Geometry object to export")
  7967. msgbox = QtWidgets.QMessageBox()
  7968. msgbox.setInformativeText(msg)
  7969. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7970. msgbox.setDefaultButton(bt_ok)
  7971. msgbox.exec_()
  7972. return
  7973. # Check for more compatible types and add as required
  7974. if (not isinstance(obj, FlatCAMGeometry)
  7975. and not isinstance(obj, FlatCAMGerber)
  7976. and not isinstance(obj, FlatCAMCNCjob)
  7977. and not isinstance(obj, FlatCAMExcellon)):
  7978. msg = '[ERROR_NOTCL] %s' % \
  7979. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7980. msgbox = QtWidgets.QMessageBox()
  7981. msgbox.setInformativeText(msg)
  7982. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7983. msgbox.setDefaultButton(bt_ok)
  7984. msgbox.exec_()
  7985. return
  7986. name = obj.options["name"]
  7987. _filter = "SVG File (*.svg);;All Files (*.*)"
  7988. try:
  7989. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7990. caption=_("Export SVG"),
  7991. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7992. filter=_filter)
  7993. except TypeError:
  7994. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7995. filename = str(filename)
  7996. if filename == "":
  7997. self.inform.emit('[WARNING_NOTCL]%s' %
  7998. _(" Export SVG cancelled."))
  7999. return
  8000. else:
  8001. self.export_svg(name, filename)
  8002. if self.defaults["global_open_style"] is False:
  8003. self.file_opened.emit("SVG", filename)
  8004. self.file_saved.emit("SVG", filename)
  8005. def on_file_exportpng(self):
  8006. self.report_usage("on_file_exportpng")
  8007. App.log.debug("on_file_exportpng()")
  8008. self.date = str(datetime.today()).rpartition('.')[0]
  8009. self.date = ''.join(c for c in self.date if c not in ':-')
  8010. self.date = self.date.replace(' ', '_')
  8011. if self.is_legacy is False:
  8012. image = _screenshot()
  8013. data = np.asarray(image)
  8014. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  8015. self.inform.emit('[[WARNING_NOTCL]] %s' %
  8016. _('Data must be a 3D array with last dimension 3 or 4'))
  8017. return
  8018. filter_ = "PNG File (*.png);;All Files (*.*)"
  8019. try:
  8020. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8021. caption=_("Export PNG Image"),
  8022. directory=self.get_last_save_folder() + '/png_' + self.date,
  8023. filter=filter_)
  8024. except TypeError:
  8025. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  8026. filename = str(filename)
  8027. if filename == "":
  8028. self.inform.emit(_("Export PNG cancelled."))
  8029. return
  8030. else:
  8031. if self.is_legacy is False:
  8032. write_png(filename, data)
  8033. else:
  8034. self.plotcanvas.figure.savefig(filename)
  8035. if self.defaults["global_open_style"] is False:
  8036. self.file_opened.emit("png", filename)
  8037. self.file_saved.emit("png", filename)
  8038. def on_file_savegerber(self):
  8039. """
  8040. Callback for menu item in Project context menu.
  8041. :return: None
  8042. """
  8043. self.report_usage("on_file_savegerber")
  8044. App.log.debug("on_file_savegerber()")
  8045. obj = self.collection.get_active()
  8046. if obj is None:
  8047. self.inform.emit('[WARNING_NOTCL] %s' %
  8048. _("No object selected. Please select an Gerber object to export."))
  8049. return
  8050. # Check for more compatible types and add as required
  8051. if not isinstance(obj, FlatCAMGerber):
  8052. self.inform.emit('[ERROR_NOTCL] %s' %
  8053. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8054. return
  8055. name = self.collection.get_active().options["name"]
  8056. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  8057. try:
  8058. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8059. caption="Save Gerber source file",
  8060. directory=self.get_last_save_folder() + '/' + name,
  8061. filter=_filter)
  8062. except TypeError:
  8063. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  8064. filename = str(filename)
  8065. if filename == "":
  8066. self.inform.emit('[WARNING_NOTCL] %s' %
  8067. _("Save Gerber source file cancelled."))
  8068. return
  8069. else:
  8070. self.save_source_file(name, filename)
  8071. if self.defaults["global_open_style"] is False:
  8072. self.file_opened.emit("Gerber", filename)
  8073. self.file_saved.emit("Gerber", filename)
  8074. def on_file_savescript(self):
  8075. """
  8076. Callback for menu item in Project context menu.
  8077. :return: None
  8078. """
  8079. self.report_usage("on_file_savescript")
  8080. App.log.debug("on_file_savescript()")
  8081. obj = self.collection.get_active()
  8082. if obj is None:
  8083. self.inform.emit('[WARNING_NOTCL] %s' %
  8084. _("No object selected. Please select an Script object to export."))
  8085. return
  8086. # Check for more compatible types and add as required
  8087. if not isinstance(obj, FlatCAMScript):
  8088. self.inform.emit('[ERROR_NOTCL] %s' %
  8089. _("Failed. Only Script objects can be saved as TCL Script files..."))
  8090. return
  8091. name = self.collection.get_active().options["name"]
  8092. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  8093. try:
  8094. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8095. caption="Save Script source file",
  8096. directory=self.get_last_save_folder() + '/' + name,
  8097. filter=_filter)
  8098. except TypeError:
  8099. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  8100. filename = str(filename)
  8101. if filename == "":
  8102. self.inform.emit('[WARNING_NOTCL] %s' %
  8103. _("Save Script source file cancelled."))
  8104. return
  8105. else:
  8106. self.save_source_file(name, filename)
  8107. if self.defaults["global_open_style"] is False:
  8108. self.file_opened.emit("Script", filename)
  8109. self.file_saved.emit("Script", filename)
  8110. def on_file_savedocument(self):
  8111. """
  8112. Callback for menu item in Project context menu.
  8113. :return: None
  8114. """
  8115. self.report_usage("on_file_savedocument")
  8116. App.log.debug("on_file_savedocument()")
  8117. obj = self.collection.get_active()
  8118. if obj is None:
  8119. self.inform.emit('[WARNING_NOTCL] %s' %
  8120. _("No object selected. Please select an Document object to export."))
  8121. return
  8122. # Check for more compatible types and add as required
  8123. if not isinstance(obj, FlatCAMScript):
  8124. self.inform.emit('[ERROR_NOTCL] %s' %
  8125. _("Failed. Only Document objects can be saved as Document files..."))
  8126. return
  8127. name = self.collection.get_active().options["name"]
  8128. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  8129. try:
  8130. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8131. caption="Save Document source file",
  8132. directory=self.get_last_save_folder() + '/' + name,
  8133. filter=_filter)
  8134. except TypeError:
  8135. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  8136. filename = str(filename)
  8137. if filename == "":
  8138. self.inform.emit('[WARNING_NOTCL] %s' %
  8139. _("Save Document source file cancelled."))
  8140. return
  8141. else:
  8142. self.save_source_file(name, filename)
  8143. if self.defaults["global_open_style"] is False:
  8144. self.file_opened.emit("Document", filename)
  8145. self.file_saved.emit("Document", filename)
  8146. def on_file_saveexcellon(self):
  8147. """
  8148. Callback for menu item in project context menu.
  8149. :return: None
  8150. """
  8151. self.report_usage("on_file_saveexcellon")
  8152. App.log.debug("on_file_saveexcellon()")
  8153. obj = self.collection.get_active()
  8154. if obj is None:
  8155. self.inform.emit('[WARNING_NOTCL] %s' %
  8156. _("No object selected. Please select an Excellon object to export."))
  8157. return
  8158. # Check for more compatible types and add as required
  8159. if not isinstance(obj, FlatCAMExcellon):
  8160. self.inform.emit('[ERROR_NOTCL] %s' %
  8161. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8162. return
  8163. name = self.collection.get_active().options["name"]
  8164. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  8165. try:
  8166. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8167. caption=_("Save Excellon source file"),
  8168. directory=self.get_last_save_folder() + '/' + name,
  8169. filter=_filter)
  8170. except TypeError:
  8171. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  8172. filename = str(filename)
  8173. if filename == "":
  8174. self.inform.emit('[WARNING_NOTCL] %s' %
  8175. _("Saving Excellon source file cancelled."))
  8176. return
  8177. else:
  8178. self.save_source_file(name, filename)
  8179. if self.defaults["global_open_style"] is False:
  8180. self.file_opened.emit("Excellon", filename)
  8181. self.file_saved.emit("Excellon", filename)
  8182. def on_file_exportexcellon(self):
  8183. """
  8184. Callback for menu item File->Export->Excellon.
  8185. :return: None
  8186. """
  8187. self.report_usage("on_file_exportexcellon")
  8188. App.log.debug("on_file_exportexcellon()")
  8189. obj = self.collection.get_active()
  8190. if obj is None:
  8191. self.inform.emit('[WARNING_NOTCL] %s' %
  8192. _("No object selected. Please Select an Excellon object to export."))
  8193. return
  8194. # Check for more compatible types and add as required
  8195. if not isinstance(obj, FlatCAMExcellon):
  8196. self.inform.emit('[ERROR_NOTCL] %s' %
  8197. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8198. return
  8199. name = self.collection.get_active().options["name"]
  8200. _filter = self.defaults["excellon_save_filters"]
  8201. try:
  8202. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8203. caption=_("Export Excellon"),
  8204. directory=self.get_last_save_folder() + '/' + name,
  8205. filter=_filter)
  8206. except TypeError:
  8207. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  8208. filename = str(filename)
  8209. if filename == "":
  8210. self.inform.emit('[WARNING_NOTCL] %s' %
  8211. _("Export Excellon cancelled."))
  8212. return
  8213. else:
  8214. used_extension = filename.rpartition('.')[2]
  8215. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  8216. self.export_excellon(name, filename)
  8217. if self.defaults["global_open_style"] is False:
  8218. self.file_opened.emit("Excellon", filename)
  8219. self.file_saved.emit("Excellon", filename)
  8220. def on_file_exportgerber(self):
  8221. """
  8222. Callback for menu item File->Export->Gerber.
  8223. :return: None
  8224. """
  8225. self.report_usage("on_file_exportgerber")
  8226. App.log.debug("on_file_exportgerber()")
  8227. obj = self.collection.get_active()
  8228. if obj is None:
  8229. self.inform.emit('[WARNING_NOTCL] %s' %
  8230. _("No object selected. Please Select an Gerber object to export."))
  8231. return
  8232. # Check for more compatible types and add as required
  8233. if not isinstance(obj, FlatCAMGerber):
  8234. self.inform.emit('[ERROR_NOTCL] %s' %
  8235. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8236. return
  8237. name = self.collection.get_active().options["name"]
  8238. _filter_ = self.defaults['gerber_save_filters']
  8239. try:
  8240. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8241. caption=_("Export Gerber"),
  8242. directory=self.get_last_save_folder() + '/' + name,
  8243. filter=_filter_)
  8244. except TypeError:
  8245. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  8246. filename = str(filename)
  8247. if filename == "":
  8248. self.inform.emit('[WARNING_NOTCL] %s' %
  8249. _("Export Gerber cancelled."))
  8250. return
  8251. else:
  8252. used_extension = filename.rpartition('.')[2]
  8253. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  8254. self.export_gerber(name, filename)
  8255. if self.defaults["global_open_style"] is False:
  8256. self.file_opened.emit("Gerber", filename)
  8257. self.file_saved.emit("Gerber", filename)
  8258. def on_file_exportdxf(self):
  8259. """
  8260. Callback for menu item File->Export DXF.
  8261. :return: None
  8262. """
  8263. self.report_usage("on_file_exportdxf")
  8264. App.log.debug("on_file_exportdxf()")
  8265. obj = self.collection.get_active()
  8266. if obj is None:
  8267. self.inform.emit('[WARNING_NOTCL] %s' %
  8268. _("No object selected."))
  8269. msg = _("Please Select a Geometry object to export")
  8270. msgbox = QtWidgets.QMessageBox()
  8271. msgbox.setInformativeText(msg)
  8272. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8273. msgbox.setDefaultButton(bt_ok)
  8274. msgbox.exec_()
  8275. return
  8276. # Check for more compatible types and add as required
  8277. if not isinstance(obj, FlatCAMGeometry):
  8278. msg = '[ERROR_NOTCL] %s' % \
  8279. _("Only Geometry objects can be used.")
  8280. msgbox = QtWidgets.QMessageBox()
  8281. msgbox.setInformativeText(msg)
  8282. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8283. msgbox.setDefaultButton(bt_ok)
  8284. msgbox.exec_()
  8285. return
  8286. name = self.collection.get_active().options["name"]
  8287. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8288. try:
  8289. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8290. caption=_("Export DXF"),
  8291. directory=self.get_last_save_folder() + '/' + name,
  8292. filter=_filter_)
  8293. except TypeError:
  8294. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  8295. filter=_filter_)
  8296. filename = str(filename)
  8297. if filename == "":
  8298. self.inform.emit('[WARNING_NOTCL] %s' %
  8299. _("Export DXF cancelled."))
  8300. return
  8301. else:
  8302. self.export_dxf(name, filename)
  8303. if self.defaults["global_open_style"] is False:
  8304. self.file_opened.emit("DXF", filename)
  8305. self.file_saved.emit("DXF", filename)
  8306. def on_file_importsvg(self, type_of_obj):
  8307. """
  8308. Callback for menu item File->Import SVG.
  8309. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8310. :type type_of_obj: str
  8311. :return: None
  8312. """
  8313. self.report_usage("on_file_importsvg")
  8314. App.log.debug("on_file_importsvg()")
  8315. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  8316. try:
  8317. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8318. directory=self.get_last_folder(), filter=_filter_)
  8319. except TypeError:
  8320. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8321. filter=_filter_)
  8322. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8323. type_of_obj = "geometry"
  8324. filenames = [str(filename) for filename in filenames]
  8325. if len(filenames) == 0:
  8326. self.inform.emit('[WARNING_NOTCL] %s' %
  8327. _("Open SVG cancelled."))
  8328. else:
  8329. for filename in filenames:
  8330. if filename != '':
  8331. self.worker_task.emit({'fcn': self.import_svg,
  8332. 'params': [filename, type_of_obj]})
  8333. def on_file_importdxf(self, type_of_obj):
  8334. """
  8335. Callback for menu item File->Import DXF.
  8336. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8337. :type type_of_obj: str
  8338. :return: None
  8339. """
  8340. self.report_usage("on_file_importdxf")
  8341. App.log.debug("on_file_importdxf()")
  8342. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8343. try:
  8344. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8345. directory=self.get_last_folder(),
  8346. filter=_filter_)
  8347. except TypeError:
  8348. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8349. filter=_filter_)
  8350. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8351. type_of_obj = "geometry"
  8352. filenames = [str(filename) for filename in filenames]
  8353. if len(filenames) == 0:
  8354. self.inform.emit('[WARNING_NOTCL] %s' %
  8355. _("Open DXF cancelled."))
  8356. else:
  8357. for filename in filenames:
  8358. if filename != '':
  8359. self.worker_task.emit({'fcn': self.import_dxf,
  8360. 'params': [filename, type_of_obj]})
  8361. # ###############################################################################################################
  8362. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8363. # ###############################################################################################################
  8364. def init_code_editor(self, name):
  8365. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  8366. # add the tab if it was closed
  8367. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8368. self.text_editor_tab.setObjectName('text_editor_tab')
  8369. # delete the absolute and relative position and messages in the infobar
  8370. self.ui.position_label.setText("")
  8371. self.ui.rel_position_label.setText("")
  8372. # first clear previous text in text editor (if any)
  8373. self.text_editor_tab.code_editor.clear()
  8374. self.text_editor_tab.code_editor.setReadOnly(False)
  8375. self.toggle_codeeditor = True
  8376. self.text_editor_tab.code_editor.completer_enable = False
  8377. self.text_editor_tab.buttonRun.hide()
  8378. # make sure to keep a reference to the code editor
  8379. self.reference_code_editor = self.text_editor_tab.code_editor
  8380. # Switch plot_area to CNCJob tab
  8381. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8382. def on_view_source(self):
  8383. """
  8384. Called when the user wants to see the source file of the selected object
  8385. :return:
  8386. """
  8387. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8388. self.proc_container.view.set_busy(_("Loading..."))
  8389. try:
  8390. obj = self.collection.get_active()
  8391. except Exception as e:
  8392. log.debug("App.on_view_source() --> %s" % str(e))
  8393. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8394. return 'fail'
  8395. if obj is None:
  8396. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8397. return 'fail'
  8398. flt = "All Files (*.*)"
  8399. if obj.kind == 'gerber':
  8400. flt = "Gerber Files (*.GBR);;PDF Files (*.PDF);;All Files (*.*)"
  8401. elif obj.kind == 'excellon':
  8402. flt = "Excellon Files (*.DRL);;PDF Files (*.PDF);;All Files (*.*)"
  8403. elif obj.kind == 'cncjob':
  8404. flt = "GCode Files (*.NC);;PDF Files (*.PDF);;All Files (*.*)"
  8405. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  8406. # add the tab if it was closed
  8407. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8408. self.source_editor_tab.setObjectName('source_editor_tab')
  8409. # delete the absolute and relative position and messages in the infobar
  8410. self.ui.position_label.setText("")
  8411. self.ui.rel_position_label.setText("")
  8412. # first clear previous text in text editor (if any)
  8413. self.source_editor_tab.code_editor.clear()
  8414. self.source_editor_tab.code_editor.setReadOnly(False)
  8415. self.source_editor_tab.code_editor.completer_enable = False
  8416. self.source_editor_tab.buttonRun.hide()
  8417. # Switch plot_area to CNCJob tab
  8418. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8419. try:
  8420. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8421. except TypeError:
  8422. pass
  8423. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8424. try:
  8425. self.source_editor_tab.buttonSave.clicked.disconnect()
  8426. except TypeError:
  8427. pass
  8428. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8429. # then append the text from GCode to the text editor
  8430. if obj.kind == 'cncjob':
  8431. try:
  8432. file = obj.export_gcode(
  8433. preamble=self.defaults["cncjob_prepend"],
  8434. postamble=self.defaults["cncjob_append"],
  8435. to_file=True)
  8436. if file == 'fail':
  8437. return 'fail'
  8438. except AttributeError:
  8439. self.inform.emit('[WARNING_NOTCL] %s' %
  8440. _("There is no selected object for which to see it's source file code."))
  8441. return 'fail'
  8442. else:
  8443. try:
  8444. file = StringIO(obj.source_file)
  8445. except (AttributeError, TypeError):
  8446. self.inform.emit('[WARNING_NOTCL] %s' %
  8447. _("There is no selected object for which to see it's source file code."))
  8448. return 'fail'
  8449. self.source_editor_tab.t_frame.hide()
  8450. try:
  8451. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  8452. # for line in file:
  8453. # QtWidgets.QApplication.processEvents()
  8454. # proc_line = str(line).strip('\n')
  8455. # self.source_editor_tab.code_editor.append(proc_line)
  8456. except Exception as e:
  8457. log.debug('App.on_view_source() -->%s' % str(e))
  8458. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  8459. return
  8460. self.source_editor_tab.handleTextChanged()
  8461. self.source_editor_tab.t_frame.show()
  8462. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8463. self.proc_container.view.set_idle()
  8464. # self.ui.show()
  8465. def on_toggle_code_editor(self):
  8466. self.report_usage("on_toggle_code_editor()")
  8467. if self.toggle_codeeditor is False:
  8468. self.init_code_editor(name=_("Code Editor"))
  8469. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8470. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8471. self.text_editor_tab.buttonSave.clicked.disconnect()
  8472. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8473. else:
  8474. for idx in range(self.ui.plot_tab_area.count()):
  8475. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8476. self.ui.plot_tab_area.closeTab(idx)
  8477. break
  8478. self.toggle_codeeditor = False
  8479. def on_code_editor_close(self):
  8480. self.toggle_codeeditor = False
  8481. def goto_text_line(self):
  8482. """
  8483. Will scroll a text to the specified text line.
  8484. :return: None
  8485. """
  8486. dia_box = Dialog_box(title=_("Go to Line ..."),
  8487. label=_("Line:"),
  8488. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  8489. initial_text='')
  8490. try:
  8491. line = int(dia_box.location) - 1
  8492. except (ValueError, TypeError):
  8493. line = 0
  8494. if dia_box.ok:
  8495. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  8496. # at the top of the window
  8497. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  8498. # get the document() of the TextEditor
  8499. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  8500. # create a Text Cursor based on the searched line
  8501. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  8502. # set cursor of the code editor with the cursor at the searcehd line
  8503. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  8504. def on_filenewscript(self, silent=False, name=None, text=None):
  8505. """
  8506. Will create a new script file and open it in the Code Editor
  8507. :param silent: if True will not display status messages
  8508. :param name: if specified will be the name of the new script
  8509. :param text: pass a source file to the newly created script to be loaded in it
  8510. :return: None
  8511. """
  8512. if silent is False:
  8513. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  8514. # delete the absolute and relative position and messages in the infobar
  8515. self.ui.position_label.setText("")
  8516. self.ui.rel_position_label.setText("")
  8517. if name is not None:
  8518. self.new_script_object(name=name, text=text)
  8519. else:
  8520. self.new_script_object(text=text)
  8521. # script_text = script_obj.source_file
  8522. #
  8523. # self.proc_container.view.set_busy(_("Loading..."))
  8524. # script_obj.script_editor_tab.t_frame.hide()
  8525. #
  8526. # script_obj.script_editor_tab.t_frame.show()
  8527. # self.proc_container.view.set_idle()
  8528. def on_fileopenscript(self, name=None, silent=False):
  8529. """
  8530. Will open a Tcl script file into the Code Editor
  8531. :param silent: if True will not display status messages
  8532. :param name: name of a Tcl script file to open
  8533. :return:
  8534. """
  8535. self.report_usage("on_fileopenscript")
  8536. App.log.debug("on_fileopenscript()")
  8537. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8538. if name:
  8539. filenames = [name]
  8540. else:
  8541. try:
  8542. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8543. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8544. except TypeError:
  8545. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8546. if len(filenames) == 0:
  8547. if silent is False:
  8548. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8549. else:
  8550. for filename in filenames:
  8551. if filename != '':
  8552. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8553. def on_filerunscript(self, name=None, silent=False):
  8554. """
  8555. File menu callback for loading and running a TCL script.
  8556. :param silent: if True will not display status messages
  8557. :param name: name of a Tcl script file to be run by FlatCAM
  8558. :return: None
  8559. """
  8560. self.report_usage("on_filerunscript")
  8561. App.log.debug("on_file_runscript()")
  8562. if name:
  8563. filename = name
  8564. if self.cmd_line_headless != 1:
  8565. self.splash.showMessage('%s: %ssec\n%s' %
  8566. (_("Canvas initialization started.\n"
  8567. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8568. _("Executing FlatCAMScript file.")
  8569. ),
  8570. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8571. color=QtGui.QColor("gray"))
  8572. else:
  8573. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8574. try:
  8575. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8576. directory=self.get_last_folder(), filter=_filter_)
  8577. except TypeError:
  8578. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8579. # The Qt methods above will return a QString which can cause problems later.
  8580. # So far json.dump() will fail to serialize it.
  8581. # TODO: Improve the serialization methods and remove this fix.
  8582. filename = str(filename)
  8583. if filename == "":
  8584. if silent is False:
  8585. self.inform.emit('[WARNING_NOTCL] %s' % _("Run TCL script cancelled."))
  8586. else:
  8587. if self.cmd_line_headless != 1:
  8588. if self.ui.shell_dock.isHidden():
  8589. self.ui.shell_dock.show()
  8590. try:
  8591. with open(filename, "r") as tcl_script:
  8592. cmd_line_shellfile_content = tcl_script.read()
  8593. if self.cmd_line_headless != 1:
  8594. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8595. else:
  8596. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8597. if silent is False:
  8598. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  8599. except Exception as e:
  8600. log.debug("App.on_filerunscript() -> %s" % str(e))
  8601. sys.exit(2)
  8602. def on_file_saveproject(self, silent=False):
  8603. """
  8604. Callback for menu item File->Save Project. Saves the project to
  8605. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8606. if set to None. The project is saved by calling ``self.save_project()``.
  8607. :param silent: if True will not display status messages
  8608. :return: None
  8609. """
  8610. self.report_usage("on_file_saveproject")
  8611. if self.project_filename is None:
  8612. self.on_file_saveprojectas()
  8613. else:
  8614. self.worker_task.emit({'fcn': self.save_project,
  8615. 'params': [self.project_filename, silent]})
  8616. if self.defaults["global_open_style"] is False:
  8617. self.file_opened.emit("project", self.project_filename)
  8618. self.file_saved.emit("project", self.project_filename)
  8619. self.set_ui_title(name=self.project_filename)
  8620. self.should_we_save = False
  8621. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8622. """
  8623. Callback for menu item File->Save Project As... Opens a file
  8624. chooser and saves the project to the given file via
  8625. ``self.save_project()``.
  8626. :param make_copy if to be create a copy of the project; boolean
  8627. :param use_thread: if to be run in a separate thread; boolean
  8628. :param quit_action: if to be followed by quiting the application; boolean
  8629. :return: None
  8630. """
  8631. self.report_usage("on_file_saveprojectas")
  8632. self.date = str(datetime.today()).rpartition('.')[0]
  8633. self.date = ''.join(c for c in self.date if c not in ':-')
  8634. self.date = self.date.replace(' ', '_')
  8635. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8636. try:
  8637. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8638. caption=_("Save Project As ..."),
  8639. directory=('{l_save}/{proj}_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date,
  8640. proj=_("Project")),
  8641. filter=filter_
  8642. )
  8643. except TypeError:
  8644. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8645. filename = str(filename)
  8646. if filename == '':
  8647. self.inform.emit('[WARNING_NOTCL] %s' % _("Save Project cancelled."))
  8648. return
  8649. if use_thread is True:
  8650. self.worker_task.emit({'fcn': self.save_project,
  8651. 'params': [filename, quit_action]})
  8652. else:
  8653. self.save_project(filename, quit_action)
  8654. # self.save_project(filename)
  8655. if self.defaults["global_open_style"] is False:
  8656. self.file_opened.emit("project", filename)
  8657. self.file_saved.emit("project", filename)
  8658. if not make_copy:
  8659. self.project_filename = filename
  8660. self.set_ui_title(name=self.project_filename)
  8661. self.should_we_save = False
  8662. def on_file_save_objects_pdf(self, use_thread=True):
  8663. self.date = str(datetime.today()).rpartition('.')[0]
  8664. self.date = ''.join(c for c in self.date if c not in ':-')
  8665. self.date = self.date.replace(' ', '_')
  8666. try:
  8667. obj_selection = self.collection.get_selected()
  8668. if len(obj_selection) == 1:
  8669. obj_name = str(obj_selection[0].options['name'])
  8670. else:
  8671. obj_name = _("FlatCAM objects print")
  8672. except AttributeError as err:
  8673. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  8674. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  8675. return
  8676. if not obj_selection:
  8677. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  8678. return
  8679. filter_ = "PDF File (*.PDF);; All Files (*.*)"
  8680. try:
  8681. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8682. caption=_("Save Object as PDF ..."),
  8683. directory=('{l_save}/{obj_name}_{date}').format(l_save=str(self.get_last_save_folder()),
  8684. obj_name=obj_name,
  8685. date=self.date),
  8686. filter=filter_
  8687. )
  8688. except TypeError:
  8689. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Object as PDF ..."), filter=filter_)
  8690. filename = str(filename)
  8691. if filename == '':
  8692. self.inform.emit('[WARNING_NOTCL] %s' % _("Save Object PDF cancelled."))
  8693. return
  8694. if use_thread is True:
  8695. proc = self.proc_container.new(_("Printing PDF ... Please wait."))
  8696. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  8697. else:
  8698. self.save_pdf(filename, obj_selection)
  8699. # self.save_project(filename)
  8700. if self.defaults["global_open_style"] is False:
  8701. self.file_opened.emit("pdf", filename)
  8702. self.file_saved.emit("pdf", filename)
  8703. def save_pdf(self, file_name, obj_selection):
  8704. p_size = self.defaults['global_workspaceT']
  8705. orientation = self.defaults['global_workspace_orientation']
  8706. color = 'black'
  8707. transparency_level = 1.0
  8708. self.pagesize = dict()
  8709. self.pagesize.update(
  8710. {
  8711. 'Bounds': None,
  8712. 'A0': (841*mm, 1189*mm),
  8713. 'A1': (594*mm, 841*mm),
  8714. 'A2': (420*mm, 594*mm),
  8715. 'A3': (297*mm, 420*mm),
  8716. 'A4': (210*mm, 297*mm),
  8717. 'A5': (148*mm, 210*mm),
  8718. 'A6': (105*mm, 148*mm),
  8719. 'A7': (74*mm, 105*mm),
  8720. 'A8': (52*mm, 74*mm),
  8721. 'A9': (37*mm, 52*mm),
  8722. 'A10': (26*mm, 37*mm),
  8723. 'B0': (1000*mm, 1414*mm),
  8724. 'B1': (707*mm, 1000*mm),
  8725. 'B2': (500*mm, 707*mm),
  8726. 'B3': (353*mm, 500*mm),
  8727. 'B4': (250*mm, 353*mm),
  8728. 'B5': (176*mm, 250*mm),
  8729. 'B6': (125*mm, 176*mm),
  8730. 'B7': (88*mm, 125*mm),
  8731. 'B8': (62*mm, 88*mm),
  8732. 'B9': (44*mm, 62*mm),
  8733. 'B10': (31*mm, 44*mm),
  8734. 'C0': (917*mm, 1297*mm),
  8735. 'C1': (648*mm, 917*mm),
  8736. 'C2': (458*mm, 648*mm),
  8737. 'C3': (324*mm, 458*mm),
  8738. 'C4': (229*mm, 324*mm),
  8739. 'C5': (162*mm, 229*mm),
  8740. 'C6': (114*mm, 162*mm),
  8741. 'C7': (81*mm, 114*mm),
  8742. 'C8': (57*mm, 81*mm),
  8743. 'C9': (40*mm, 57*mm),
  8744. 'C10': (28*mm, 40*mm),
  8745. # American paper sizes
  8746. 'LETTER': (8.5*inch, 11*inch),
  8747. 'LEGAL': (8.5*inch, 14*inch),
  8748. 'ELEVENSEVENTEEN': (11*inch, 17*inch),
  8749. # From https://en.wikipedia.org/wiki/Paper_size
  8750. 'JUNIOR_LEGAL': (5*inch, 8*inch),
  8751. 'HALF_LETTER': (5.5*inch, 8*inch),
  8752. 'GOV_LETTER': (8*inch, 10.5*inch),
  8753. 'GOV_LEGAL': (8.5*inch, 13*inch),
  8754. 'LEDGER': (17*inch, 11*inch),
  8755. }
  8756. )
  8757. exported_svg = list()
  8758. for obj in obj_selection:
  8759. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  8760. scale_factor_x=None, scale_factor_y=None,
  8761. skew_factor_x=None, skew_factor_y=None,
  8762. mirror=None)
  8763. if obj.kind.lower() == 'gerber':
  8764. # color = self.defaults["gerber_plot_fill"][:-2]
  8765. color = obj.fill_color[:-2]
  8766. elif obj.kind.lower() == 'excellon':
  8767. color = '#C40000'
  8768. elif obj.kind.lower() == 'geometry':
  8769. color = self.defaults["global_draw_color"]
  8770. # Change the attributes of the exported SVG
  8771. # We don't need stroke-width
  8772. # We set opacity to maximum
  8773. # We set the colour to WHITE
  8774. root = ET.fromstring(svg_obj)
  8775. for child in root:
  8776. child.set('fill', str(color))
  8777. child.set('opacity', str(transparency_level))
  8778. child.set('stroke', str(color))
  8779. exported_svg.append(ET.tostring(root))
  8780. xmin = Inf
  8781. ymin = Inf
  8782. xmax = -Inf
  8783. ymax = -Inf
  8784. for obj in obj_selection:
  8785. try:
  8786. gxmin, gymin, gxmax, gymax = obj.bounds()
  8787. xmin = min([xmin, gxmin])
  8788. ymin = min([ymin, gymin])
  8789. xmax = max([xmax, gxmax])
  8790. ymax = max([ymax, gymax])
  8791. except Exception as e:
  8792. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  8793. # Determine bounding area for svg export
  8794. bounds = [xmin, ymin, xmax, ymax]
  8795. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  8796. # This contain the measure units
  8797. uom = obj_selection[0].units.lower()
  8798. # Define a boundary around SVG of about 1.0mm (~39mils)
  8799. if uom in "mm":
  8800. boundary = 1.0
  8801. else:
  8802. boundary = 0.0393701
  8803. # Convert everything to strings for use in the xml doc
  8804. svgwidth = str(size[0] + (2 * boundary))
  8805. svgheight = str(size[1] + (2 * boundary))
  8806. minx = str(bounds[0] - boundary)
  8807. miny = str(bounds[1] + boundary + size[1])
  8808. # Add a SVG Header and footer to the svg output from shapely
  8809. # The transform flips the Y Axis so that everything renders
  8810. # properly within svg apps such as inkscape
  8811. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8812. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8813. svg_header += 'width="' + svgwidth + uom + '" '
  8814. svg_header += 'height="' + svgheight + uom + '" '
  8815. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8816. svg_header += '>'
  8817. svg_header += '<g transform="scale(1,-1)">'
  8818. svg_footer = '</g> </svg>'
  8819. svg_elem = str(svg_header)
  8820. for svg_item in exported_svg:
  8821. svg_elem += str(svg_item)
  8822. svg_elem += str(svg_footer)
  8823. # Parse the xml through a xml parser just to add line feeds
  8824. # and to make it look more pretty for the output
  8825. doc = parse_xml_string(svg_elem)
  8826. doc_final = doc.toprettyxml()
  8827. try:
  8828. if self.defaults['units'].upper() == 'IN':
  8829. unit = inch
  8830. else:
  8831. unit = mm
  8832. doc_final = StringIO(doc_final)
  8833. drawing = svg2rlg(doc_final)
  8834. if p_size == 'Bounds':
  8835. renderPDF.drawToFile(drawing, file_name)
  8836. else:
  8837. if orientation == 'p':
  8838. page_size = portrait(self.pagesize[p_size])
  8839. else:
  8840. page_size = landscape(self.pagesize[p_size])
  8841. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  8842. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  8843. renderPDF.draw(drawing, my_canvas, 0, 0)
  8844. my_canvas.save()
  8845. except Exception as e:
  8846. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  8847. return 'fail'
  8848. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  8849. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8850. """
  8851. Exports a Geometry Object to an SVG file.
  8852. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8853. :param filename: Path to the SVG file to save to.
  8854. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8855. :return:
  8856. """
  8857. self.report_usage("export_svg()")
  8858. if filename is None:
  8859. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8860. is not None else self.defaults["global_last_folder"]
  8861. self.log.debug("export_svg()")
  8862. try:
  8863. obj = self.collection.get_by_name(str(obj_name))
  8864. except Exception:
  8865. # TODO: The return behavior has not been established... should raise exception?
  8866. return "Could not retrieve object: %s" % obj_name
  8867. with self.proc_container.new(_("Exporting SVG")) as proc:
  8868. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8869. # Determine bounding area for svg export
  8870. bounds = obj.bounds()
  8871. size = obj.size()
  8872. # Convert everything to strings for use in the xml doc
  8873. svgwidth = str(size[0])
  8874. svgheight = str(size[1])
  8875. minx = str(bounds[0])
  8876. miny = str(bounds[1] - size[1])
  8877. uom = obj.units.lower()
  8878. # Add a SVG Header and footer to the svg output from shapely
  8879. # The transform flips the Y Axis so that everything renders
  8880. # properly within svg apps such as inkscape
  8881. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8882. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8883. svg_header += 'width="' + svgwidth + uom + '" '
  8884. svg_header += 'height="' + svgheight + uom + '" '
  8885. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8886. svg_header += '<g transform="scale(1,-1)">'
  8887. svg_footer = '</g> </svg>'
  8888. svg_elem = svg_header + exported_svg + svg_footer
  8889. # Parse the xml through a xml parser just to add line feeds
  8890. # and to make it look more pretty for the output
  8891. svgcode = parse_xml_string(svg_elem)
  8892. svgcode = svgcode.toprettyxml()
  8893. try:
  8894. with open(filename, 'w') as fp:
  8895. fp.write(svgcode)
  8896. except PermissionError:
  8897. self.inform.emit('[WARNING] %s' %
  8898. _("Permission denied, saving not possible.\n"
  8899. "Most likely another app is holding the file open and not accessible."))
  8900. return 'fail'
  8901. if self.defaults["global_open_style"] is False:
  8902. self.file_opened.emit("SVG", filename)
  8903. self.file_saved.emit("SVG", filename)
  8904. self.inform.emit('[success] %s: %s' %
  8905. (_("SVG file exported to"), filename))
  8906. def save_source_file(self, obj_name, filename, use_thread=True):
  8907. """
  8908. Exports a FlatCAM Object to an Gerber/Excellon file.
  8909. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8910. :param filename: Path to the Gerber file to save to.
  8911. :param use_thread: if to be run in a separate thread
  8912. :return:
  8913. """
  8914. self.report_usage("save source file()")
  8915. if filename is None:
  8916. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8917. is not None else self.defaults["global_last_folder"]
  8918. self.log.debug("save source file()")
  8919. obj = self.collection.get_by_name(obj_name)
  8920. file_string = StringIO(obj.source_file)
  8921. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8922. if file_string.getvalue() == '':
  8923. self.inform.emit('[ERROR_NOTCL] %s' %
  8924. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  8925. return 'fail'
  8926. try:
  8927. with open(filename, 'w') as file:
  8928. file.writelines('G04*\n')
  8929. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8930. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8931. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8932. file.writelines('G04 Created on : %s*\n' % time_string)
  8933. for line in file_string:
  8934. file.writelines(line)
  8935. except PermissionError:
  8936. self.inform.emit('[WARNING] %s' %
  8937. _("Permission denied, saving not possible.\n"
  8938. "Most likely another app is holding the file open and not accessible."))
  8939. return 'fail'
  8940. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8941. """
  8942. Exports a Excellon Object to an Excellon file.
  8943. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8944. :param filename: Path to the Excellon file to save to.
  8945. :param local_use:
  8946. :param use_thread: if to be run in a separate thread
  8947. :return:
  8948. """
  8949. self.report_usage("export_excellon()")
  8950. if filename is None:
  8951. if self.defaults["global_last_save_folder"]:
  8952. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  8953. else:
  8954. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  8955. self.log.debug("export_excellon()")
  8956. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8957. self.defaults["excellon_exp_decimals"]
  8958. )
  8959. if local_use is None:
  8960. try:
  8961. obj = self.collection.get_by_name(str(obj_name))
  8962. except Exception:
  8963. # TODO: The return behavior has not been established... should raise exception?
  8964. return "Could not retrieve object: %s" % obj_name
  8965. else:
  8966. obj = local_use
  8967. if not isinstance(obj, FlatCAMExcellon):
  8968. self.inform.emit('[ERROR_NOTCL] %s' %
  8969. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8970. return
  8971. # updated units
  8972. eunits = self.defaults["excellon_exp_units"]
  8973. ewhole = self.defaults["excellon_exp_integer"]
  8974. efract = self.defaults["excellon_exp_decimals"]
  8975. ezeros = self.defaults["excellon_exp_zeros"]
  8976. eformat = self.defaults["excellon_exp_format"]
  8977. slot_type = self.defaults["excellon_exp_slot_type"]
  8978. fc_units = self.defaults['units'].upper()
  8979. if fc_units == 'MM':
  8980. factor = 1 if eunits == 'METRIC' else 0.03937
  8981. else:
  8982. factor = 25.4 if eunits == 'METRIC' else 1
  8983. def make_excellon():
  8984. try:
  8985. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8986. header = 'M48\n'
  8987. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8988. (str(self.version), str(self.version_date))
  8989. header += ';Filename: %s' % str(obj_name) + '\n'
  8990. header += ';Created on : %s' % time_str + '\n'
  8991. if eformat == 'dec':
  8992. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8993. header += eunits + '\n'
  8994. for tool in obj.tools:
  8995. if eunits == 'METRIC':
  8996. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8997. tool=str(tool),
  8998. dec=2)
  8999. else:
  9000. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9001. tool=str(tool),
  9002. dec=4)
  9003. else:
  9004. if ezeros == 'LZ':
  9005. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  9006. form='ndec', e_zeros='LZ', factor=factor,
  9007. slot_type=slot_type)
  9008. header += '%s,%s\n' % (eunits, 'LZ')
  9009. header += format_exc
  9010. for tool in obj.tools:
  9011. if eunits == 'METRIC':
  9012. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9013. tool=str(tool),
  9014. dec=2)
  9015. else:
  9016. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9017. tool=str(tool),
  9018. dec=4)
  9019. else:
  9020. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  9021. form='ndec', e_zeros='TZ', factor=factor,
  9022. slot_type=slot_type)
  9023. header += '%s,%s\n' % (eunits, 'TZ')
  9024. header += format_exc
  9025. for tool in obj.tools:
  9026. if eunits == 'METRIC':
  9027. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9028. tool=str(tool),
  9029. dec=2)
  9030. else:
  9031. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9032. tool=str(tool),
  9033. dec=4)
  9034. header += '%\n'
  9035. footer = 'M30\n'
  9036. exported_excellon = header
  9037. exported_excellon += excellon_code
  9038. exported_excellon += footer
  9039. if local_use is None:
  9040. try:
  9041. with open(filename, 'w') as fp:
  9042. fp.write(exported_excellon)
  9043. except PermissionError:
  9044. self.inform.emit('[WARNING] %s' %
  9045. _("Permission denied, saving not possible.\n"
  9046. "Most likely another app is holding the file open and not accessible."))
  9047. return 'fail'
  9048. if self.defaults["global_open_style"] is False:
  9049. self.file_opened.emit("Excellon", filename)
  9050. self.file_saved.emit("Excellon", filename)
  9051. self.inform.emit('[success] %s: %s' %
  9052. (_("Excellon file exported to"), filename))
  9053. else:
  9054. return exported_excellon
  9055. except Exception as e:
  9056. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  9057. return 'fail'
  9058. if use_thread is True:
  9059. with self.proc_container.new(_("Exporting Excellon")) as proc:
  9060. def job_thread_exc(app_obj):
  9061. ret = make_excellon()
  9062. if ret == 'fail':
  9063. self.inform.emit('[ERROR_NOTCL] %s' %
  9064. _('Could not export Excellon file.'))
  9065. return
  9066. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  9067. else:
  9068. ret = make_excellon()
  9069. if ret == 'fail':
  9070. self.inform.emit('[ERROR_NOTCL] %s' %
  9071. _('Could not export Excellon file.'))
  9072. return 'fail'
  9073. if local_use is not None:
  9074. return ret
  9075. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  9076. """
  9077. Exports a Gerber Object to an Gerber file.
  9078. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  9079. :param filename: Path to the Gerber file to save to.
  9080. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  9081. When not None, the value will be the actual Gerber object for which to create the Gerber code
  9082. :param use_thread: if to be run in a separate thread
  9083. :return:
  9084. """
  9085. self.report_usage("export_gerber()")
  9086. if filename is None:
  9087. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  9088. is not None else self.defaults["global_last_folder"]
  9089. self.log.debug("export_gerber()")
  9090. if local_use is None:
  9091. try:
  9092. obj = self.collection.get_by_name(str(obj_name))
  9093. except Exception:
  9094. # TODO: The return behavior has not been established... should raise exception?
  9095. return "Could not retrieve object: %s" % obj_name
  9096. else:
  9097. obj = local_use
  9098. # updated units
  9099. gunits = self.defaults["gerber_exp_units"]
  9100. gwhole = self.defaults["gerber_exp_integer"]
  9101. gfract = self.defaults["gerber_exp_decimals"]
  9102. gzeros = self.defaults["gerber_exp_zeros"]
  9103. fc_units = self.defaults['units'].upper()
  9104. if fc_units == 'MM':
  9105. factor = 1 if gunits == 'MM' else 0.03937
  9106. else:
  9107. factor = 25.4 if gunits == 'MM' else 1
  9108. def make_gerber():
  9109. try:
  9110. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  9111. header = 'G04*\n'
  9112. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  9113. (str(self.version), str(self.version_date))
  9114. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  9115. header += 'G04 Created on : %s*' % time_str + '\n'
  9116. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  9117. header += "%MO{units}*%\n".format(units=gunits)
  9118. for apid in obj.apertures:
  9119. if obj.apertures[apid]['type'] == 'C':
  9120. header += "%ADD{apid}{type},{size}*%\n".format(
  9121. apid=str(apid),
  9122. type='C',
  9123. size=(factor * obj.apertures[apid]['size'])
  9124. )
  9125. elif obj.apertures[apid]['type'] == 'R':
  9126. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  9127. apid=str(apid),
  9128. type='R',
  9129. width=(factor * obj.apertures[apid]['width']),
  9130. height=(factor * obj.apertures[apid]['height'])
  9131. )
  9132. elif obj.apertures[apid]['type'] == 'O':
  9133. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  9134. apid=str(apid),
  9135. type='O',
  9136. width=(factor * obj.apertures[apid]['width']),
  9137. height=(factor * obj.apertures[apid]['height'])
  9138. )
  9139. header += '\n'
  9140. # obsolete units but some software may need it
  9141. if gunits == 'IN':
  9142. header += 'G70*\n'
  9143. else:
  9144. header += 'G71*\n'
  9145. # Absolute Mode
  9146. header += 'G90*\n'
  9147. header += 'G01*\n'
  9148. # positive polarity
  9149. header += '%LPD*%\n'
  9150. footer = 'M02*\n'
  9151. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  9152. exported_gerber = header
  9153. exported_gerber += gerber_code
  9154. exported_gerber += footer
  9155. if local_use is None:
  9156. try:
  9157. with open(filename, 'w') as fp:
  9158. fp.write(exported_gerber)
  9159. except PermissionError:
  9160. self.inform.emit('[WARNING] %s' %
  9161. _("Permission denied, saving not possible.\n"
  9162. "Most likely another app is holding the file open and not accessible."))
  9163. return 'fail'
  9164. if self.defaults["global_open_style"] is False:
  9165. self.file_opened.emit("Gerber", filename)
  9166. self.file_saved.emit("Gerber", filename)
  9167. self.inform.emit('[success] %s: %s' %
  9168. (_("Gerber file exported to"), filename))
  9169. else:
  9170. return exported_gerber
  9171. except Exception as e:
  9172. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  9173. return 'fail'
  9174. if use_thread is True:
  9175. with self.proc_container.new(_("Exporting Gerber")) as proc:
  9176. def job_thread_grb(app_obj):
  9177. ret = make_gerber()
  9178. if ret == 'fail':
  9179. self.inform.emit('[ERROR_NOTCL] %s' %
  9180. _('Could not export Gerber file.'))
  9181. return
  9182. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  9183. else:
  9184. ret = make_gerber()
  9185. if ret == 'fail':
  9186. self.inform.emit('[ERROR_NOTCL] %s' %
  9187. _('Could not export Gerber file.'))
  9188. return 'fail'
  9189. if local_use is not None:
  9190. return ret
  9191. def export_dxf(self, obj_name, filename, use_thread=True):
  9192. """
  9193. Exports a Geometry Object to an DXF file.
  9194. :param obj_name: the name of the FlatCAM object to be saved as DXF
  9195. :param filename: Path to the DXF file to save to.
  9196. :param use_thread: if to be run in a separate thread
  9197. :return:
  9198. """
  9199. self.report_usage("export_dxf()")
  9200. if filename is None:
  9201. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  9202. is not None else self.defaults["global_last_folder"]
  9203. self.log.debug("export_dxf()")
  9204. try:
  9205. obj = self.collection.get_by_name(str(obj_name))
  9206. except Exception:
  9207. # TODO: The return behavior has not been established... should raise exception?
  9208. return "Could not retrieve object: %s" % obj_name
  9209. def make_dxf():
  9210. try:
  9211. dxf_code = obj.export_dxf()
  9212. dxf_code.saveas(filename)
  9213. if self.defaults["global_open_style"] is False:
  9214. self.file_opened.emit("DXF", filename)
  9215. self.file_saved.emit("DXF", filename)
  9216. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  9217. except Exception:
  9218. return 'fail'
  9219. if use_thread is True:
  9220. with self.proc_container.new(_("Exporting DXF")) as proc:
  9221. def job_thread_exc(app_obj):
  9222. ret_dxf_val = make_dxf()
  9223. if ret_dxf_val == 'fail':
  9224. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  9225. return
  9226. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  9227. else:
  9228. ret = make_dxf()
  9229. if ret == 'fail':
  9230. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  9231. return
  9232. def import_svg(self, filename, geo_type='geometry', outname=None):
  9233. """
  9234. Adds a new Geometry Object to the projects and populates
  9235. it with shapes extracted from the SVG file.
  9236. :param filename: Path to the SVG file.
  9237. :param geo_type: Type of FlatCAM object that will be created from SVG
  9238. :param outname:
  9239. :return:
  9240. """
  9241. self.report_usage("import_svg()")
  9242. log.debug("App.import_svg()")
  9243. obj_type = ""
  9244. if geo_type is None or geo_type == "geometry":
  9245. obj_type = "geometry"
  9246. elif geo_type == "gerber":
  9247. obj_type = "gerber"
  9248. else:
  9249. self.inform.emit('[ERROR_NOTCL] %s' %
  9250. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  9251. return
  9252. units = self.defaults['units'].upper()
  9253. def obj_init(geo_obj, app_obj):
  9254. geo_obj.import_svg(filename, obj_type, units=units)
  9255. geo_obj.multigeo = False
  9256. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  9257. with self.proc_container.new(_("Importing SVG")) as proc:
  9258. # Object name
  9259. name = outname or filename.split('/')[-1].split('\\')[-1]
  9260. self.new_object(obj_type, name, obj_init, autoselected=False)
  9261. # Register recent file
  9262. self.file_opened.emit("svg", filename)
  9263. # GUI feedback
  9264. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9265. def import_dxf(self, filename, geo_type='geometry', outname=None):
  9266. """
  9267. Adds a new Geometry Object to the projects and populates
  9268. it with shapes extracted from the DXF file.
  9269. :param filename: Path to the DXF file.
  9270. :param geo_type: Type of FlatCAM object that will be created from DXF
  9271. :param outname:
  9272. :type putname: str
  9273. :return:
  9274. """
  9275. self.report_usage("import_dxf()")
  9276. obj_type = ""
  9277. if geo_type is None or geo_type == "geometry":
  9278. obj_type = "geometry"
  9279. elif geo_type == "gerber":
  9280. obj_type = geo_type
  9281. else:
  9282. self.inform.emit('[ERROR_NOTCL] %s' %
  9283. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  9284. return
  9285. units = self.defaults['units'].upper()
  9286. def obj_init(geo_obj, app_obj):
  9287. geo_obj.import_dxf(filename, obj_type, units=units)
  9288. geo_obj.multigeo = False
  9289. with self.proc_container.new(_("Importing DXF")) as proc:
  9290. # Object name
  9291. name = outname or filename.split('/')[-1].split('\\')[-1]
  9292. self.new_object(obj_type, name, obj_init, autoselected=False)
  9293. # Register recent file
  9294. self.file_opened.emit("dxf", filename)
  9295. # GUI feedback
  9296. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9297. def open_gerber(self, filename, outname=None):
  9298. """
  9299. Opens a Gerber file, parses it and creates a new object for
  9300. it in the program. Thread-safe.
  9301. :param outname: Name of the resulting object. None causes the
  9302. name to be that of the file.
  9303. :param filename: Gerber file filename
  9304. :type filename: str
  9305. :return: None
  9306. """
  9307. # How the object should be initialized
  9308. def obj_init(gerber_obj, app_obj):
  9309. assert isinstance(gerber_obj, FlatCAMGerber), \
  9310. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  9311. # Opening the file happens here
  9312. try:
  9313. gerber_obj.parse_file(filename)
  9314. except IOError:
  9315. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  9316. return "fail"
  9317. except ParseError as err:
  9318. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  9319. app_obj.log.error(str(err))
  9320. return "fail"
  9321. except Exception as e:
  9322. log.debug("App.open_gerber() --> %s" % str(e))
  9323. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  9324. msg += traceback.format_exc()
  9325. app_obj.inform.emit(msg)
  9326. return "fail"
  9327. if gerber_obj.is_empty():
  9328. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  9329. _("Object is not Gerber file or empty. Aborting object creation."))
  9330. return "fail"
  9331. App.log.debug("open_gerber()")
  9332. with self.proc_container.new(_("Opening Gerber")) as proc:
  9333. # Object name
  9334. name = outname or filename.split('/')[-1].split('\\')[-1]
  9335. # # ## Object creation # ##
  9336. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  9337. if ret == 'fail':
  9338. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  9339. return 'fail'
  9340. # Register recent file
  9341. self.file_opened.emit("gerber", filename)
  9342. # GUI feedback
  9343. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9344. def open_excellon(self, filename, outname=None, plot=True):
  9345. """
  9346. Opens an Excellon file, parses it and creates a new object for
  9347. it in the program. Thread-safe.
  9348. :param outname: Name of the resulting object. None causes the
  9349. name to be that of the file.
  9350. :param filename: Excellon file filename
  9351. :type filename: str
  9352. :return: None
  9353. """
  9354. App.log.debug("open_excellon()")
  9355. # How the object should be initialized
  9356. def obj_init(excellon_obj, app_obj):
  9357. try:
  9358. ret = excellon_obj.parse_file(filename=filename)
  9359. if ret == "fail":
  9360. log.debug("Excellon parsing failed.")
  9361. self.inform.emit('[ERROR_NOTCL] %s' %
  9362. _("This is not Excellon file."))
  9363. return "fail"
  9364. except IOError:
  9365. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9366. (_("Cannot open file"), filename))
  9367. log.debug("Could not open Excellon object.")
  9368. return "fail"
  9369. except Exception:
  9370. msg = '[ERROR_NOTCL] %s' % \
  9371. _("An internal error has occurred. See shell.\n")
  9372. msg += traceback.format_exc()
  9373. app_obj.inform.emit(msg)
  9374. return "fail"
  9375. ret = excellon_obj.create_geometry()
  9376. if ret == 'fail':
  9377. log.debug("Could not create geometry for Excellon object.")
  9378. return "fail"
  9379. for tool in excellon_obj.tools:
  9380. if excellon_obj.tools[tool]['solid_geometry']:
  9381. return
  9382. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9383. (_("No geometry found in file"), filename))
  9384. return "fail"
  9385. with self.proc_container.new(_("Opening Excellon.")):
  9386. # Object name
  9387. name = outname or filename.split('/')[-1].split('\\')[-1]
  9388. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  9389. if ret_val == 'fail':
  9390. self.inform.emit('[ERROR_NOTCL] %s' %
  9391. _('Open Excellon file failed. Probable not an Excellon file.'))
  9392. return
  9393. # Register recent file
  9394. self.file_opened.emit("excellon", filename)
  9395. # GUI feedback
  9396. self.inform.emit('[success] %s: %s' %
  9397. (_("Opened"), filename))
  9398. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  9399. """
  9400. Opens a G-gcode file, parses it and creates a new object for
  9401. it in the program. Thread-safe.
  9402. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9403. :param filename: G-code file filename
  9404. :type filename: str
  9405. :return: None
  9406. """
  9407. App.log.debug("open_gcode()")
  9408. # How the object should be initialized
  9409. def obj_init(job_obj, app_obj_):
  9410. """
  9411. :param job_obj: the resulting object
  9412. :type app_obj_: App
  9413. """
  9414. assert isinstance(app_obj_, App), \
  9415. "Initializer expected App, got %s" % type(app_obj_)
  9416. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  9417. try:
  9418. f = open(filename)
  9419. gcode = f.read()
  9420. f.close()
  9421. except IOError:
  9422. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  9423. (_("Failed to open"), filename))
  9424. return "fail"
  9425. job_obj.gcode = gcode
  9426. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9427. if gcode_ret == "fail":
  9428. self.inform.emit('[ERROR_NOTCL] %s' %
  9429. _("This is not GCODE"))
  9430. return "fail"
  9431. job_obj.create_geometry()
  9432. with self.proc_container.new(_("Opening G-Code.")):
  9433. # Object name
  9434. name = outname or filename.split('/')[-1].split('\\')[-1]
  9435. # New object creation and file processing
  9436. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9437. if obj_ret == 'fail':
  9438. self.inform.emit('[ERROR_NOTCL] %s' %
  9439. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9440. "Try to load it from File menu.\n "
  9441. "Attempting to create a FlatCAM CNCJob Object from "
  9442. "G-Code file failed during processing"))
  9443. return "fail"
  9444. # Register recent file
  9445. self.file_opened.emit("cncjob", filename)
  9446. # GUI feedback
  9447. self.inform.emit('[success] %s: %s' %
  9448. (_("Opened"), filename))
  9449. def open_hpgl2(self, filename, outname=None):
  9450. """
  9451. Opens a HPGL2 file, parses it and creates a new object for
  9452. it in the program. Thread-safe.
  9453. :param outname: Name of the resulting object. None causes the
  9454. name to be that of the file.
  9455. :param filename: HPGL2 file filename
  9456. :type filename: str
  9457. :return: None
  9458. """
  9459. filename = filename
  9460. # How the object should be initialized
  9461. def obj_init(geo_obj, app_obj):
  9462. assert isinstance(geo_obj, FlatCAMGeometry), \
  9463. "Expected to initialize a FlatCAMGeometry but got %s" % type(geo_obj)
  9464. # Opening the file happens here
  9465. obj = HPGL2(self)
  9466. try:
  9467. HPGL2.parse_file(obj, filename)
  9468. except IOError:
  9469. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  9470. return "fail"
  9471. except ParseError as err:
  9472. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  9473. app_obj.log.error(str(err))
  9474. return "fail"
  9475. except Exception as e:
  9476. log.debug("App.open_hpgl2() --> %s" % str(e))
  9477. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  9478. msg += traceback.format_exc()
  9479. app_obj.inform.emit(msg)
  9480. return "fail"
  9481. geo_obj.multigeo = True
  9482. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  9483. geo_obj.tools = deepcopy(obj.tools)
  9484. geo_obj.source_file = deepcopy(obj.source_file)
  9485. del obj
  9486. if not geo_obj.solid_geometry:
  9487. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  9488. _("Object is not HPGL2 file or empty. Aborting object creation."))
  9489. return "fail"
  9490. App.log.debug("open_hpgl2()")
  9491. with self.proc_container.new(_("Opening HPGL2")) as proc:
  9492. # Object name
  9493. name = outname or filename.split('/')[-1].split('\\')[-1]
  9494. # # ## Object creation # ##
  9495. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  9496. if ret == 'fail':
  9497. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  9498. return 'fail'
  9499. # Register recent file
  9500. self.file_opened.emit("geometry", filename)
  9501. # GUI feedback
  9502. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9503. def open_script(self, filename, outname=None, silent=False):
  9504. """
  9505. Opens a Script file, parses it and creates a new object for
  9506. it in the program. Thread-safe.
  9507. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9508. :param filename: Script file filename
  9509. :type filename: str
  9510. :return: None
  9511. """
  9512. App.log.debug("open_script()")
  9513. with self.proc_container.new(_("Opening TCL Script...")):
  9514. try:
  9515. with open(filename, "r") as opened_script:
  9516. script_content = opened_script.readlines()
  9517. script_content = ''.join(script_content)
  9518. if silent is False:
  9519. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9520. except Exception as e:
  9521. log.debug("App.open_script() -> %s" % str(e))
  9522. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9523. return
  9524. # Object name
  9525. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9526. # New object creation and file processing
  9527. self.on_filenewscript(name=script_name, text=script_content)
  9528. # Register recent file
  9529. self.file_opened.emit("script", filename)
  9530. # GUI feedback
  9531. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9532. def open_config_file(self, filename, run_from_arg=None):
  9533. """
  9534. Loads a config file from the specified file.
  9535. :param filename: Name of the file from which to load.
  9536. :type filename: str
  9537. :return: None
  9538. """
  9539. App.log.debug("Opening config file: " + filename)
  9540. if run_from_arg:
  9541. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9542. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9543. _("Opening FlatCAM Config file.")),
  9544. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9545. color=QtGui.QColor("gray"))
  9546. # # add the tab if it was closed
  9547. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9548. # # first clear previous text in text editor (if any)
  9549. # self.ui.text_editor_tab.code_editor.clear()
  9550. #
  9551. # # Switch plot_area to CNCJob tab
  9552. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9553. # close the Code editor if already open
  9554. if self.toggle_codeeditor:
  9555. self.on_toggle_code_editor()
  9556. self.on_toggle_code_editor()
  9557. try:
  9558. if filename:
  9559. f = QtCore.QFile(filename)
  9560. if f.open(QtCore.QIODevice.ReadOnly):
  9561. stream = QtCore.QTextStream(f)
  9562. code_edited = stream.readAll()
  9563. self.text_editor_tab.code_editor.setPlainText(code_edited)
  9564. f.close()
  9565. except IOError:
  9566. App.log.error("Failed to open config file: %s" % filename)
  9567. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9568. (_("Failed to open config file"), filename))
  9569. return
  9570. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9571. """
  9572. Loads a project from the specified file.
  9573. 1) Loads and parses file
  9574. 2) Registers the file as recently opened.
  9575. 3) Calls on_file_new()
  9576. 4) Updates options
  9577. 5) Calls new_object() with the object's from_dict() as init method.
  9578. 6) Calls plot_all() if plot=True
  9579. :param filename: Name of the file from which to load.
  9580. :type filename: str
  9581. :param run_from_arg: True if run for arguments
  9582. :param plot: If True plot all objects in the project
  9583. :param cli: run from command line
  9584. :return: None
  9585. """
  9586. App.log.debug("Opening project: " + filename)
  9587. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9588. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9589. if cli is None:
  9590. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9591. if run_from_arg:
  9592. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9593. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9594. _("Opening FlatCAM Project file.")),
  9595. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9596. color=QtGui.QColor("gray"))
  9597. # Open and parse an uncompressed Project file
  9598. try:
  9599. f = open(filename, 'r')
  9600. except IOError:
  9601. App.log.error("Failed to open project file: %s" % filename)
  9602. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9603. (_("Failed to open project file"), filename))
  9604. return
  9605. try:
  9606. d = json.load(f, object_hook=dict2obj)
  9607. except Exception as e:
  9608. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9609. (filename, str(e)))
  9610. f.close()
  9611. # Open and parse a compressed Project file
  9612. try:
  9613. with lzma.open(filename) as f:
  9614. file_content = f.read().decode('utf-8')
  9615. d = json.loads(file_content, object_hook=dict2obj)
  9616. except Exception as e:
  9617. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9618. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9619. (_("Failed to open project file"), filename))
  9620. return
  9621. # Clear the current project
  9622. # # NOT THREAD SAFE # ##
  9623. if run_from_arg is True:
  9624. pass
  9625. elif cli is True:
  9626. self.delete_selection_shape()
  9627. else:
  9628. self.on_file_new()
  9629. # Project options
  9630. self.options.update(d['options'])
  9631. self.project_filename = filename
  9632. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9633. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9634. if cli is None:
  9635. self.set_screen_units(self.options["units"])
  9636. # Re create objects
  9637. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9638. for obj in d['objs']:
  9639. try:
  9640. def obj_init(obj_inst, app_inst):
  9641. obj_inst.from_dict(obj)
  9642. App.log.debug("Recreating from opened project an %s object: %s" %
  9643. (obj['kind'].capitalize(), obj['options']['name']))
  9644. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9645. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9646. if cli is None:
  9647. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9648. obj['kind'].upper(),
  9649. obj['options']['name']
  9650. )
  9651. )
  9652. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9653. except Exception as e:
  9654. print('App.open_project() --> ' + str(e))
  9655. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  9656. self.should_we_save = False
  9657. self.file_opened.emit("project", filename)
  9658. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9659. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9660. if cli is None:
  9661. self.set_ui_title(name=self.project_filename)
  9662. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9663. def propagate_defaults(self, silent=False):
  9664. """
  9665. This method is used to set default values in classes. It's
  9666. an alternative to project options but allows the use
  9667. of values invisible to the user.
  9668. :return: None
  9669. """
  9670. if silent is False:
  9671. self.log.debug("propagate_defaults()")
  9672. # Which objects to update the given parameters.
  9673. routes = {
  9674. "global_zdownrate": CNCjob,
  9675. "excellon_zeros": Excellon,
  9676. "excellon_format_upper_in": Excellon,
  9677. "excellon_format_lower_in": Excellon,
  9678. "excellon_format_upper_mm": Excellon,
  9679. "excellon_format_lower_mm": Excellon,
  9680. "excellon_units": Excellon,
  9681. "gerber_use_buffer_for_union": Gerber,
  9682. "geometry_multidepth": Geometry
  9683. }
  9684. for param in routes:
  9685. if param in routes[param].defaults:
  9686. try:
  9687. routes[param].defaults[param] = self.defaults[param]
  9688. if silent is False:
  9689. self.log.debug(" " + param + " OK")
  9690. except KeyError:
  9691. if silent is False:
  9692. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9693. else:
  9694. # Try extracting the name:
  9695. # classname_param here is param in the object
  9696. if param.find(routes[param].__name__.lower() + "_") == 0:
  9697. p = param[len(routes[param].__name__) + 1:]
  9698. if p in routes[param].defaults:
  9699. routes[param].defaults[p] = self.defaults[param]
  9700. if silent is False:
  9701. self.log.debug(" " + param + " OK!")
  9702. def plot_all(self, zoom=True):
  9703. """
  9704. Re-generates all plots from all objects.
  9705. :return: None
  9706. """
  9707. self.log.debug("Plot_all()")
  9708. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9709. for obj in self.collection.get_list():
  9710. def worker_task(obj):
  9711. with self.proc_container.new("Plotting"):
  9712. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9713. if zoom:
  9714. self.object_plotted.emit(obj)
  9715. # Send to worker
  9716. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9717. def register_folder(self, filename):
  9718. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9719. def register_save_folder(self, filename):
  9720. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9721. def set_progress_bar(self, percentage, text=""):
  9722. self.ui.progress_bar.setValue(int(percentage))
  9723. def setup_shell(self):
  9724. """
  9725. Creates shell functions. Runs once at startup.
  9726. :return: None
  9727. """
  9728. self.log.debug("setup_shell()")
  9729. def shelp(p=None):
  9730. if not p:
  9731. return _("Available commands:\n") + \
  9732. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9733. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9734. if p not in commands:
  9735. return "Unknown command: %s" % p
  9736. return commands[p]["help"]
  9737. # --- Migrated to new architecture ---
  9738. # def options(name):
  9739. # ops = self.collection.get_by_name(str(name)).options
  9740. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9741. def h(*args):
  9742. """
  9743. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9744. and standalone parameters into list.
  9745. """
  9746. kwa = {}
  9747. a = []
  9748. n = len(args)
  9749. name = None
  9750. for i in range(n):
  9751. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9752. if match:
  9753. assert name is None
  9754. name = match.group(1)
  9755. continue
  9756. if name is None:
  9757. a.append(args[i])
  9758. else:
  9759. kwa[name] = args[i]
  9760. name = None
  9761. return a, kwa
  9762. @contextmanager
  9763. def wait_signal(signal, timeout=10000):
  9764. """
  9765. Block loop until signal emitted, timeout (ms) elapses
  9766. or unhandled exception happens in a thread.
  9767. :param timeout: time after which the loop is exited
  9768. :param signal: Signal to wait for.
  9769. """
  9770. loop = QtCore.QEventLoop()
  9771. # Normal termination
  9772. signal.connect(loop.quit)
  9773. # Termination by exception in thread
  9774. self.thread_exception.connect(loop.quit)
  9775. status = {'timed_out': False}
  9776. def report_quit():
  9777. status['timed_out'] = True
  9778. loop.quit()
  9779. yield
  9780. # Temporarily change how exceptions are managed.
  9781. oeh = sys.excepthook
  9782. ex = []
  9783. def except_hook(type_, value, traceback_):
  9784. ex.append(value)
  9785. oeh(type_, value, traceback_)
  9786. sys.excepthook = except_hook
  9787. # Terminate on timeout
  9788. if timeout is not None:
  9789. QtCore.QTimer.singleShot(timeout, report_quit)
  9790. # # ## Block ## ##
  9791. loop.exec_()
  9792. # Restore exception management
  9793. sys.excepthook = oeh
  9794. if ex:
  9795. self.raiseTclError(str(ex[0]))
  9796. if status['timed_out']:
  9797. raise Exception('Timed out!')
  9798. def make_docs():
  9799. output = ''
  9800. import collections
  9801. od = collections.OrderedDict(sorted(commands.items()))
  9802. for cmd_, val in od.items():
  9803. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9804. t = val['help']
  9805. usage_i = t.find('>')
  9806. if usage_i < 0:
  9807. expl = t
  9808. output += expl + '\n\n'
  9809. continue
  9810. expl = t[:usage_i - 1]
  9811. output += expl + '\n\n'
  9812. end_usage_i = t[usage_i:].find('\n')
  9813. if end_usage_i < 0:
  9814. end_usage_i = len(t[usage_i:])
  9815. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9816. else:
  9817. extras = t[usage_i+end_usage_i+1:]
  9818. parts = [s.strip() for s in extras.split('\n')]
  9819. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9820. for p in parts:
  9821. output += ' ' + p + '\n\n'
  9822. return output
  9823. '''
  9824. Howto implement TCL shell commands:
  9825. All parameters passed to command should be possible to set as None and test it afterwards.
  9826. This is because we need to see error caused in tcl,
  9827. if None value as default parameter is not allowed TCL will return empty error.
  9828. Use:
  9829. def mycommand(name=None,...):
  9830. Test it like this:
  9831. if name is None:
  9832. self.raise_tcl_error('Argument name is missing.')
  9833. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9834. otherwise we will miss it and processing will silently continue.
  9835. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9836. which is catched in exec_command and displayed in TCL shell console with red background.
  9837. Error in console is displayed with TCL trace.
  9838. This behavior works only within main thread,
  9839. errors with promissed tasks can be catched and detected only with log.
  9840. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9841. TCL shell.
  9842. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9843. '''
  9844. commands = {
  9845. 'help': {
  9846. 'fcn': shelp,
  9847. 'help': _("Shows list of commands.")
  9848. },
  9849. }
  9850. # Import/overwrite tcl commands as objects of TclCommand descendants
  9851. # This modifies the variable 'commands'.
  9852. tclCommands.register_all_commands(self, commands)
  9853. # Add commands to the tcl interpreter
  9854. for cmd in commands:
  9855. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9856. # Make the tcl puts function return instead of print to stdout
  9857. self.tcl.eval('''
  9858. rename puts original_puts
  9859. proc puts {args} {
  9860. if {[llength $args] == 1} {
  9861. return "[lindex $args 0]"
  9862. } else {
  9863. eval original_puts $args
  9864. }
  9865. }
  9866. ''')
  9867. def setup_recent_items(self):
  9868. # TODO: Move this to constructor
  9869. icons = {
  9870. "gerber": self.resource_location + "/flatcam_icon16.png",
  9871. "excellon": self.resource_location + "/drill16.png",
  9872. 'geometry': self.resource_location + "/geometry16.png",
  9873. "cncjob": self.resource_location + "/cnc16.png",
  9874. "script": self.resource_location + "/script_new24.png",
  9875. "document": self.resource_location + "/notes16_1.png",
  9876. "project": self.resource_location + "/project16.png",
  9877. "svg": self.resource_location + "/geometry16.png",
  9878. "dxf": self.resource_location + "/dxf16.png",
  9879. "pdf": self.resource_location + "/pdf32.png",
  9880. "image": self.resource_location + "/image16.png"
  9881. }
  9882. try:
  9883. image_opener = self.image_tool.import_image
  9884. except AttributeError:
  9885. image_opener = None
  9886. openers = {
  9887. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9888. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9889. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9890. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9891. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9892. "document": None,
  9893. 'project': self.open_project,
  9894. 'svg': self.import_svg,
  9895. 'dxf': self.import_dxf,
  9896. 'image': image_opener,
  9897. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9898. }
  9899. # Open recent file for files
  9900. try:
  9901. f = open(self.data_path + '/recent.json')
  9902. except IOError:
  9903. App.log.error("Failed to load recent item list.")
  9904. self.inform.emit('[ERROR_NOTCL] %s' %
  9905. _("Failed to load recent item list."))
  9906. return
  9907. try:
  9908. self.recent = json.load(f)
  9909. except json.scanner.JSONDecodeError:
  9910. App.log.error("Failed to parse recent item list.")
  9911. self.inform.emit('[ERROR_NOTCL] %s' %
  9912. _("Failed to parse recent item list."))
  9913. f.close()
  9914. return
  9915. f.close()
  9916. # Open recent file for projects
  9917. try:
  9918. fp = open(self.data_path + '/recent_projects.json')
  9919. except IOError:
  9920. App.log.error("Failed to load recent project item list.")
  9921. self.inform.emit('[ERROR_NOTCL] %s' %
  9922. _("Failed to load recent projects item list."))
  9923. return
  9924. try:
  9925. self.recent_projects = json.load(fp)
  9926. except json.scanner.JSONDecodeError:
  9927. App.log.error("Failed to parse recent project item list.")
  9928. self.inform.emit('[ERROR_NOTCL] %s' %
  9929. _("Failed to parse recent project item list."))
  9930. fp.close()
  9931. return
  9932. fp.close()
  9933. # Closure needed to create callbacks in a loop.
  9934. # Otherwise late binding occurs.
  9935. def make_callback(func, fname):
  9936. def opener():
  9937. func(fname)
  9938. return opener
  9939. def reset_recent_files():
  9940. # Reset menu
  9941. self.ui.recent.clear()
  9942. self.recent = []
  9943. try:
  9944. ff = open(self.data_path + '/recent.json', 'w')
  9945. except IOError:
  9946. App.log.error("Failed to open recent items file for writing.")
  9947. return
  9948. json.dump(self.recent, ff)
  9949. def reset_recent_projects():
  9950. # Reset menu
  9951. self.ui.recent_projects.clear()
  9952. self.recent_projects = []
  9953. try:
  9954. fp = open(self.data_path + '/recent_projects.json', 'w')
  9955. except IOError:
  9956. App.log.error("Failed to open recent projects items file for writing.")
  9957. return
  9958. json.dump(self.recent, fp)
  9959. # Reset menu
  9960. self.ui.recent.clear()
  9961. self.ui.recent_projects.clear()
  9962. # Create menu items for projects
  9963. for recent in self.recent_projects:
  9964. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9965. if recent['kind'] == 'project':
  9966. try:
  9967. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9968. # Attach callback
  9969. o = make_callback(openers[recent["kind"]], recent['filename'])
  9970. action.triggered.connect(o)
  9971. self.ui.recent_projects.addAction(action)
  9972. except KeyError:
  9973. App.log.error("Unsupported file type: %s" % recent["kind"])
  9974. # Last action in Recent Files menu is one that Clear the content
  9975. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  9976. (_("Clear Recent projects")), self)
  9977. clear_action_proj.triggered.connect(reset_recent_projects)
  9978. self.ui.recent_projects.addSeparator()
  9979. self.ui.recent_projects.addAction(clear_action_proj)
  9980. # Create menu items for files
  9981. for recent in self.recent:
  9982. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9983. if recent['kind'] != 'project':
  9984. try:
  9985. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9986. # Attach callback
  9987. o = make_callback(openers[recent["kind"]], recent['filename'])
  9988. action.triggered.connect(o)
  9989. self.ui.recent.addAction(action)
  9990. except KeyError:
  9991. App.log.error("Unsupported file type: %s" % recent["kind"])
  9992. # Last action in Recent Files menu is one that Clear the content
  9993. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  9994. (_("Clear Recent files")), self)
  9995. clear_action.triggered.connect(reset_recent_files)
  9996. self.ui.recent.addSeparator()
  9997. self.ui.recent.addAction(clear_action)
  9998. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9999. # self.ui.menufilerecent.set_submenu(recent_menu)
  10000. # recent_menu.show_all()
  10001. # self.ui.recent.show()
  10002. self.log.debug("Recent items list has been populated.")
  10003. def setup_component_editor(self):
  10004. # label = QtWidgets.QLabel("Choose an item from Project")
  10005. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  10006. sel_title = QtWidgets.QTextEdit(
  10007. _('<b>Shortcut Key List</b>'))
  10008. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  10009. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  10010. settings = QSettings("Open Source", "FlatCAM")
  10011. if settings.contains("notebook_font_size"):
  10012. fsize = settings.value('notebook_font_size', type=int)
  10013. else:
  10014. fsize = 12
  10015. tsize = fsize + int(fsize / 2)
  10016. # selected_text = (_('''
  10017. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  10018. #
  10019. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  10020. # The normal flow when working in FlatCAM is the following:</span></p>
  10021. #
  10022. # <ol>
  10023. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  10024. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  10025. # even dragging and dropping the files on the GUI.<br />
  10026. # <br />
  10027. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  10028. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  10029. # &nbsp;</li>
  10030. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  10031. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  10032. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  10033. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  10034. # <br />
  10035. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  10036. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  10037. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  10038. # it even if it was out of focus.<br />
  10039. # <br />
  10040. # You can change the parameters in this screen and the flow direction is like this:<br />
  10041. # <br />
  10042. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  10043. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  10044. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  10045. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  10046. # </ol>
  10047. #
  10048. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  10049. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  10050. # <strong>F3</strong>.</span></p>
  10051. #
  10052. # ''').format(fsize=fsize, tsize=tsize))
  10053. selected_text = '''
  10054. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  10055. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  10056. {s1}</span></p>
  10057. <ol>
  10058. <li><span style="font-size:{fsize}px">{s2}<br />
  10059. <br />
  10060. {s3}</span><br />
  10061. &nbsp;</li>
  10062. <li><span style="font-size:{fsize}px">{s4}<br />
  10063. &nbsp;</li>
  10064. <br />
  10065. <li><span style="font-size:{fsize}px">{s5}<br />
  10066. &nbsp;</li>
  10067. <br />
  10068. <li><span style="font-size:{fsize}px">{s6}<br />
  10069. <br />
  10070. {s7}</span></li>
  10071. </ol>
  10072. <p><span style="font-size:{fsize}px">{s8}</span></p>
  10073. '''.format(
  10074. title=_("Selected Tab - Choose an Item from Project Tab"),
  10075. subtitle=_("Details"),
  10076. s1=_("The normal flow when working in FlatCAM is the following:"),
  10077. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  10078. "using either the toolbars, key shortcuts or even dragging and dropping the "
  10079. "files on the GUI."),
  10080. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  10081. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  10082. "actions offered within the app."),
  10083. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  10084. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  10085. "SELECTED TAB will be updated with the object properties according to its kind: "
  10086. "Gerber, Excellon, Geometry or CNCJob object."),
  10087. s5=_("If the selection of the object is done on the canvas by single click instead, "
  10088. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  10089. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  10090. "the SELECTED TAB and populate it even if it was out of focus."),
  10091. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  10092. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  10093. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  10094. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  10095. "(again, done in SELECTED TAB) --> Save GCode."),
  10096. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  10097. "or through its own key shortcut: <b>F3</b>."),
  10098. tsize=tsize,
  10099. fsize=fsize
  10100. )
  10101. sel_title.setText(selected_text)
  10102. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  10103. self.ui.selected_scroll_area.setWidget(sel_title)
  10104. def setup_obj_classes(self):
  10105. """
  10106. Sets up application specifics on the FlatCAMObj class.
  10107. :return: None
  10108. """
  10109. FlatCAMObj.app = self
  10110. ObjectCollection.app = self
  10111. Gerber.app = self
  10112. Excellon.app = self
  10113. Geometry.app = self
  10114. CNCjob.app = self
  10115. FCProcess.app = self
  10116. FCProcessContainer.app = self
  10117. OptionsGroupUI.app = self
  10118. def version_check(self):
  10119. """
  10120. Checks for the latest version of the program. Alerts the
  10121. user if theirs is outdated. This method is meant to be run
  10122. in a separate thread.
  10123. :return: None
  10124. """
  10125. self.log.debug("version_check()")
  10126. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  10127. full_url = App.version_url + \
  10128. "?s=" + str(self.defaults['global_serial']) + \
  10129. "&v=" + str(self.version) + \
  10130. "&os=" + str(self.os) + \
  10131. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  10132. else:
  10133. # no_stats dict; just so it won't break things on website
  10134. no_ststs_dict = {}
  10135. no_ststs_dict["global_ststs"] = {}
  10136. full_url = App.version_url + \
  10137. "?s=" + str(self.defaults['global_serial']) + \
  10138. "&v=" + str(self.version) + \
  10139. "&os=" + str(self.os) + \
  10140. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  10141. App.log.debug("Checking for updates @ %s" % full_url)
  10142. # ## Get the data
  10143. try:
  10144. f = urllib.request.urlopen(full_url)
  10145. except Exception:
  10146. # App.log.warning("Failed checking for latest version. Could not connect.")
  10147. self.log.warning("Failed checking for latest version. Could not connect.")
  10148. self.inform.emit('[WARNING_NOTCL] %s' %
  10149. _("Failed checking for latest version. Could not connect."))
  10150. return
  10151. try:
  10152. data = json.load(f)
  10153. except Exception as e:
  10154. App.log.error("Could not parse information about latest version.")
  10155. self.inform.emit('[ERROR_NOTCL] %s' %
  10156. _("Could not parse information about latest version."))
  10157. App.log.debug("json.load(): %s" % str(e))
  10158. f.close()
  10159. return
  10160. f.close()
  10161. # ## Latest version?
  10162. if self.version >= data["version"]:
  10163. App.log.debug("FlatCAM is up to date!")
  10164. self.inform.emit('[success] %s' %
  10165. _("FlatCAM is up to date!"))
  10166. return
  10167. App.log.debug("Newer version available.")
  10168. self.message.emit(
  10169. _("Newer Version Available"),
  10170. _("There is a newer version of FlatCAM available for download:\n\n") +
  10171. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  10172. _("info")
  10173. )
  10174. def on_plotcanvas_setup(self, container=None):
  10175. """
  10176. This is doing the setup for the plot area (canvas)
  10177. :param container: widget where to install the canvas
  10178. :return: None
  10179. """
  10180. if container:
  10181. plot_container = container
  10182. else:
  10183. plot_container = self.ui.right_layout
  10184. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  10185. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  10186. self.is_legacy = True
  10187. self.defaults["global_graphic_engine"] = "2D"
  10188. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  10189. else:
  10190. try:
  10191. self.plotcanvas = PlotCanvas(plot_container, self)
  10192. except Exception as er:
  10193. msg_txt = traceback.format_exc()
  10194. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  10195. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  10196. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  10197. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  10198. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  10199. msg += msg_txt
  10200. self.inform.emit(msg)
  10201. return 'fail'
  10202. # So it can receive key presses
  10203. self.plotcanvas.native.setFocus()
  10204. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  10205. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  10206. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  10207. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  10208. # Keys over plot enabled
  10209. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  10210. if self.defaults['global_cursor_type'] == 'small':
  10211. self.app_cursor = self.plotcanvas.new_cursor()
  10212. else:
  10213. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  10214. if self.ui.grid_snap_btn.isChecked():
  10215. self.app_cursor.enabled = True
  10216. else:
  10217. self.app_cursor.enabled = False
  10218. if self.is_legacy is False:
  10219. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  10220. else:
  10221. # will use the default Matplotlib axes
  10222. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  10223. def on_zoom_fit(self, event):
  10224. """
  10225. Callback for zoom-out request. This can be either from the corresponding
  10226. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  10227. with axes limits from the geometry bounds of all objects.
  10228. :param event: Ignored.
  10229. :return: None
  10230. """
  10231. if self.is_legacy is False:
  10232. self.plotcanvas.fit_view()
  10233. else:
  10234. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  10235. width = xmax - xmin
  10236. height = ymax - ymin
  10237. xmin -= 0.05 * width
  10238. xmax += 0.05 * width
  10239. ymin -= 0.05 * height
  10240. ymax += 0.05 * height
  10241. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  10242. def on_zoom_in(self):
  10243. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  10244. def on_zoom_out(self):
  10245. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  10246. def disable_all_plots(self):
  10247. self.report_usage("disable_all_plots()")
  10248. self.disable_plots(self.collection.get_list())
  10249. self.inform.emit('[success] %s' %
  10250. _("All plots disabled."))
  10251. def disable_other_plots(self):
  10252. self.report_usage("disable_other_plots()")
  10253. self.disable_plots(self.collection.get_non_selected())
  10254. self.inform.emit('[success] %s' %
  10255. _("All non selected plots disabled."))
  10256. def enable_all_plots(self):
  10257. self.report_usage("enable_all_plots()")
  10258. self.enable_plots(self.collection.get_list())
  10259. self.inform.emit('[success] %s' %
  10260. _("All plots enabled."))
  10261. def on_enable_sel_plots(self):
  10262. log.debug("App.on_enable_sel_plot()")
  10263. object_list = self.collection.get_selected()
  10264. self.enable_plots(objects=object_list)
  10265. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  10266. def on_disable_sel_plots(self):
  10267. log.debug("App.on_disable_sel_plot()")
  10268. # self.inform.emit(_("Disabling plots ..."))
  10269. object_list = self.collection.get_selected()
  10270. self.disable_plots(objects=object_list)
  10271. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  10272. def enable_plots(self, objects):
  10273. """
  10274. Disables plots
  10275. :param objects: list of Objects to be enabled
  10276. :return:
  10277. """
  10278. log.debug("Enabling plots ...")
  10279. # self.inform.emit(_("Working ..."))
  10280. for obj in objects:
  10281. if obj.options['plot'] is False:
  10282. obj.options.set_change_callback(lambda x: None)
  10283. obj.options['plot'] = True
  10284. try:
  10285. # only the Gerber obj has on_plot_cb_click() method
  10286. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  10287. # disable this cb while disconnected,
  10288. # in case the operation takes time the user is not allowed to change it
  10289. obj.ui.plot_cb.setDisabled(True)
  10290. except AttributeError:
  10291. pass
  10292. obj.set_form_item("plot")
  10293. try:
  10294. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  10295. obj.ui.plot_cb.setDisabled(False)
  10296. except AttributeError:
  10297. pass
  10298. obj.options.set_change_callback(obj.on_options_change)
  10299. def worker_task(objs):
  10300. with self.proc_container.new(_("Enabling plots ...")):
  10301. for obj in objs:
  10302. # obj.options['plot'] = True
  10303. if isinstance(obj, FlatCAMCNCjob):
  10304. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  10305. else:
  10306. obj.plot(visible=True)
  10307. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10308. # self.plots_updated.emit()
  10309. def disable_plots(self, objects):
  10310. """
  10311. Disables plots
  10312. :param objects: list of Objects to be disabled
  10313. :return:
  10314. """
  10315. # if no objects selected then do nothing
  10316. if not self.collection.get_selected():
  10317. return
  10318. log.debug("Disabling plots ...")
  10319. # self.inform.emit(_("Working ..."))
  10320. for obj in objects:
  10321. if obj.options['plot'] is True:
  10322. obj.options.set_change_callback(lambda x: None)
  10323. obj.options['plot'] = False
  10324. try:
  10325. # only the Gerber obj has on_plot_cb_click() method
  10326. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  10327. obj.ui.plot_cb.setDisabled(True)
  10328. except AttributeError:
  10329. pass
  10330. obj.set_form_item("plot")
  10331. try:
  10332. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  10333. obj.ui.plot_cb.setDisabled(False)
  10334. except AttributeError:
  10335. pass
  10336. obj.options.set_change_callback(obj.on_options_change)
  10337. try:
  10338. self.delete_selection_shape()
  10339. except Exception as e:
  10340. log.debug("App.disable_plots() --> %s" % str(e))
  10341. # self.plots_updated.emit()
  10342. def worker_task(objs):
  10343. with self.proc_container.new(_("Disabling plots ...")):
  10344. for obj in objs:
  10345. # obj.options['plot'] = True
  10346. if isinstance(obj, FlatCAMCNCjob):
  10347. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  10348. else:
  10349. obj.plot(visible=False)
  10350. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10351. def toggle_plots(self, objects):
  10352. """
  10353. Toggle plots visibility
  10354. :param objects: list of Objects for which to be toggled the visibility
  10355. :return:
  10356. """
  10357. # if no objects selected then do nothing
  10358. if not self.collection.get_selected():
  10359. return
  10360. log.debug("Toggling plots ...")
  10361. self.inform.emit(_("Working ..."))
  10362. for obj in objects:
  10363. if obj.options['plot'] is False:
  10364. obj.options['plot'] = True
  10365. else:
  10366. obj.options['plot'] = False
  10367. self.plots_updated.emit()
  10368. def clear_plots(self):
  10369. objects = self.collection.get_list()
  10370. for obj in objects:
  10371. obj.clear(obj == objects[-1])
  10372. # Clear pool to free memory
  10373. self.clear_pool()
  10374. def on_set_color_action_triggered(self):
  10375. new_color = self.defaults['gerber_plot_fill']
  10376. act_name = self.sender().text().lower()
  10377. sel_obj_list = self.collection.get_selected()
  10378. if not sel_obj_list:
  10379. return
  10380. if act_name == 'red':
  10381. new_color = '#FF0000' + \
  10382. str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  10383. if act_name == 'blue':
  10384. new_color = '#0000FF' + \
  10385. str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  10386. if act_name == 'yellow':
  10387. new_color = '#FFDF00' + \
  10388. str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  10389. if act_name == 'green':
  10390. new_color = '#00FF00' + \
  10391. str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  10392. if act_name == 'purple':
  10393. new_color = '#FF00FF' + \
  10394. str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  10395. if act_name == 'brown':
  10396. new_color = '#A52A2A' + \
  10397. str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  10398. if act_name == 'custom':
  10399. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  10400. c_dialog = QtWidgets.QColorDialog()
  10401. plot_fill_color = c_dialog.getColor(initial=new_color)
  10402. if plot_fill_color.isValid() is False:
  10403. return
  10404. new_color = str(plot_fill_color.name()) + \
  10405. str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  10406. new_line_color = color_variant(new_color[:7], 0.7)
  10407. for sel_obj in sel_obj_list:
  10408. sel_obj.fill_color = new_color
  10409. sel_obj.outline_color = new_line_color
  10410. sel_obj.shapes.redraw(
  10411. update_colors=(new_color, new_line_color)
  10412. )
  10413. def on_grid_snap_triggered(self, state):
  10414. if state:
  10415. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  10416. else:
  10417. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  10418. def generate_cnc_job(self, objects):
  10419. self.report_usage("generate_cnc_job()")
  10420. # for obj in objects:
  10421. # obj.generatecncjob()
  10422. for obj in objects:
  10423. obj.on_generatecnc_button_click()
  10424. def save_project(self, filename, quit_action=False, silent=False):
  10425. """
  10426. Saves the current project to the specified file.
  10427. :param filename: Name of the file in which to save.
  10428. :type filename: str
  10429. :param quit_action: if the project saving will be followed by an app quit; boolean
  10430. :param silent: if True will not display status messages
  10431. :return: None
  10432. """
  10433. self.log.debug("save_project()")
  10434. self.save_in_progress = True
  10435. with self.proc_container.new(_("Saving FlatCAM Project")):
  10436. # Capture the latest changes
  10437. # Current object
  10438. try:
  10439. self.collection.get_active().read_form()
  10440. except Exception as e:
  10441. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  10442. pass
  10443. # Serialize the whole project
  10444. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  10445. "options": self.options,
  10446. "version": self.version}
  10447. if self.defaults["global_save_compressed"] is True:
  10448. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  10449. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  10450. # # Write
  10451. f.write(g)
  10452. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  10453. else:
  10454. # Open file
  10455. try:
  10456. f = open(filename, 'w')
  10457. except IOError:
  10458. App.log.error("Failed to open file for saving: %s", filename)
  10459. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  10460. return
  10461. # Write
  10462. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  10463. f.close()
  10464. # verification of the saved project
  10465. # Open and parse
  10466. try:
  10467. saved_f = open(filename, 'r')
  10468. except IOError:
  10469. if silent is False:
  10470. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10471. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  10472. return
  10473. try:
  10474. saved_d = json.load(saved_f, object_hook=dict2obj)
  10475. except Exception:
  10476. if silent is False:
  10477. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10478. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  10479. f.close()
  10480. return
  10481. saved_f.close()
  10482. if silent is False:
  10483. if 'version' in saved_d:
  10484. self.inform.emit('[success] %s: %s' %
  10485. (_("Project saved to"), filename))
  10486. else:
  10487. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10488. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  10489. tb_settings = QSettings("Open Source", "FlatCAM")
  10490. lock_state = self.ui.lock_action.isChecked()
  10491. tb_settings.setValue('toolbar_lock', lock_state)
  10492. # This will write the setting to the platform specific storage.
  10493. del tb_settings
  10494. # if quit:
  10495. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  10496. # t.start()
  10497. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  10498. def start_delayed_quit(self, delay, filename, should_quit=None):
  10499. """
  10500. :param delay: period of checking if project file size is more than zero; in seconds
  10501. :param filename: the name of the project file to be checked periodically for size more than zero
  10502. :param should_quit: if the task finished will be followed by an app quit; boolean
  10503. :return:
  10504. """
  10505. to_quit = should_quit
  10506. self.save_timer = QtCore.QTimer()
  10507. self.save_timer.setInterval(delay)
  10508. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  10509. self.save_timer.start()
  10510. def check_project_file_size(self, filename, should_quit=None):
  10511. """
  10512. :param filename: the name of the project file to be checked periodically for size more than zero
  10513. :param should_quit: will quit the app if True; boolean
  10514. :return:
  10515. """
  10516. try:
  10517. if os.stat(filename).st_size > 0:
  10518. self.save_in_progress = False
  10519. self.save_timer.stop()
  10520. if should_quit:
  10521. self.app_quit.emit()
  10522. except Exception:
  10523. traceback.print_exc()
  10524. def on_plotarea_tab_closed(self, tab_idx):
  10525. widget = self.ui.plot_tab_area.widget(tab_idx)
  10526. if widget is not None:
  10527. widget.deleteLater()
  10528. self.ui.plot_tab_area.removeTab(tab_idx)
  10529. def on_options_app2project(self):
  10530. """
  10531. Callback for Options->Transfer Options->App=>Project. Copies options
  10532. from application defaults to project defaults.
  10533. :return: None
  10534. """
  10535. self.report_usage("on_options_app2project")
  10536. self.defaults_read_form()
  10537. self.options.update(self.defaults)
  10538. # self.options_write_form()
  10539. class ArgsThread(QtCore.QObject):
  10540. open_signal = pyqtSignal(list)
  10541. start = pyqtSignal()
  10542. if sys.platform == 'win32':
  10543. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  10544. else:
  10545. address = ('/tmp/testipc', 'AF_UNIX')
  10546. def __init__(self):
  10547. super(ArgsThread, self).__init__()
  10548. self.start.connect(self.run)
  10549. def my_loop(self, address):
  10550. try:
  10551. listener = Listener(*address)
  10552. while True:
  10553. conn = listener.accept()
  10554. self.serve(conn)
  10555. except socket.error:
  10556. conn = Client(*address)
  10557. conn.send(sys.argv)
  10558. conn.send('close')
  10559. # close the current instance only if there are args
  10560. if len(sys.argv) > 1:
  10561. sys.exit()
  10562. def serve(self, conn):
  10563. while True:
  10564. msg = conn.recv()
  10565. if msg == 'close':
  10566. break
  10567. self.open_signal.emit(msg)
  10568. conn.close()
  10569. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10570. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10571. @pyqtSlot()
  10572. def run(self):
  10573. self.my_loop(self.address)
  10574. class GracefulException(Exception):
  10575. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  10576. def __init__(self):
  10577. super().__init__()
  10578. def __str__(self):
  10579. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  10580. # end of file