FlatCAMApp.py 418 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import tkinter as tk
  20. from PyQt5 import QtPrintSupport
  21. from contextlib import contextmanager
  22. import gc
  23. from xml.dom.minidom import parseString as parse_xml_string
  24. # #######################################
  25. # # Imports part of FlatCAM ##
  26. # #######################################
  27. from ObjectCollection import *
  28. from FlatCAMObj import *
  29. from flatcamGUI.PlotCanvas import *
  30. from flatcamGUI.FlatCAMGUI import *
  31. from FlatCAMCommon import LoudDict
  32. from FlatCAMPostProc import load_postprocessors
  33. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  34. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  35. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  36. from FlatCAMProcess import *
  37. from FlatCAMWorkerStack import WorkerStack
  38. from flatcamGUI.VisPyVisuals import Color
  39. from vispy.gloo.util import _screenshot
  40. from vispy.io import write_png
  41. from flatcamTools import *
  42. from multiprocessing import Pool
  43. import tclCommands
  44. import gettext
  45. import FlatCAMTranslation as fcTranslate
  46. import builtins
  47. fcTranslate.apply_language('strings')
  48. if '_' not in builtins.__dict__:
  49. _ = gettext.gettext
  50. # ########################################
  51. # # App ###
  52. # ########################################
  53. class App(QtCore.QObject):
  54. """
  55. The main application class. The constructor starts the GUI.
  56. """
  57. # Get Cmd Line Options
  58. cmd_line_shellfile = ''
  59. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  60. try:
  61. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  62. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  63. except getopt.GetoptError:
  64. print(cmd_line_help)
  65. sys.exit(2)
  66. for opt, arg in cmd_line_options:
  67. if opt == '-h':
  68. print(cmd_line_help)
  69. sys.exit()
  70. elif opt == '--shellfile':
  71. cmd_line_shellfile = arg
  72. # ## Logging ###
  73. log = logging.getLogger('base')
  74. log.setLevel(logging.DEBUG)
  75. # log.setLevel(logging.WARNING)
  76. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  77. handler = logging.StreamHandler()
  78. handler.setFormatter(formatter)
  79. log.addHandler(handler)
  80. # ####################################
  81. # Version and VERSION DATE ###########
  82. # ####################################
  83. version = 8.97
  84. version_date = "2019/08/31"
  85. beta = True
  86. # current date now
  87. date = str(datetime.today()).rpartition('.')[0]
  88. date = ''.join(c for c in date if c not in ':-')
  89. date = date.replace(' ', '_')
  90. # URL for update checks and statistics
  91. version_url = "http://flatcam.org/version"
  92. # App URL
  93. app_url = "http://flatcam.org"
  94. # Manual URL
  95. manual_url = "http://flatcam.org/manual/index.html"
  96. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  97. # this variable will hold the project status
  98. # if True it will mean that the project was modified and not saved
  99. should_we_save = False
  100. # flag is True if saving action has been triggered
  101. save_in_progress = False
  102. # #################
  103. # # Signals ##
  104. # #################
  105. # Inform the user
  106. # Handled by:
  107. # * App.info() --> Print on the status bar
  108. inform = QtCore.pyqtSignal(str)
  109. app_quit = QtCore.pyqtSignal()
  110. # General purpose background task
  111. worker_task = QtCore.pyqtSignal(dict)
  112. # File opened
  113. # Handled by:
  114. # * register_folder()
  115. # * register_recent()
  116. # Note: Setting the parameters to unicode does not seem
  117. # to have an effect. Then are received as Qstring
  118. # anyway.
  119. # File type and filename
  120. file_opened = QtCore.pyqtSignal(str, str)
  121. # File type and filename
  122. file_saved = QtCore.pyqtSignal(str, str)
  123. # Percentage of progress
  124. progress = QtCore.pyqtSignal(int)
  125. plots_updated = QtCore.pyqtSignal()
  126. # Emitted by new_object() and passes the new object as argument, plot flag.
  127. # on_object_created() adds the object to the collection, plots on appropriate flag
  128. # and emits new_object_available.
  129. object_created = QtCore.pyqtSignal(object, bool, bool)
  130. # Emitted when a object has been changed (like scaled, mirrored)
  131. object_changed = QtCore.pyqtSignal(object)
  132. # Emitted after object has been plotted.
  133. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  134. object_plotted = QtCore.pyqtSignal(object)
  135. # Emitted when a new object has been added or deleted from/to the collection
  136. object_status_changed = QtCore.pyqtSignal(object, str)
  137. message = QtCore.pyqtSignal(str, str, str)
  138. # Emmited when shell command is finished(one command only)
  139. shell_command_finished = QtCore.pyqtSignal(object)
  140. # Emitted when multiprocess pool has been recreated
  141. pool_recreated = QtCore.pyqtSignal(object)
  142. # Emitted when an unhandled exception happens
  143. # in the worker task.
  144. thread_exception = QtCore.pyqtSignal(object)
  145. # used to signal that there are arguments for the app
  146. args_at_startup = QtCore.pyqtSignal()
  147. def __init__(self, user_defaults=True, post_gui=None):
  148. """
  149. Starts the application.
  150. :return: app
  151. :rtype: App
  152. """
  153. App.log.info("FlatCAM Starting...")
  154. self.main_thread = QtWidgets.QApplication.instance().thread()
  155. # #######################
  156. # # ## OS-specific ######
  157. # #######################
  158. portable = False
  159. # Folder for user settings.
  160. if sys.platform == 'win32':
  161. from win32com.shell import shell, shellcon
  162. if platform.architecture()[0] == '32bit':
  163. App.log.debug("Win32!")
  164. else:
  165. App.log.debug("Win64!")
  166. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  167. try:
  168. with open(config_file, 'r') as f:
  169. try:
  170. for line in f:
  171. param = str(line).rpartition('=')
  172. if param[0] == 'portable':
  173. try:
  174. portable = eval(param[2])
  175. except NameError:
  176. portable = False
  177. except Exception as e:
  178. log.debug('App.__init__() -->%s' % str(e))
  179. return
  180. except FileNotFoundError:
  181. pass
  182. if portable is False:
  183. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  184. else:
  185. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  186. self.os = 'windows'
  187. else: # Linux/Unix/MacOS
  188. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  189. self.os = 'unix'
  190. # ############################ ##
  191. # # ## Setup folders and files # ##
  192. # ############################ ##
  193. if not os.path.exists(self.data_path):
  194. os.makedirs(self.data_path)
  195. App.log.debug('Created data folder: ' + self.data_path)
  196. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  197. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  198. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  199. if not os.path.exists(self.postprocessorpaths):
  200. os.makedirs(self.postprocessorpaths)
  201. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  202. # create current_defaults.FlatConfig file if there is none
  203. try:
  204. f = open(self.data_path + '/current_defaults.FlatConfig')
  205. f.close()
  206. except IOError:
  207. App.log.debug('Creating empty current_defaults.FlatConfig')
  208. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  209. json.dump({}, f)
  210. f.close()
  211. # create factory_defaults.FlatConfig file if there is none
  212. try:
  213. f = open(self.data_path + '/factory_defaults.FlatConfig')
  214. f.close()
  215. except IOError:
  216. App.log.debug('Creating empty factory_defaults.FlatConfig')
  217. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  218. json.dump({}, f)
  219. f.close()
  220. try:
  221. f = open(self.data_path + '/recent.json')
  222. f.close()
  223. except IOError:
  224. App.log.debug('Creating empty recent.json')
  225. f = open(self.data_path + '/recent.json', 'w')
  226. json.dump([], f)
  227. f.close()
  228. try:
  229. fp = open(self.data_path + '/recent_projects.json')
  230. fp.close()
  231. except IOError:
  232. App.log.debug('Creating empty recent_projects.json')
  233. fp = open(self.data_path + '/recent_projects.json', 'w')
  234. json.dump([], fp)
  235. fp.close()
  236. # Application directory. CHDIR to it. Otherwise, trying to load
  237. # GUI icons will fail as their path is relative.
  238. # This will fail under cx_freeze ...
  239. self.app_home = os.path.dirname(os.path.realpath(__file__))
  240. App.log.debug("Application path is " + self.app_home)
  241. App.log.debug("Started in " + os.getcwd())
  242. # cx_freeze workaround
  243. if os.path.isfile(self.app_home):
  244. self.app_home = os.path.dirname(self.app_home)
  245. os.chdir(self.app_home)
  246. # Create multiprocessing pool
  247. self.pool = Pool()
  248. # variable to store mouse coordinates
  249. self.mouse = [0, 0]
  250. # ###################
  251. # # Initialize GUI ##
  252. # ###################
  253. # FlatCAM colors used in plotting
  254. self.FC_light_green = '#BBF268BF'
  255. self.FC_dark_green = '#006E20BF'
  256. self.FC_light_blue = '#a5a5ffbf'
  257. self.FC_dark_blue = '#0000ffbf'
  258. QtCore.QObject.__init__(self)
  259. self.ui = FlatCAMGUI(self.version, self.beta, self)
  260. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  261. self.ui.final_save.connect(self.final_save)
  262. # #############
  263. # ### Data ####
  264. # #############
  265. self.recent = []
  266. self.recent_projects = []
  267. self.clipboard = QtWidgets.QApplication.clipboard()
  268. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  269. self.project_filename = None
  270. self.toggle_units_ignore = False
  271. # self.defaults_form = PreferencesUI()
  272. # when adding entries here read the comments in the method found bellow named:
  273. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  274. self.defaults_form_fields = {
  275. # General App
  276. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  277. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  278. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  279. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  280. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  281. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  282. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  283. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  284. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  285. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  286. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  287. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  288. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  289. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  290. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  291. "global_delete_confirmation": self.ui.general_defaults_form.general_app_group.delete_conf_cb,
  292. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  293. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  294. # General GUI Preferences
  295. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  296. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  297. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  298. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  299. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  300. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  301. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  302. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  303. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  304. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  305. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  306. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  307. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  308. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  309. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  310. # General GUI Settings
  311. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  312. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  313. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  314. # Gerber General
  315. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  316. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  317. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  318. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  319. # Gerber Options
  320. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  321. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  322. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  323. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  324. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  325. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  326. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  327. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  328. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  329. # Gerber Advanced Options
  330. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  331. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  332. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  333. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  334. # Gerber Export
  335. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  336. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  337. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  338. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  339. # Gerber Editor
  340. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  341. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  342. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  343. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  344. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  345. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  346. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  347. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  348. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  349. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  350. "gerber_editor_circ_angle":
  351. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  352. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  353. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  354. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  355. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  356. # Excellon General
  357. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  358. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  359. "excellon_format_upper_in":
  360. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  361. "excellon_format_lower_in":
  362. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  363. "excellon_format_upper_mm":
  364. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  365. "excellon_format_lower_mm":
  366. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  367. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  368. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  369. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  370. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  371. # Excellon Options
  372. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  373. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  374. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  375. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  376. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  377. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  378. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  379. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  380. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  381. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  382. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  383. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  384. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  385. # Excellon Advanced Options
  386. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  387. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  388. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  389. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  390. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  391. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  392. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  393. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  394. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  395. # Excellon Export
  396. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  397. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  398. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  399. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  400. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  401. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  402. # Excellon Editor
  403. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  404. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  405. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  406. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  407. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  408. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  409. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  410. "excellon_editor_circ_angle":
  411. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  412. # Excellon Slots
  413. "excellon_editor_slot_direction":
  414. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  415. "excellon_editor_slot_angle":
  416. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  417. "excellon_editor_slot_length":
  418. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  419. # Excellon Slots
  420. "excellon_editor_slot_array_size":
  421. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  422. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  423. "excellon_editor_slot_lin_pitch":
  424. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  425. "excellon_editor_slot_lin_angle":
  426. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  427. "excellon_editor_slot_circ_dir":
  428. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  429. "excellon_editor_slot_circ_angle":
  430. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  431. # Geometry General
  432. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  433. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  434. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  435. # Geometry Options
  436. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  437. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  438. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  439. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  440. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  441. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  442. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  443. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  444. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  445. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  446. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  447. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  448. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  449. # Geometry Advanced Options
  450. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  451. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  452. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  453. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  454. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  455. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  456. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  457. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  458. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  459. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  460. # Geometry Editor
  461. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  462. # CNCJob General
  463. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  464. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  465. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  466. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontsize_sp,
  467. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry,
  468. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  469. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  470. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  471. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  472. # CNC Job Options
  473. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  474. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  475. # CNC Job Advanced Options
  476. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  477. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  478. # NCC Tool
  479. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  480. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  481. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  482. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  483. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  484. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  485. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  486. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  487. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  488. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  489. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  490. # CutOut Tool
  491. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  492. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  493. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  494. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  495. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  496. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  497. # Paint Area Tool
  498. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  499. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  500. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  501. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  502. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  503. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  504. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  505. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  506. # 2-sided Tool
  507. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  508. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  509. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  510. # Film Tool
  511. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  512. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  513. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  514. # Panelize Tool
  515. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  516. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  517. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  518. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  519. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  520. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  521. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  522. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  523. # Calculators Tool
  524. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  525. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  526. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  527. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  528. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  529. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  530. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  531. # Transformations Tool
  532. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  533. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  534. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  535. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  536. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  537. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  538. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  539. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  540. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  541. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  542. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  543. # SolderPaste Dispensing Tool
  544. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  545. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  546. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  547. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  548. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  549. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  550. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  551. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  552. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  553. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  554. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  555. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  556. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  557. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  558. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  559. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  560. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb
  561. }
  562. # ############################
  563. # ### LOAD POSTPROCESSORS ####
  564. # ############################
  565. self.postprocessors = load_postprocessors(self)
  566. for name in list(self.postprocessors.keys()):
  567. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  568. if name.partition('_')[0] == 'Paste':
  569. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  570. continue
  571. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  572. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  573. if name == 'hpgl':
  574. continue
  575. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  576. # ############################
  577. # ### LOAD LANGUAGES ####
  578. # ############################
  579. self.languages = fcTranslate.load_languages()
  580. for name in sorted(self.languages.values()):
  581. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  582. self.defaults = LoudDict()
  583. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  584. self.defaults.update({
  585. # Global APP Preferences
  586. "global_serial": 0,
  587. "global_stats": {},
  588. "global_tabs_detachable": True,
  589. "units": "IN",
  590. "global_app_level": 'b',
  591. "global_portable": False,
  592. "global_language": 'English',
  593. "global_version_check": True,
  594. "global_send_stats": True,
  595. "global_pan_button": '2',
  596. "global_mselect_key": 'Control',
  597. "global_project_at_startup": False,
  598. "global_project_autohide": True,
  599. "global_toggle_tooltips": True,
  600. "global_worker_number": 2,
  601. "global_tolerance": 0.01,
  602. "global_open_style": True,
  603. "global_delete_confirmation": True,
  604. "global_compression_level": 3,
  605. "global_save_compressed": True,
  606. # Global GUI Preferences
  607. "global_gridx": 0.0393701,
  608. "global_gridy": 0.0393701,
  609. "global_snap_max": 0.001968504,
  610. "global_workspace": False,
  611. "global_workspaceT": "A4P",
  612. "global_grid_context_menu": {
  613. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  614. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  615. },
  616. "global_plot_fill": '#BBF268BF',
  617. "global_plot_line": '#006E20BF',
  618. "global_sel_fill": '#a5a5ffbf',
  619. "global_sel_line": '#0000ffbf',
  620. "global_alt_sel_fill": '#BBF268BF',
  621. "global_alt_sel_line": '#006E20BF',
  622. "global_draw_color": '#FF0000',
  623. "global_sel_draw_color": '#0000FF',
  624. "global_proj_item_color": '#000000',
  625. "global_proj_item_dis_color": '#b7b7cb',
  626. "global_toolbar_view": 511,
  627. "global_background_timeout": 300000, # Default value is 5 minutes
  628. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  629. # (python trace only for unknown errors),
  630. # 1 = show trace(show trace always),
  631. # 2 = (For the future).
  632. # Persistence
  633. "global_last_folder": None,
  634. "global_last_save_folder": None,
  635. # Default window geometry
  636. "global_def_win_x": 100,
  637. "global_def_win_y": 100,
  638. "global_def_win_w": 1024,
  639. "global_def_win_h": 650,
  640. "global_def_notebook_width": 1,
  641. # Constants...
  642. "global_defaults_save_period_ms": 20000, # Time between default saves.
  643. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  644. "global_shell_at_startup": False, # Show the shell at startup.
  645. "global_recent_limit": 10, # Max. items in recent list.
  646. "fit_key": 'V',
  647. "zoom_out_key": '-',
  648. "zoom_in_key": '=',
  649. "grid_toggle_key": 'G',
  650. "global_zoom_ratio": 1.5,
  651. "global_point_clipboard_format": "(%.4f, %.4f)",
  652. "global_zdownrate": None,
  653. # General GUI Settings
  654. "global_hover": False,
  655. "global_selection_shape": True,
  656. "global_layout": "compact",
  657. # Gerber General
  658. "gerber_plot": True,
  659. "gerber_solid": True,
  660. "gerber_multicolored": False,
  661. "gerber_isotooldia": 0.00787402,
  662. "gerber_isopasses": 1,
  663. "gerber_isooverlap": 0.00393701,
  664. # Gerber Options
  665. "gerber_combine_passes": False,
  666. "gerber_milling_type": "cl",
  667. "gerber_noncoppermargin": 0.00393701,
  668. "gerber_noncopperrounded": False,
  669. "gerber_bboxmargin": 0.00393701,
  670. "gerber_bboxrounded": False,
  671. "gerber_circle_steps": 128,
  672. "gerber_use_buffer_for_union": True,
  673. # Gerber Advanced Options
  674. "gerber_aperture_display": False,
  675. "gerber_aperture_scale_factor": 1.0,
  676. "gerber_aperture_buffer_factor": 0.0,
  677. "gerber_follow": False,
  678. # Gerber Export
  679. "gerber_exp_units": 'IN',
  680. "gerber_exp_integer": 2,
  681. "gerber_exp_decimals": 4,
  682. "gerber_exp_zeros": 'L',
  683. # Gerber Editor
  684. "gerber_editor_sel_limit": 30,
  685. "gerber_editor_newcode": 10,
  686. "gerber_editor_newsize": 0.8,
  687. "gerber_editor_newtype": 'C',
  688. "gerber_editor_newdim": "0.5, 0.5",
  689. "gerber_editor_array_size": 5,
  690. "gerber_editor_lin_axis": 'X',
  691. "gerber_editor_lin_pitch": 1,
  692. "gerber_editor_lin_angle": 0.0,
  693. "gerber_editor_circ_dir": 'CW',
  694. "gerber_editor_circ_angle": 0.0,
  695. "gerber_editor_scale_f": 1.0,
  696. "gerber_editor_buff_f": 0.1,
  697. "gerber_editor_ma_low": 0.0,
  698. "gerber_editor_ma_high": 1.0,
  699. # Excellon General
  700. "excellon_plot": True,
  701. "excellon_solid": True,
  702. "excellon_format_upper_in": 2,
  703. "excellon_format_lower_in": 4,
  704. "excellon_format_upper_mm": 3,
  705. "excellon_format_lower_mm": 3,
  706. "excellon_zeros": "L",
  707. "excellon_units": "INCH",
  708. "excellon_optimization_type": 'B',
  709. "excellon_search_time": 3,
  710. # Excellon Options
  711. "excellon_drillz": -0.0590551,
  712. "excellon_travelz": 0.0787402,
  713. "excellon_feedrate": 3.14961,
  714. "excellon_spindlespeed": None,
  715. "excellon_spindledir": 'CW',
  716. "excellon_dwell": False,
  717. "excellon_dwelltime": 1,
  718. "excellon_toolchange": False,
  719. "excellon_toolchangez": 0.5,
  720. "excellon_ppname_e": 'default',
  721. "excellon_tooldia": 0.0314961,
  722. "excellon_slot_tooldia": 0.0708661,
  723. "excellon_gcode_type": "drills",
  724. # Excellon Advanced Options
  725. "excellon_offset": 0.0,
  726. "excellon_toolchangexy": "0.0, 0.0",
  727. "excellon_startz": None,
  728. "excellon_endz": 0.5,
  729. "excellon_feedrate_rapid": 31.4961,
  730. "excellon_z_pdepth": -0.02,
  731. "excellon_feedrate_probe": 3.14961,
  732. "excellon_f_plunge": False,
  733. "excellon_f_retract": False,
  734. # Excellon Export
  735. "excellon_exp_units": 'INCH',
  736. "excellon_exp_format": 'ndec',
  737. "excellon_exp_integer": 2,
  738. "excellon_exp_decimals": 4,
  739. "excellon_exp_zeros": 'LZ',
  740. "excellon_exp_slot_type": 'routing',
  741. # Excellon Editor
  742. "excellon_editor_sel_limit": 30,
  743. "excellon_editor_newdia": 0.039,
  744. "excellon_editor_array_size": 5,
  745. "excellon_editor_lin_dir": 'X',
  746. "excellon_editor_lin_pitch": 0.1,
  747. "excellon_editor_lin_angle": 0.0,
  748. "excellon_editor_circ_dir": 'CW',
  749. "excellon_editor_circ_angle": 12,
  750. # Excellon Slots
  751. "excellon_editor_slot_direction": 'X',
  752. "excellon_editor_slot_angle": 0.0,
  753. "excellon_editor_slot_length": 5.0,
  754. # Excellon Slot Array
  755. "excellon_editor_slot_array_size": 5,
  756. "excellon_editor_slot_lin_dir": 'X',
  757. "excellon_editor_slot_lin_pitch": 0.1,
  758. "excellon_editor_slot_lin_angle": 0.0,
  759. "excellon_editor_slot_circ_dir": 'CW',
  760. "excellon_editor_slot_circ_angle": 0.0,
  761. # Geometry General
  762. "geometry_plot": True,
  763. "geometry_circle_steps": 128,
  764. "geometry_cnctooldia": "0.0944882",
  765. # Geometry Options
  766. "geometry_cutz": -0.0944882,
  767. "geometry_vtipdia": 0.1,
  768. "geometry_vtipangle": 30,
  769. "geometry_multidepth": False,
  770. "geometry_depthperpass": 0.0314961,
  771. "geometry_travelz": 0.0787402,
  772. "geometry_toolchange": False,
  773. "geometry_toolchangez": 0.5,
  774. "geometry_feedrate": 3.14961,
  775. "geometry_feedrate_z": 3.14961,
  776. "geometry_spindlespeed": None,
  777. "geometry_spindledir": 'CW',
  778. "geometry_dwell": False,
  779. "geometry_dwelltime": 1,
  780. "geometry_ppname_g": 'default',
  781. # Geometry Advanced Options
  782. "geometry_toolchangexy": "0.0, 0.0",
  783. "geometry_startz": None,
  784. "geometry_endz": 0.5,
  785. "geometry_feedrate_rapid": 3.14961,
  786. "geometry_extracut": False,
  787. "geometry_z_pdepth": -0.02,
  788. "geometry_f_plunge": False,
  789. "geometry_feedrate_probe": 3.14961,
  790. "geometry_segx": 0.0,
  791. "geometry_segy": 0.0,
  792. # Geometry Editor
  793. "geometry_editor_sel_limit": 30,
  794. # CNC Job General
  795. "cncjob_plot": True,
  796. "cncjob_plot_kind": 'all',
  797. "cncjob_annotation": True,
  798. "cncjob_annotation_fontsize": 9,
  799. "cncjob_annotation_fontcolor": '#990000',
  800. "cncjob_tooldia": 0.0393701,
  801. "cncjob_coords_decimals": 4,
  802. "cncjob_fr_decimals": 2,
  803. "cncjob_steps_per_circle": 128,
  804. # CNC Job Options
  805. "cncjob_prepend": "",
  806. "cncjob_append": "",
  807. # CNC Job Advanced Options
  808. "cncjob_toolchange_macro": "",
  809. "cncjob_toolchange_macro_enable": False,
  810. "tools_ncctools": "0.0393701, 0.019685",
  811. "tools_nccorder": 'rev',
  812. "tools_nccoverlap": 0.015748,
  813. "tools_nccmargin": 0.0393701,
  814. "tools_nccmethod": "seed",
  815. "tools_nccconnect": True,
  816. "tools_ncccontour": True,
  817. "tools_nccrest": False,
  818. "tools_ncc_offset_choice": False,
  819. "tools_ncc_offset_value": 0.0000,
  820. "tools_nccref": 'itself',
  821. "tools_cutouttooldia": 0.0944882,
  822. "tools_cutoutkind": "single",
  823. "tools_cutoutmargin": 0.00393701,
  824. "tools_cutoutgapsize": 0.15748,
  825. "tools_gaps_ff": "4",
  826. "tools_cutout_convexshape": False,
  827. "tools_painttooldia": 0.023622,
  828. "tools_paintorder": 'rev',
  829. "tools_paintoverlap": 0.015748,
  830. "tools_paintmargin": 0.0,
  831. "tools_paintmethod": "seed",
  832. "tools_selectmethod": "single",
  833. "tools_pathconnect": True,
  834. "tools_paintcontour": True,
  835. "tools_2sided_mirror_axis": "X",
  836. "tools_2sided_axis_loc": "point",
  837. "tools_2sided_drilldia": 0.0393701,
  838. "tools_film_type": 'neg',
  839. "tools_film_boundary": 0.0393701,
  840. "tools_film_scale": 0,
  841. "tools_panelize_spacing_columns": 0,
  842. "tools_panelize_spacing_rows": 0,
  843. "tools_panelize_columns": 1,
  844. "tools_panelize_rows": 1,
  845. "tools_panelize_constrain": False,
  846. "tools_panelize_constrainx": 0.0,
  847. "tools_panelize_constrainy": 0.0,
  848. "tools_panelize_panel_type": 'gerber',
  849. "tools_calc_vshape_tip_dia": 0.007874,
  850. "tools_calc_vshape_tip_angle": 30,
  851. "tools_calc_vshape_cut_z": 0.000787,
  852. "tools_calc_electro_length": 10.0,
  853. "tools_calc_electro_width": 10.0,
  854. "tools_calc_electro_cdensity": 13.0,
  855. "tools_calc_electro_growth": 10.0,
  856. "tools_transform_rotate": 90,
  857. "tools_transform_skew_x": 0.0,
  858. "tools_transform_skew_y": 0.0,
  859. "tools_transform_scale_x": 1.0,
  860. "tools_transform_scale_y": 1.0,
  861. "tools_transform_scale_link": True,
  862. "tools_transform_scale_reference": True,
  863. "tools_transform_offset_x": 0.0,
  864. "tools_transform_offset_y": 0.0,
  865. "tools_transform_mirror_reference": False,
  866. "tools_transform_mirror_point": (0, 0),
  867. "tools_solderpaste_tools": "0.0393701, 0.011811",
  868. "tools_solderpaste_new": 0.011811,
  869. "tools_solderpaste_z_start": 0.00019685039,
  870. "tools_solderpaste_z_dispense": 0.00393701,
  871. "tools_solderpaste_z_stop": 0.00019685039,
  872. "tools_solderpaste_z_travel": 0.00393701,
  873. "tools_solderpaste_z_toolchange": 0.0393701,
  874. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  875. "tools_solderpaste_frxy": 3.0,
  876. "tools_solderpaste_frz": 3.0,
  877. "tools_solderpaste_frz_dispense": 0.0393701,
  878. "tools_solderpaste_speedfwd": 20,
  879. "tools_solderpaste_dwellfwd": 1,
  880. "tools_solderpaste_speedrev": 10,
  881. "tools_solderpaste_dwellrev": 1,
  882. "tools_solderpaste_pp": 'Paste_1',
  883. "tools_sub_close_paths": True
  884. })
  885. # ##############################
  886. # ## Load defaults from file ###
  887. # ##############################
  888. if user_defaults:
  889. self.load_defaults(filename='current_defaults')
  890. # ###########################
  891. # #### APPLY APP LANGUAGE ###
  892. # ###########################
  893. ret_val = fcTranslate.apply_language('strings')
  894. if ret_val == "no language":
  895. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  896. log.debug("Could not find the Language files. The App strings are missing.")
  897. else:
  898. # make the current language the current selection on the language combobox
  899. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  900. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  901. # ##################################
  902. # ### CREATE UNIQUE SERIAL NUMBER ##
  903. # ##################################
  904. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  905. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  906. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  907. self.save_defaults(silent=True)
  908. self.propagate_defaults(silent=True)
  909. self.restore_main_win_geom()
  910. def auto_save_defaults():
  911. try:
  912. self.save_defaults(silent=True)
  913. self.propagate_defaults(silent=True)
  914. finally:
  915. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  916. # the following lines activates automatic defaults save
  917. # if user_defaults:
  918. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  919. # self.options_form = PreferencesUI()
  920. self.options_form_fields = {
  921. "units": self.ui.general_options_form.general_app_group.units_radio,
  922. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  923. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  924. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  925. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  926. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  927. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  928. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  929. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  930. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  931. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  932. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  933. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  934. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  935. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  936. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  937. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  938. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  939. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  940. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  941. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  942. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  943. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  944. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  945. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  946. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  947. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  948. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  949. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  950. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  951. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  952. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  953. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  954. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  955. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  956. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  957. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  958. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  959. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  960. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  961. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  962. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  963. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  964. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  965. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  966. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  967. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  968. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  969. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  970. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  971. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  972. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  973. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  974. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  975. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  976. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  977. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  978. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  979. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  980. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  981. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  982. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  983. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  984. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  985. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  986. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  987. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  988. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  989. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  990. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  991. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  992. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  993. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  994. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  995. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  996. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  997. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  998. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  999. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1000. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1001. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1002. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1003. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1004. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1005. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1006. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1007. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1008. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1009. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1010. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1011. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1012. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1013. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1014. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1015. }
  1016. for name in list(self.postprocessors.keys()):
  1017. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1018. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1019. self.options = LoudDict()
  1020. self.options.set_change_callback(self.on_options_dict_change)
  1021. self.options.update({
  1022. "units": "IN",
  1023. "global_gridx": 1.0,
  1024. "global_gridy": 1.0,
  1025. "global_snap_max": 0.05,
  1026. "global_background_timeout": 300000, # Default value is 5 minutes
  1027. "global_verbose_error_level": 0, # Shell verbosity:
  1028. # 0 = default(python trace only for unknown errors),
  1029. # 1 = show trace(show trace allways), 2 = (For the future).
  1030. "gerber_plot": True,
  1031. "gerber_solid": True,
  1032. "gerber_multicolored": False,
  1033. "gerber_isotooldia": 0.016,
  1034. "gerber_isopasses": 1,
  1035. "gerber_isooverlap": 0.15,
  1036. "gerber_combine_passes": True,
  1037. "gerber_noncoppermargin": 0.0,
  1038. "gerber_noncopperrounded": False,
  1039. "gerber_bboxmargin": 0.0,
  1040. "gerber_bboxrounded": False,
  1041. "excellon_plot": True,
  1042. "excellon_solid": False,
  1043. "excellon_format_upper_in": 2,
  1044. "excellon_format_lower_in": 4,
  1045. "excellon_format_upper_mm": 3,
  1046. "excellon_format_lower_mm": 3,
  1047. "excellon_units": 'INCH',
  1048. "excellon_optimization_type": 'B',
  1049. "excellon_search_time": 3,
  1050. "excellon_zeros": "L",
  1051. "excellon_drillz": -0.1,
  1052. "excellon_travelz": 0.1,
  1053. "excellon_feedrate": 3.0,
  1054. "excellon_feedrate_rapid": 3.0,
  1055. "excellon_spindlespeed": None,
  1056. "excellon_spindledir": 'CW',
  1057. "excellon_dwell": True,
  1058. "excellon_dwelltime": 1000,
  1059. "excellon_toolchange": False,
  1060. "excellon_toolchangez": 1.0,
  1061. "excellon_toolchangexy": "0.0, 0.0",
  1062. "excellon_tooldia": 0.016,
  1063. "excellon_ppname_e": 'default',
  1064. "excellon_f_plunge": False,
  1065. "excellon_startz": None,
  1066. "excellon_endz": 2.0,
  1067. "geometry_plot": True,
  1068. "geometry_segx": 0.0,
  1069. "geometry_segy": 0.0,
  1070. "geometry_cutz": -0.002,
  1071. "geometry_vtipdia": 0.1,
  1072. "geometry_vtipangle": 30,
  1073. "geometry_travelz": 0.1,
  1074. "geometry_feedrate": 3.0,
  1075. "geometry_feedrate_z": 3.0,
  1076. "geometry_feedrate_rapid": 3.0,
  1077. "geometry_spindlespeed": None,
  1078. "geometry_spindledir": 'CW',
  1079. "geometry_dwell": True,
  1080. "geometry_dwelltime": 1000,
  1081. "geometry_cnctooldia": 0.016,
  1082. "geometry_toolchange": False,
  1083. "geometry_toolchangez": 2.0,
  1084. "geometry_toolchangexy": "0.0, 0.0",
  1085. "geometry_startz": None,
  1086. "geometry_endz": 2.0,
  1087. "geometry_ppname_g": "default",
  1088. "geometry_f_plunge": False,
  1089. "geometry_depthperpass": 0.002,
  1090. "geometry_multidepth": False,
  1091. "geometry_extracut": False,
  1092. "cncjob_plot": True,
  1093. "cncjob_tooldia": 0.016,
  1094. "cncjob_prepend": "",
  1095. "cncjob_append": "",
  1096. "tools_ncctools": "1.0, 0.5",
  1097. "tools_nccoverlap": 0.4,
  1098. "tools_nccmargin": 1,
  1099. "tools_cutouttooldia": 0.07,
  1100. "tools_cutoutmargin": 0.1,
  1101. "tools_cutoutgapsize": 0.15,
  1102. "tools_gaps_ff": "8",
  1103. "tools_painttooldia": 0.07,
  1104. "tools_paintoverlap": 0.15,
  1105. "tools_paintmargin": 0.0,
  1106. "tools_paintmethod": "seed",
  1107. "tools_selectmethod": "single",
  1108. "tools_pathconnect": True,
  1109. "tools_paintcontour": True,
  1110. "tools_2sided_mirror_axis": "X",
  1111. "tools_2sided_axis_loc": 'point',
  1112. "tools_2sided_drilldia": 1,
  1113. "tools_film_type": 'neg',
  1114. "tools_film_boundary": 1,
  1115. "tools_film_scale": 0,
  1116. "tools_panelize_spacing_columns": 0,
  1117. "tools_panelize_spacing_rows": 0,
  1118. "tools_panelize_columns": 1,
  1119. "tools_panelize_rows": 1,
  1120. "tools_panelize_constrain": False,
  1121. "tools_panelize_constrainx": 0.0,
  1122. "tools_panelize_constrainy": 0.0
  1123. })
  1124. self.options.update(self.defaults) # Copy app defaults to project options
  1125. self.gen_form = None
  1126. self.ger_form = None
  1127. self.exc_form = None
  1128. self.geo_form = None
  1129. self.cnc_form = None
  1130. self.tools_form = None
  1131. self.on_options_combo_change(0) # Will show the initial form
  1132. # ################################
  1133. # ### Initialize the color box's color in Preferences -> Global -> Color
  1134. # Init Plot Colors
  1135. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1136. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1137. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1138. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1139. int(self.defaults['global_plot_fill'][7:9], 16))
  1140. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1141. int(self.defaults['global_plot_fill'][7:9], 16))
  1142. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1143. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1144. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1145. # Init Left-Right Selection colors
  1146. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1147. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1148. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1149. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1150. int(self.defaults['global_sel_fill'][7:9], 16))
  1151. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1152. int(self.defaults['global_sel_fill'][7:9], 16))
  1153. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1154. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1155. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1156. # Init Right-Left Selection colors
  1157. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1158. self.defaults['global_alt_sel_fill'])
  1159. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1160. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1161. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1162. int(self.defaults['global_sel_fill'][7:9], 16))
  1163. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1164. int(self.defaults['global_sel_fill'][7:9], 16))
  1165. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1166. self.defaults['global_alt_sel_line'])
  1167. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1168. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1169. # Init Draw color and Selection Draw Color
  1170. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1171. self.defaults['global_draw_color'])
  1172. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1173. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1174. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1175. self.defaults['global_sel_draw_color'])
  1176. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1177. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1178. # Init Project Items color
  1179. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1180. self.defaults['global_proj_item_color'])
  1181. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1182. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1183. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1184. self.defaults['global_proj_item_dis_color'])
  1185. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1186. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1187. # Init the Annotation CNC Job color
  1188. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(
  1189. self.defaults['cncjob_annotation_fontcolor'])
  1190. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  1191. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1192. # ### End of Data ####
  1193. # ###############################################
  1194. # ############# SETUP Plot Area #################
  1195. # ###############################################
  1196. start_plot_time = time.time() # debug
  1197. self.plotcanvas = None
  1198. self.app_cursor = None
  1199. self.hover_shapes = None
  1200. self.on_plotcanvas_setup()
  1201. end_plot_time = time.time()
  1202. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1203. self.ui.splitter.setStretchFactor(1, 2)
  1204. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1205. # depending on from where those tools are called different actions can be done
  1206. self.call_source = 'app'
  1207. # ##############################################
  1208. # ######### SETUP OBJECT COLLECTION ############
  1209. # ##############################################
  1210. self.collection = ObjectCollection(self)
  1211. self.ui.project_tab_layout.addWidget(self.collection.view)
  1212. # ### Adjust tabs width ## ##
  1213. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1214. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1215. self.collection.view.setMinimumWidth(290)
  1216. self.log.debug("Finished creating Object Collection.")
  1217. # ###############################################
  1218. # ############# Worker SETUP ####################
  1219. # ###############################################
  1220. if self.defaults["global_worker_number"]:
  1221. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1222. else:
  1223. self.workers = WorkerStack(workers_number=2)
  1224. self.worker_task.connect(self.workers.add_task)
  1225. self.log.debug("Finished creating Workers crew.")
  1226. # ################################################
  1227. # ############### Signal handling ################
  1228. # ################################################
  1229. # ### Custom signals ###
  1230. self.inform.connect(self.info)
  1231. self.app_quit.connect(self.quit_application)
  1232. self.message.connect(self.message_dialog)
  1233. self.progress.connect(self.set_progress_bar)
  1234. self.object_created.connect(self.on_object_created)
  1235. self.object_changed.connect(self.on_object_changed)
  1236. self.object_plotted.connect(self.on_object_plotted)
  1237. self.plots_updated.connect(self.on_plots_updated)
  1238. self.file_opened.connect(self.register_recent)
  1239. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1240. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1241. # ### Standard signals
  1242. # ### Menu
  1243. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1244. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1245. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1246. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1247. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1248. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1249. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1250. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1251. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1252. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1253. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1254. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1255. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1256. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1257. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1258. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1259. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1260. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1261. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1262. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1263. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1264. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1265. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1266. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1267. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1268. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1269. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1270. self.ui.menufile_exit.triggered.connect(self.final_save)
  1271. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1272. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1273. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1274. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1275. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1276. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1277. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1278. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1279. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1280. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1281. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1282. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1283. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1284. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1285. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1286. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1287. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1288. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1289. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1290. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1291. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1292. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1293. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1294. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1295. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1296. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1297. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1298. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1299. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1300. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1301. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1302. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1303. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1304. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1305. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1306. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1307. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1308. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1309. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1310. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1311. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1312. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1313. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1314. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1315. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1316. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1317. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1318. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1319. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1320. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1321. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1322. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1323. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1324. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1325. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1326. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1327. # ToolBar signals
  1328. self.connect_toolbar_signals()
  1329. # Notebook signals
  1330. # make the right click on the notebook tab connect to a function
  1331. self.ui.notebook.setupContextMenu()
  1332. self.ui.notebook.addContextMenu(
  1333. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1334. initial_checked=self.defaults["global_tabs_detachable"])
  1335. # activate initial state
  1336. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1337. # Context Menu
  1338. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1339. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1340. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1341. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1342. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1343. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1344. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1345. self.ui.clearplot.triggered.connect(self.clear_plots)
  1346. self.ui.replot.triggered.connect(self.plot_all)
  1347. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1348. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1349. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1350. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1351. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1352. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1353. # Preferences Plot Area TAB
  1354. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1355. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1356. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1357. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1358. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1359. # ##############################
  1360. # ### GUI PREFERENCES SIGNALS ##
  1361. # ##############################
  1362. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1363. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1364. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1365. )
  1366. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1367. lambda: self.on_toggle_units(no_pref=False))
  1368. # ##############################
  1369. # ### GUI PREFERENCES SIGNALS ##
  1370. # ##############################
  1371. # Setting plot colors signals
  1372. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1373. self.on_pf_color_entry)
  1374. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1375. self.on_pf_color_button)
  1376. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1377. self.on_pf_color_spinner)
  1378. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1379. self.on_pf_color_slider)
  1380. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1381. self.on_pl_color_entry)
  1382. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1383. self.on_pl_color_button)
  1384. # Setting selection (left - right) colors signals
  1385. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1386. self.on_sf_color_entry)
  1387. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1388. self.on_sf_color_button)
  1389. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1390. self.on_sf_color_spinner)
  1391. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1392. self.on_sf_color_slider)
  1393. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1394. self.on_sl_color_entry)
  1395. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1396. self.on_sl_color_button)
  1397. # Setting selection (right - left) colors signals
  1398. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1399. self.on_alt_sf_color_entry)
  1400. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1401. self.on_alt_sf_color_button)
  1402. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1403. self.on_alt_sf_color_spinner)
  1404. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1405. self.on_alt_sf_color_slider)
  1406. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1407. self.on_alt_sl_color_entry)
  1408. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1409. self.on_alt_sl_color_button)
  1410. # Setting Editor Draw colors signals
  1411. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1412. self.on_draw_color_entry)
  1413. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1414. self.on_draw_color_button)
  1415. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1416. self.on_sel_draw_color_entry)
  1417. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1418. self.on_sel_draw_color_button)
  1419. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1420. self.on_proj_color_entry)
  1421. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1422. self.on_proj_color_button)
  1423. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1424. self.on_proj_color_dis_entry)
  1425. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1426. self.on_proj_color_dis_button)
  1427. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1428. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1429. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1430. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1431. self.on_cnc_custom_parameters)
  1432. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.editingFinished.connect(
  1433. self.on_annotation_fontcolor_entry)
  1434. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.clicked.connect(
  1435. self.on_annotation_fontcolor_button)
  1436. # Modify G-CODE Plot Area TAB
  1437. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1438. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1439. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1440. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1441. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1442. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1443. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1444. # portability changed
  1445. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1446. # Object list
  1447. self.collection.view.activated.connect(self.on_row_activated)
  1448. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1449. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1450. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1451. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1452. self.on_excellon_defaults_button)
  1453. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1454. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1455. self.on_excellon_options_button)
  1456. # when there are arguments at application startup this get launched
  1457. self.args_at_startup.connect(self.on_startup_args)
  1458. self.log.debug("Finished connecting Signals.")
  1459. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1460. self.tool_tab_locked = False
  1461. # decide if to show or hide the Notebook side of the screen at startup
  1462. if self.defaults["global_project_at_startup"] is True:
  1463. self.ui.splitter.setSizes([1, 1])
  1464. else:
  1465. self.ui.splitter.setSizes([0, 1])
  1466. # ###########################################
  1467. # ################# Other setups ############
  1468. # ###########################################
  1469. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1470. self.setup_obj_classes()
  1471. self.setup_recent_items()
  1472. self.setup_component_editor()
  1473. # ###########################################
  1474. # #######Auto-complete KEYWORDS #############
  1475. # ###########################################
  1476. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1477. 'aligndrill', 'bbox', 'bounding_box', 'clear',
  1478. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1479. 'export_gcode',
  1480. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1481. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1482. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1483. 'millholes', 'mirror', 'new', 'new_geometry', 'non_copper_regions', 'ncr',
  1484. 'offset', 'open_excellon', 'open_gcode',
  1485. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1486. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1487. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1488. ]
  1489. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1490. 'holes', 'grid', 'minoffset', 'gridoffset', 'axisoffset', 'dia', 'dist',
  1491. 'gridoffsetx', 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate',
  1492. 'feedrate_rapid', 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g',
  1493. 'outname', 'margin', 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed',
  1494. 'toolchange', 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble',
  1495. 'filename', 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads',
  1496. 'x', 'y', 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value',
  1497. 'angle_x', 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1498. ]
  1499. self.tcl_keywords = [
  1500. "after", "append", "apply", "array", "auto_execok", "auto_import", "auto_load", "auto_mkindex",
  1501. "auto_qualify", "auto_reset", "bgerror", "binary", "break", "case", "catch", "cd", "chan", "clock", "close",
  1502. "concat", "continue", "coroutine", "dict", "encoding", "eof", "error", "eval", "exec", "exit", "expr",
  1503. "fblocked", "fconfigure", "fcopy", "file", "fileevent", "flush", "for", "foreach", "format", "gets", "glob",
  1504. "global", "history", "if", "incr", "info", "interp", "join", "lappend", "lassign", "lindex", "linsert",
  1505. "list", "llength", "load", "lrange", "lrepeat", "lreplace", "lreverse", "lsearch", "lset", "lsort",
  1506. "mathfunc", "mathop", "memory", "my", "namespace", "next", "nextto", "open", "package", "parray", "pid",
  1507. "pkg_mkIndex", "platform", "proc", "puts", "pwd", "read", "refchan", "regexp", "regsub", "rename", "return",
  1508. "scan", "seek", "self", "set", "socket", "source", "split", "string", "subst", "switch", "tailcall",
  1509. "tcl_endOfWord", "tcl_findLibrary", "tcl_startOfNextWord", "tcl_startOfPreviousWord", "tcl_wordBreakAfter",
  1510. "tcl_wordBreakBefore", "tell", "throw", "time", "tm", "trace", "transchan", "try", "unknown", "unload",
  1511. "unset", "update", "uplevel", "upvar", "variable", "vwait", "while", "yield", "yieldto", "zlib",
  1512. "attemptckalloc", "attemptckrealloc", "ckalloc", "ckfree", "ckrealloc", "Tcl_Access", "Tcl_AddErrorInfo",
  1513. "Tcl_AddObjErrorInfo", "Tcl_AlertNotifier", "Tcl_Alloc", "Tcl_AllocStatBuf", "Tcl_AllowExceptions",
  1514. "Tcl_AppendAllObjTypes", "Tcl_AppendElement", "Tcl_AppendExportList", "Tcl_AppendFormatToObj",
  1515. "Tcl_AppendLimitedToObj", "Tcl_AppendObjToErrorInfo", "Tcl_AppendObjToObj", "Tcl_AppendPrintfToObj",
  1516. "Tcl_AppendResult", "Tcl_AppendResultVA", "Tcl_AppendStringsToObj", "Tcl_AppendStringsToObjVA",
  1517. "Tcl_AppendToObj", "Tcl_AppendUnicodeToObj", "Tcl_AppInit", "Tcl_AsyncCreate", "Tcl_AsyncDelete",
  1518. "Tcl_AsyncInvoke", "Tcl_AsyncMark", "Tcl_AsyncReady", "Tcl_AttemptAlloc", "Tcl_AttemptRealloc",
  1519. "Tcl_AttemptSetObjLength", "Tcl_BackgroundError", "Tcl_BackgroundException", "Tcl_Backslash",
  1520. "Tcl_BadChannelOption", "Tcl_CallWhenDeleted", "Tcl_Canceled", "Tcl_CancelEval", "Tcl_CancelIdleCall",
  1521. "Tcl_ChannelBlockModeProc", "Tcl_ChannelBuffered", "Tcl_ChannelClose2Proc", "Tcl_ChannelCloseProc",
  1522. "Tcl_ChannelFlushProc", "Tcl_ChannelGetHandleProc", "Tcl_ChannelGetOptionProc", "Tcl_ChannelHandlerProc",
  1523. "Tcl_ChannelInputProc", "Tcl_ChannelName", "Tcl_ChannelOutputProc", "Tcl_ChannelSeekProc",
  1524. "Tcl_ChannelSetOptionProc", "Tcl_ChannelThreadActionProc", "Tcl_ChannelTruncateProc", "Tcl_ChannelVersion",
  1525. "Tcl_ChannelWatchProc", "Tcl_ChannelWideSeekProc", "Tcl_Chdir", "Tcl_ClassGetMetadata",
  1526. "Tcl_ClassSetConstructor", "Tcl_ClassSetDestructor", "Tcl_ClassSetMetadata", "Tcl_ClearChannelHandlers",
  1527. "Tcl_Close", "Tcl_CommandComplete", "Tcl_CommandTraceInfo", "Tcl_Concat", "Tcl_ConcatObj",
  1528. "Tcl_ConditionFinalize", "Tcl_ConditionNotify", "Tcl_ConditionWait", "Tcl_ConvertCountedElement",
  1529. "Tcl_ConvertElement", "Tcl_ConvertToType", "Tcl_CopyObjectInstance", "Tcl_CreateAlias",
  1530. "Tcl_CreateAliasObj", "Tcl_CreateChannel", "Tcl_CreateChannelHandler", "Tcl_CreateCloseHandler",
  1531. "Tcl_CreateCommand", "Tcl_CreateEncoding", "Tcl_CreateEnsemble", "Tcl_CreateEventSource",
  1532. "Tcl_CreateExitHandler", "Tcl_CreateFileHandler", "Tcl_CreateHashEntry", "Tcl_CreateInterp",
  1533. "Tcl_CreateMathFunc", "Tcl_CreateNamespace", "Tcl_CreateObjCommand", "Tcl_CreateObjTrace",
  1534. "Tcl_CreateSlave", "Tcl_CreateThread", "Tcl_CreateThreadExitHandler", "Tcl_CreateTimerHandler",
  1535. "Tcl_CreateTrace", "Tcl_CutChannel", "Tcl_DecrRefCount", "Tcl_DeleteAssocData", "Tcl_DeleteChannelHandler",
  1536. "Tcl_DeleteCloseHandler", "Tcl_DeleteCommand", "Tcl_DeleteCommandFromToken", "Tcl_DeleteEvents",
  1537. "Tcl_DeleteEventSource", "Tcl_DeleteExitHandler", "Tcl_DeleteFileHandler", "Tcl_DeleteHashEntry",
  1538. "Tcl_DeleteHashTable", "Tcl_DeleteInterp", "Tcl_DeleteNamespace", "Tcl_DeleteThreadExitHandler",
  1539. "Tcl_DeleteTimerHandler", "Tcl_DeleteTrace", "Tcl_DetachChannel", "Tcl_DetachPids", "Tcl_DictObjDone",
  1540. "Tcl_DictObjFirst", "Tcl_DictObjGet", "Tcl_DictObjNext", "Tcl_DictObjPut", "Tcl_DictObjPutKeyList",
  1541. "Tcl_DictObjRemove", "Tcl_DictObjRemoveKeyList", "Tcl_DictObjSize", "Tcl_DiscardInterpState",
  1542. "Tcl_DiscardResult", "Tcl_DontCallWhenDeleted", "Tcl_DoOneEvent", "Tcl_DoWhenIdle", "Tcl_DStringAppend",
  1543. "Tcl_DStringAppendElement", "Tcl_DStringEndSublist", "Tcl_DStringFree", "Tcl_DStringGetResult",
  1544. "Tcl_DStringInit", "Tcl_DStringLength", "Tcl_DStringResult", "Tcl_DStringSetLength",
  1545. "Tcl_DStringStartSublist", "Tcl_DStringTrunc", "Tcl_DStringValue", "Tcl_DumpActiveMemory",
  1546. "Tcl_DuplicateObj", "Tcl_Eof", "Tcl_ErrnoId", "Tcl_ErrnoMsg", "Tcl_Eval", "Tcl_EvalEx", "Tcl_EvalFile",
  1547. "Tcl_EvalObjEx", "Tcl_EvalObjv", "Tcl_EvalTokens", "Tcl_EvalTokensStandard", "Tcl_EventuallyFree",
  1548. "Tcl_Exit", "Tcl_ExitThread", "Tcl_Export", "Tcl_ExposeCommand", "Tcl_ExprBoolean", "Tcl_ExprBooleanObj",
  1549. "Tcl_ExprDouble", "Tcl_ExprDoubleObj", "Tcl_ExprLong", "Tcl_ExprLongObj", "Tcl_ExprObj", "Tcl_ExprString",
  1550. "Tcl_ExternalToUtf", "Tcl_ExternalToUtfDString", "Tcl_Finalize", "Tcl_FinalizeNotifier",
  1551. "Tcl_FinalizeThread", "Tcl_FindCommand", "Tcl_FindEnsemble", "Tcl_FindExecutable", "Tcl_FindHashEntry",
  1552. "Tcl_FindNamespace", "Tcl_FirstHashEntry", "Tcl_Flush", "Tcl_ForgetImport", "Tcl_Format",
  1553. "Tcl_Free· Tcl_FreeEncoding", "Tcl_FreeParse", "Tcl_FreeResult", "Tcl_FSAccess", "Tcl_FSChdir",
  1554. "Tcl_FSConvertToPathType", "Tcl_FSCopyDirectory", "Tcl_FSCopyFile", "Tcl_FSCreateDirectory", "Tcl_FSData",
  1555. "Tcl_FSDeleteFile", "Tcl_FSEqualPaths", "Tcl_FSEvalFile", "Tcl_FSEvalFileEx", "Tcl_FSFileAttrsGet",
  1556. "Tcl_FSFileAttrsSet", "Tcl_FSFileAttrStrings", "Tcl_FSFileSystemInfo", "Tcl_FSGetCwd",
  1557. "Tcl_FSGetFileSystemForPath", "Tcl_FSGetInternalRep", "Tcl_FSGetNativePath", "Tcl_FSGetNormalizedPath",
  1558. "Tcl_FSGetPathType", "Tcl_FSGetTranslatedPath", "Tcl_FSGetTranslatedStringPath", "Tcl_FSJoinPath",
  1559. "Tcl_FSJoinToPath", "Tcl_FSLink· Tcl_FSListVolumes", "Tcl_FSLoadFile", "Tcl_FSLstat",
  1560. "Tcl_FSMatchInDirectory", "Tcl_FSMountsChanged", "Tcl_FSNewNativePath", "Tcl_FSOpenFileChannel",
  1561. "Tcl_FSPathSeparator", "Tcl_FSRegister", "Tcl_FSRemoveDirectory", "Tcl_FSRenameFile", "Tcl_FSSplitPath",
  1562. "Tcl_FSStat", "Tcl_FSUnloadFile", "Tcl_FSUnregister", "Tcl_FSUtime", "Tcl_GetAccessTimeFromStat",
  1563. "Tcl_GetAlias", "Tcl_GetAliasObj", "Tcl_GetAssocData", "Tcl_GetBignumFromObj", "Tcl_GetBlocksFromStat",
  1564. "Tcl_GetBlockSizeFromStat", "Tcl_GetBoolean", "Tcl_GetBooleanFromObj", "Tcl_GetByteArrayFromObj",
  1565. "Tcl_GetChangeTimeFromStat", "Tcl_GetChannel", "Tcl_GetChannelBufferSize", "Tcl_GetChannelError",
  1566. "Tcl_GetChannelErrorInterp", "Tcl_GetChannelHandle", "Tcl_GetChannelInstanceData", "Tcl_GetChannelMode",
  1567. "Tcl_GetChannelName", "Tcl_GetChannelNames", "Tcl_GetChannelNamesEx", "Tcl_GetChannelOption",
  1568. "Tcl_GetChannelThread", "Tcl_GetChannelType", "Tcl_GetCharLength", "Tcl_GetClassAsObject",
  1569. "Tcl_GetCommandFromObj", "Tcl_GetCommandFullName", "Tcl_GetCommandInfo", "Tcl_GetCommandInfoFromToken",
  1570. "Tcl_GetCommandName", "Tcl_GetCurrentNamespace", "Tcl_GetCurrentThread", "Tcl_GetCwd",
  1571. "Tcl_GetDefaultEncodingDir", "Tcl_GetDeviceTypeFromStat", "Tcl_GetDouble", "Tcl_GetDoubleFromObj",
  1572. "Tcl_GetEncoding", "Tcl_GetEncodingFromObj", "Tcl_GetEncodingName", "Tcl_GetEncodingNameFromEnvironment",
  1573. "Tcl_GetEncodingNames", "Tcl_GetEncodingSearchPath", "Tcl_GetEnsembleFlags", "Tcl_GetEnsembleMappingDict",
  1574. "Tcl_GetEnsembleNamespace", "Tcl_GetEnsembleParameterList", "Tcl_GetEnsembleSubcommandList",
  1575. "Tcl_GetEnsembleUnknownHandler", "Tcl_GetErrno", "Tcl_GetErrorLine", "Tcl_GetFSDeviceFromStat",
  1576. "Tcl_GetFSInodeFromStat", "Tcl_GetGlobalNamespace", "Tcl_GetGroupIdFromStat", "Tcl_GetHashKey",
  1577. "Tcl_GetHashValue", "Tcl_GetHostName", "Tcl_GetIndexFromObj", "Tcl_GetIndexFromObjStruct", "Tcl_GetInt",
  1578. "Tcl_GetInterpPath", "Tcl_GetIntFromObj", "Tcl_GetLinkCountFromStat", "Tcl_GetLongFromObj", "Tcl_GetMaster",
  1579. "Tcl_GetMathFuncInfo", "Tcl_GetModeFromStat", "Tcl_GetModificationTimeFromStat", "Tcl_GetNameOfExecutable",
  1580. "Tcl_GetNamespaceUnknownHandler", "Tcl_GetObjectAsClass", "Tcl_GetObjectCommand", "Tcl_GetObjectFromObj",
  1581. "Tcl_GetObjectName", "Tcl_GetObjectNamespace", "Tcl_GetObjResult", "Tcl_GetObjType", "Tcl_GetOpenFile",
  1582. "Tcl_GetPathType", "Tcl_GetRange", "Tcl_GetRegExpFromObj", "Tcl_GetReturnOptions", "Tcl_Gets",
  1583. "Tcl_GetServiceMode", "Tcl_GetSizeFromStat", "Tcl_GetSlave", "Tcl_GetsObj", "Tcl_GetStackedChannel",
  1584. "Tcl_GetStartupScript", "Tcl_GetStdChannel", "Tcl_GetString", "Tcl_GetStringFromObj", "Tcl_GetStringResult",
  1585. "Tcl_GetThreadData", "Tcl_GetTime", "Tcl_GetTopChannel", "Tcl_GetUniChar", "Tcl_GetUnicode",
  1586. "Tcl_GetUnicodeFromObj", "Tcl_GetUserIdFromStat", "Tcl_GetVar", "Tcl_GetVar2", "Tcl_GetVar2Ex",
  1587. "Tcl_GetVersion", "Tcl_GetWideIntFromObj", "Tcl_GlobalEval", "Tcl_GlobalEvalObj", "Tcl_HashStats",
  1588. "Tcl_HideCommand", "Tcl_Import", "Tcl_IncrRefCount", "Tcl_Init", "Tcl_InitCustomHashTable",
  1589. "Tcl_InitHashTable", "Tcl_InitMemory", "Tcl_InitNotifier", "Tcl_InitObjHashTable", "Tcl_InitStubs",
  1590. "Tcl_InputBlocked", "Tcl_InputBuffered", "Tcl_InterpActive", "Tcl_InterpDeleted", "Tcl_InvalidateStringRep",
  1591. "Tcl_IsChannelExisting", "Tcl_IsChannelRegistered", "Tcl_IsChannelShared", "Tcl_IsEnsemble", "Tcl_IsSafe",
  1592. "Tcl_IsShared", "Tcl_IsStandardChannel", "Tcl_JoinPath", "Tcl_JoinThread", "Tcl_LimitAddHandler",
  1593. "Tcl_LimitCheck", "Tcl_LimitExceeded", "Tcl_LimitGetCommands", "Tcl_LimitGetGranularity",
  1594. "Tcl_LimitGetTime", "Tcl_LimitReady", "Tcl_LimitRemoveHandler", "Tcl_LimitSetCommands",
  1595. "Tcl_LimitSetGranularity", "Tcl_LimitSetTime", "Tcl_LimitTypeEnabled", "Tcl_LimitTypeExceeded",
  1596. "Tcl_LimitTypeReset", "Tcl_LimitTypeSet", "Tcl_LinkVar", "Tcl_ListMathFuncs", "Tcl_ListObjAppendElement",
  1597. "Tcl_ListObjAppendList", "Tcl_ListObjGetElements", "Tcl_ListObjIndex", "Tcl_ListObjLength",
  1598. "Tcl_ListObjReplace", "Tcl_LogCommandInfo", "Tcl_Main", "Tcl_MakeFileChannel", "Tcl_MakeSafe",
  1599. "Tcl_MakeTcpClientChannel", "Tcl_Merge", "Tcl_MethodDeclarerClass", "Tcl_MethodDeclarerObject",
  1600. "Tcl_MethodIsPublic", "Tcl_MethodIsType", "Tcl_MethodName", "Tcl_MutexFinalize", "Tcl_MutexLock",
  1601. "Tcl_MutexUnlock", "Tcl_NewBignumObj", "Tcl_NewBooleanObj", "Tcl_NewByteArrayObj", "Tcl_NewDictObj",
  1602. "Tcl_NewDoubleObj", "Tcl_NewInstanceMethod", "Tcl_NewIntObj", "Tcl_NewListObj", "Tcl_NewLongObj",
  1603. "Tcl_NewMethod", "Tcl_NewObj", "Tcl_NewObjectInstance", "Tcl_NewStringObj", "Tcl_NewUnicodeObj",
  1604. "Tcl_NewWideIntObj", "Tcl_NextHashEntry", "Tcl_NotifyChannel", "Tcl_NRAddCallback", "Tcl_NRCallObjProc",
  1605. "Tcl_NRCmdSwap", "Tcl_NRCreateCommand", "Tcl_NREvalObj", "Tcl_NREvalObjv", "Tcl_NumUtfChars",
  1606. "Tcl_ObjectContextInvokeNext", "Tcl_ObjectContextIsFiltering", "Tcl_ObjectContextMethod",
  1607. "Tcl_ObjectContextObject", "Tcl_ObjectContextSkippedArgs", "Tcl_ObjectDeleted", "Tcl_ObjectGetMetadata",
  1608. "Tcl_ObjectGetMethodNameMapper", "Tcl_ObjectSetMetadata", "Tcl_ObjectSetMethodNameMapper", "Tcl_ObjGetVar2",
  1609. "Tcl_ObjPrintf", "Tcl_ObjSetVar2", "Tcl_OpenCommandChannel", "Tcl_OpenFileChannel", "Tcl_OpenTcpClient",
  1610. "Tcl_OpenTcpServer", "Tcl_OutputBuffered", "Tcl_Panic", "Tcl_PanicVA", "Tcl_ParseArgsObjv",
  1611. "Tcl_ParseBraces", "Tcl_ParseCommand", "Tcl_ParseExpr", "Tcl_ParseQuotedString", "Tcl_ParseVar",
  1612. "Tcl_ParseVarName", "Tcl_PkgPresent", "Tcl_PkgPresentEx", "Tcl_PkgProvide", "Tcl_PkgProvideEx",
  1613. "Tcl_PkgRequire", "Tcl_PkgRequireEx", "Tcl_PkgRequireProc", "Tcl_PosixError", "Tcl_Preserve",
  1614. "Tcl_PrintDouble", "Tcl_PutEnv", "Tcl_QueryTimeProc", "Tcl_QueueEvent", "Tcl_Read", "Tcl_ReadChars",
  1615. "Tcl_ReadRaw", "Tcl_Realloc", "Tcl_ReapDetachedProcs", "Tcl_RecordAndEval", "Tcl_RecordAndEvalObj",
  1616. "Tcl_RegExpCompile", "Tcl_RegExpExec", "Tcl_RegExpExecObj", "Tcl_RegExpGetInfo", "Tcl_RegExpMatch",
  1617. "Tcl_RegExpMatchObj", "Tcl_RegExpRange", "Tcl_RegisterChannel", "Tcl_RegisterConfig", "Tcl_RegisterObjType",
  1618. "Tcl_Release", "Tcl_ResetResult", "Tcl_RestoreInterpState", "Tcl_RestoreResult", "Tcl_SaveInterpState",
  1619. "Tcl_SaveResult", "Tcl_ScanCountedElement", "Tcl_ScanElement", "Tcl_Seek", "Tcl_ServiceAll",
  1620. "Tcl_ServiceEvent", "Tcl_ServiceModeHook", "Tcl_SetAssocData", "Tcl_SetBignumObj", "Tcl_SetBooleanObj",
  1621. "Tcl_SetByteArrayLength", "Tcl_SetByteArrayObj", "Tcl_SetChannelBufferSize", "Tcl_SetChannelError",
  1622. "Tcl_SetChannelErrorInterp", "Tcl_SetChannelOption", "Tcl_SetCommandInfo", "Tcl_SetCommandInfoFromToken",
  1623. "Tcl_SetDefaultEncodingDir", "Tcl_SetDoubleObj", "Tcl_SetEncodingSearchPath", "Tcl_SetEnsembleFlags",
  1624. "Tcl_SetEnsembleMappingDict", "Tcl_SetEnsembleParameterList", "Tcl_SetEnsembleSubcommandList",
  1625. "Tcl_SetEnsembleUnknownHandler", "Tcl_SetErrno", "Tcl_SetErrorCode", "Tcl_SetErrorCodeVA",
  1626. "Tcl_SetErrorLine", "Tcl_SetExitProc", "Tcl_SetHashValue", "Tcl_SetIntObj", "Tcl_SetListObj",
  1627. "Tcl_SetLongObj", "Tcl_SetMainLoop", "Tcl_SetMaxBlockTime", "Tcl_SetNamespaceUnknownHandler",
  1628. "Tcl_SetNotifier", "Tcl_SetObjErrorCode", "Tcl_SetObjLength", "Tcl_SetObjResult", "Tcl_SetPanicProc",
  1629. "Tcl_SetRecursionLimit", "Tcl_SetResult", "Tcl_SetReturnOptions", "Tcl_SetServiceMode",
  1630. "Tcl_SetStartupScript", "Tcl_SetStdChannel", "Tcl_SetStringObj", "Tcl_SetSystemEncoding", "Tcl_SetTimeProc",
  1631. "Tcl_SetTimer", "Tcl_SetUnicodeObj", "Tcl_SetVar", "Tcl_SetVar2", "Tcl_SetVar2Ex", "Tcl_SetWideIntObj",
  1632. "Tcl_SignalId", "Tcl_SignalMsg", "Tcl_Sleep", "Tcl_SourceRCFile", "Tcl_SpliceChannel", "Tcl_SplitList",
  1633. "Tcl_SplitPath", "Tcl_StackChannel", "Tcl_StandardChannels", "Tcl_Stat", "Tcl_StaticPackage",
  1634. "Tcl_StringCaseMatch", "Tcl_StringMatch", "Tcl_SubstObj", "Tcl_TakeBignumFromObj", "Tcl_Tell",
  1635. "Tcl_ThreadAlert", "Tcl_ThreadQueueEvent", "Tcl_TraceCommand", "Tcl_TraceVar", "Tcl_TraceVar2",
  1636. "Tcl_TransferResult", "Tcl_TranslateFileName", "Tcl_TruncateChannel", "Tcl_Ungets", "Tcl_UniChar",
  1637. "Tcl_UniCharAtIndex", "Tcl_UniCharCaseMatch", "Tcl_UniCharIsAlnum", "Tcl_UniCharIsAlpha",
  1638. "Tcl_UniCharIsControl", "Tcl_UniCharIsDigit", "Tcl_UniCharIsGraph", "Tcl_UniCharIsLower",
  1639. "Tcl_UniCharIsPrint", "Tcl_UniCharIsPunct", "Tcl_UniCharIsSpace", "Tcl_UniCharIsUpper",
  1640. "Tcl_UniCharIsWordChar", "Tcl_UniCharLen", "Tcl_UniCharNcasecmp", "Tcl_UniCharNcmp", "Tcl_UniCharToLower",
  1641. "Tcl_UniCharToTitle", "Tcl_UniCharToUpper", "Tcl_UniCharToUtf", "Tcl_UniCharToUtfDString", "Tcl_UnlinkVar",
  1642. "Tcl_UnregisterChannel", "Tcl_UnsetVar", "Tcl_UnsetVar2", "Tcl_UnstackChannel", "Tcl_UntraceCommand",
  1643. "Tcl_UntraceVar", "Tcl_UntraceVar2", "Tcl_UpdateLinkedVar", "Tcl_UpVar", "Tcl_UpVar2", "Tcl_UtfAtIndex",
  1644. "Tcl_UtfBackslash", "Tcl_UtfCharComplete", "Tcl_UtfFindFirst", "Tcl_UtfFindLast", "Tcl_UtfNext",
  1645. "Tcl_UtfPrev", "Tcl_UtfToExternal", "Tcl_UtfToExternalDString", "Tcl_UtfToLower", "Tcl_UtfToTitle",
  1646. "Tcl_UtfToUniChar", "Tcl_UtfToUniCharDString", "Tcl_UtfToUpper", "Tcl_ValidateAllMemory", "Tcl_VarEval",
  1647. "Tcl_VarEvalVA", "Tcl_VarTraceInfo", "Tcl_VarTraceInfo2", "Tcl_WaitForEvent", "Tcl_WaitPid",
  1648. "Tcl_WinTCharToUtf", "Tcl_WinUtfToTChar", "Tcl_Write", "Tcl_WriteChars", "Tcl_WriteObj", "Tcl_WriteRaw",
  1649. "Tcl_WrongNumArgs", "Tcl_ZlibAdler32", "Tcl_ZlibCRC32", "Tcl_ZlibDeflate", "Tcl_ZlibInflate",
  1650. "Tcl_ZlibStreamChecksum", "Tcl_ZlibStreamClose", "Tcl_ZlibStreamEof", "Tcl_ZlibStreamGet",
  1651. "Tcl_ZlibStreamGetCommandName", "Tcl_ZlibStreamInit", "Tcl_ZlibStreamPut", "dde", "http", "msgcat",
  1652. "registry", "tcltest", "Tcl_AllocHashEntryProc", "Tcl_AppInitProc", "Tcl_ArgvInfo", "Tcl_AsyncProc",
  1653. "Tcl_ChannelProc", "Tcl_ChannelType", "Tcl_CloneProc", "Tcl_CloseProc", "Tcl_CmdDeleteProc", "Tcl_CmdInfo",
  1654. "Tcl_CmdObjTraceDeleteProc", "Tcl_CmdObjTraceProc", "Tcl_CmdProc", "Tcl_CmdTraceProc",
  1655. "Tcl_CommandTraceProc", "Tcl_CompareHashKeysProc", "Tcl_Config", "Tcl_DriverBlockModeProc",
  1656. "Tcl_DriverClose2Proc", "Tcl_DriverCloseProc", "Tcl_DriverFlushProc", "Tcl_DriverGetHandleProc",
  1657. "Tcl_DriverGetOptionProc", "Tcl_DriverHandlerProc", "Tcl_DriverInputProc", "Tcl_DriverOutputProc",
  1658. "Tcl_DriverSeekProc", "Tcl_DriverSetOptionProc", "Tcl_DriverThreadActionProc", "Tcl_DriverTruncateProc",
  1659. "Tcl_DriverWatchProc", "Tcl_DriverWideSeekProc", "Tcl_DupInternalRepProc", "Tcl_EncodingConvertProc",
  1660. "Tcl_EncodingFreeProc", "Tcl_EncodingType", "Tcl_Event", "Tcl_EventCheckProc", "Tcl_EventDeleteProc",
  1661. "Tcl_EventProc", "Tcl_EventSetupProc", "Tcl_ExitProc", "Tcl_FileProc", "Tcl_Filesystem",
  1662. "Tcl_FreeHashEntryProc", "Tcl_FreeInternalRepProc", "Tcl_FreeProc", "Tcl_FSAccessProc", "Tcl_FSChdirProc",
  1663. "Tcl_FSCopyDirectoryProc", "Tcl_FSCopyFileProc", "Tcl_FSCreateDirectoryProc", "Tcl_FSCreateInternalRepProc",
  1664. "Tcl_FSDeleteFileProc", "Tcl_FSDupInternalRepProc", "Tcl_FSFileAttrsGetProc", "Tcl_FSFileAttrsSetProc",
  1665. "Tcl_FSFilesystemPathTypeProc", "Tcl_FSFilesystemSeparatorProc", "Tcl_FSFreeInternalRepProc",
  1666. "Tcl_FSGetCwdProc", "Tcl_FSInternalToNormalizedProc", "Tcl_FSLinkProc", "Tcl_FSListVolumesProc",
  1667. "Tcl_FSLoadFileProc", "Tcl_FSLstatProc", "Tcl_FSMatchInDirectoryProc", "Tcl_FSNormalizePathProc",
  1668. "Tcl_FSOpenFileChannelProc", "Tcl_FSPathInFilesystemProc", "Tcl_FSRemoveDirectoryProc",
  1669. "Tcl_FSRenameFileProc", "Tcl_FSStatProc", "Tcl_FSUnloadFileProc", "Tcl_FSUtimeProc", "Tcl_GlobTypeData",
  1670. "Tcl_HashKeyType", "Tcl_IdleProc", "Tcl_Interp", "Tcl_InterpDeleteProc", "Tcl_LimitHandlerDeleteProc",
  1671. "Tcl_LimitHandlerProc", "Tcl_MainLoopProc", "Tcl_MathProc", "Tcl_MethodCallProc", "Tcl_MethodDeleteProc",
  1672. "Tcl_MethodType", "Tcl_NamespaceDeleteProc", "Tcl_NotifierProcs", "Tcl_Obj", "Tcl_ObjCmdProc",
  1673. "Tcl_ObjectMapMethodNameProc", "Tcl_ObjectMetadataDeleteProc", "Tcl_ObjType", "Tcl_PackageInitProc",
  1674. "Tcl_PackageUnloadProc", "Tcl_PanicProc", "Tcl_RegExpIndices", "Tcl_RegExpInfo", "Tcl_ScaleTimeProc",
  1675. "Tcl_SetFromAnyProc", "Tcl_TcpAcceptProc", "Tcl_Time", "Tcl_TimerProc", "Tcl_Token", "Tcl_UpdateStringProc",
  1676. "Tcl_Value", "Tcl_VarTraceProc", "argc", "argv", "argv0", "auto_path", "env", "errorCode", "errorInfo",
  1677. "filename", "re_syntax", "safe", "Tcl", "tcl_interactive", "tcl_library", "TCL_MEM_DEBUG",
  1678. "tcl_nonwordchars", "tcl_patchLevel", "tcl_pkgPath", "tcl_platform", "tcl_precision", "tcl_rcFileName",
  1679. "tcl_traceCompile", "tcl_traceEval", "tcl_version", "tcl_wordchars"
  1680. ]
  1681. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1682. # ###########################################
  1683. # ########### Shell SETUP ###################
  1684. # ###########################################
  1685. self.shell = FCShell(self, version=self.version)
  1686. self.shell._edit.set_model_data(self.myKeywords)
  1687. self.ui.code_editor.set_model_data(self.myKeywords)
  1688. self.shell.setWindowIcon(self.ui.app_icon)
  1689. self.shell.setWindowTitle("FlatCAM Shell")
  1690. self.shell.resize(*self.defaults["global_shell_shape"])
  1691. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1692. self.shell.append_output(_("(Type help to get started)\n\n"))
  1693. self.init_tcl()
  1694. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1695. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1696. self.ui.shell_dock.setWidget(self.shell)
  1697. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1698. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1699. QtWidgets.QDockWidget.DockWidgetFloatable |
  1700. QtWidgets.QDockWidget.DockWidgetClosable)
  1701. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1702. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1703. if self.defaults["global_shell_at_startup"]:
  1704. self.ui.shell_dock.show()
  1705. else:
  1706. self.ui.shell_dock.hide()
  1707. # ###########################################
  1708. # ######### Tools and Plugins ###############
  1709. # ###########################################
  1710. self.dblsidedtool = None
  1711. self.measurement_tool = None
  1712. self.panelize_tool = None
  1713. self.film_tool = None
  1714. self.paste_tool = None
  1715. self.calculator_tool = None
  1716. self.sub_tool = None
  1717. self.move_tool = None
  1718. self.cutout_tool = None
  1719. self.ncclear_tool = None
  1720. self.paint_tool = None
  1721. self.transform_tool = None
  1722. self.properties_tool = None
  1723. self.pdf_tool = None
  1724. self.image_tool = None
  1725. self.pcb_wizard_tool = None
  1726. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1727. self.install_tools()
  1728. # ### System Font Parsing ###
  1729. # self.f_parse = ParseFont(self)
  1730. # self.parse_system_fonts()
  1731. # ###############################################
  1732. # ######## START-UP ARGUMENTS ###################
  1733. # ###############################################
  1734. # test if the program was started with a script as parameter
  1735. if self.cmd_line_shellfile:
  1736. try:
  1737. with open(self.cmd_line_shellfile, "r") as myfile:
  1738. cmd_line_shellfile_text = myfile.read()
  1739. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1740. except Exception as ext:
  1741. print("ERROR: ", ext)
  1742. sys.exit(2)
  1743. # ###############################################
  1744. # ############# Check for updates ###############
  1745. # ###############################################
  1746. # Separate thread (Not worker)
  1747. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1748. if (self.beta is False or self.beta is None) and \
  1749. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1750. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1751. self.thr2 = QtCore.QThread()
  1752. self.worker_task.emit({'fcn': self.version_check,
  1753. 'params': []})
  1754. self.thr2.start(QtCore.QThread.LowPriority)
  1755. # ################################################
  1756. # ######### Variables for global usage ###########
  1757. # ################################################
  1758. # coordinates for relative position display
  1759. self.rel_point1 = (0, 0)
  1760. self.rel_point2 = (0, 0)
  1761. # variable to store coordinates
  1762. self.pos = (0, 0)
  1763. self.pos_jump = (0, 0)
  1764. # decide if we have a double click or single click
  1765. self.doubleclick = False
  1766. # variable to store if a command is active (then the var is not None) and which one it is
  1767. self.command_active = None
  1768. # variable to store the status of moving selection action
  1769. # None value means that it's not an selection action
  1770. # True value = a selection from left to right
  1771. # False value = a selection from right to left
  1772. self.selection_type = None
  1773. # List to store the objects that are currently loaded in FlatCAM
  1774. # This list is updated on each object creation or object delete
  1775. self.all_objects_list = []
  1776. # List to store the objects that are selected
  1777. self.sel_objects_list = []
  1778. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1779. self.key_modifiers = None
  1780. # Variable to hold the status of the axis
  1781. self.toggle_axis = True
  1782. # Variable to store the status of the fullscreen event
  1783. self.toggle_fscreen = False
  1784. # Variable to store the status of the code editor
  1785. self.toggle_codeeditor = False
  1786. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1787. self.click_noproject = False
  1788. self.cursor = None
  1789. # Variable to store the GCODE that was edited
  1790. self.gcode_edited = ""
  1791. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1792. self.preferences_changed_flag = False
  1793. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1794. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1795. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1796. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1797. ]
  1798. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1799. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1800. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1801. 'mpf'
  1802. ]
  1803. self.svg_list = ['svg']
  1804. self.dxf_list = ['dxf']
  1805. self.pdf_list = ['pdf']
  1806. self.prj_list = ['flatprj']
  1807. self.conf_list = ['flatconfig']
  1808. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1809. # flag for polygons not cleared
  1810. self.poly_not_cleared = False
  1811. # VisPy visuals
  1812. self.isHovering = False
  1813. self.notHovering = True
  1814. # #########################################################
  1815. # ### Save defaults to factory_defaults.FlatConfig file ###
  1816. # ### It's done only once after install ###################
  1817. # #########################################################
  1818. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1819. fac_def_from_file = factory_file.read()
  1820. factory_defaults = json.loads(fac_def_from_file)
  1821. # if the file contain an empty dictionary then save the factory defaults into the file
  1822. if not factory_defaults:
  1823. self.save_factory_defaults(silent=False)
  1824. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1825. initial_lay = 'compact'
  1826. self.on_layout(lay=initial_lay)
  1827. # Set the combobox in Preferences to the current layout
  1828. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1829. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1830. factory_file.close()
  1831. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1832. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1833. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1834. ####################################################
  1835. # ### ADDING FlatCAM EDITORS section ###############
  1836. ####################################################
  1837. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1838. # at the first launch of the App , the editors will not be functional.
  1839. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1840. self.exc_editor = FlatCAMExcEditor(self)
  1841. self.grb_editor = FlatCAMGrbEditor(self)
  1842. self.log.debug("Finished adding FlatCAM Editor's.")
  1843. # Post-GUI initialization: Experimental attempt
  1844. # to perform unit tests on the GUI.
  1845. # if post_gui is not None:
  1846. # post_gui(self)
  1847. App.log.debug("END of constructor. Releasing control.")
  1848. self.set_ui_title(name=_("New Project - Not saved"))
  1849. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1850. # the path/file_name must be enclosed in quotes if it contain spaces
  1851. if App.args:
  1852. self.args_at_startup.emit()
  1853. @staticmethod
  1854. def copy_and_overwrite(from_path, to_path):
  1855. """
  1856. From here:
  1857. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1858. :param from_path: source path
  1859. :param to_path: destination path
  1860. :return: None
  1861. """
  1862. if os.path.exists(to_path):
  1863. shutil.rmtree(to_path)
  1864. try:
  1865. shutil.copytree(from_path, to_path)
  1866. except FileNotFoundError:
  1867. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1868. shutil.copytree(from_new_path, to_path)
  1869. def on_startup_args(self):
  1870. log.debug("Application was started with an argument. Processing ...")
  1871. for argument in App.args:
  1872. if '.FlatPrj' in argument:
  1873. try:
  1874. project_name = str(argument)
  1875. if project_name == "":
  1876. self.inform.emit(_("Open cancelled."))
  1877. else:
  1878. # self.open_project(project_name)
  1879. run_from_arg = True
  1880. # self.worker_task.emit({'fcn': self.open_project,
  1881. # 'params': [project_name, run_from_arg]})
  1882. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1883. except Exception as e:
  1884. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1885. elif '.FlatConfig' in argument:
  1886. try:
  1887. file_name = str(argument)
  1888. if file_name == "":
  1889. self.inform.emit(_("Open Config file failed."))
  1890. else:
  1891. # run_from_arg = True
  1892. # self.worker_task.emit({'fcn': self.open_config_file,
  1893. # 'params': [file_name, run_from_arg]})
  1894. self.open_config_file(file_name, run_from_arg=True)
  1895. except Exception as e:
  1896. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1897. elif '.FlatScript' in argument:
  1898. try:
  1899. file_name = str(argument)
  1900. if file_name == "":
  1901. self.inform.emit(_("Open Script file failed."))
  1902. else:
  1903. # run_from_arg = True
  1904. # self.worker_task.emit({'fcn': self.open_script_file,
  1905. # 'params': [file_name, run_from_arg]})
  1906. self.on_filerunscript(name=file_name)
  1907. except Exception as e:
  1908. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1909. def set_ui_title(self, name):
  1910. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  1911. (self.version,
  1912. ('BETA' if self.beta else ''),
  1913. platform.architecture()[0],
  1914. name)
  1915. )
  1916. def defaults_read_form(self):
  1917. for option in self.defaults_form_fields:
  1918. try:
  1919. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1920. except Exception as e:
  1921. log.debug("App.defaults_read_form() --> %s" % str(e))
  1922. def defaults_write_form(self, factor=None, fl_units=None):
  1923. for option in self.defaults:
  1924. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  1925. # try:
  1926. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1927. # except KeyError:
  1928. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1929. # # TODO: Rethink this?
  1930. # pass
  1931. def defaults_write_form_field(self, field, factor=None, units=None):
  1932. try:
  1933. if factor is None:
  1934. if units is None:
  1935. self.defaults_form_fields[field].set_value(self.defaults[field])
  1936. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  1937. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  1938. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  1939. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  1940. else:
  1941. if units is None:
  1942. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  1943. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  1944. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  1945. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  1946. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  1947. except KeyError:
  1948. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  1949. # TODO: Rethink this?
  1950. pass
  1951. except AttributeError:
  1952. log.debug(field)
  1953. def clear_pool(self):
  1954. self.pool.close()
  1955. self.pool = Pool()
  1956. self.pool_recreated.emit(self.pool)
  1957. gc.collect()
  1958. # the order that the tools are installed is important as they can depend on each other install position
  1959. def install_tools(self):
  1960. self.dblsidedtool = DblSidedTool(self)
  1961. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1962. self.measurement_tool = Measurement(self)
  1963. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1964. self.panelize_tool = Panelize(self)
  1965. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1966. self.film_tool = Film(self)
  1967. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1968. self.paste_tool = SolderPaste(self)
  1969. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  1970. self.calculator_tool = ToolCalculator(self)
  1971. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  1972. self.sub_tool = ToolSub(self)
  1973. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  1974. self.move_tool = ToolMove(self)
  1975. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1976. before=self.ui.menueditorigin)
  1977. self.cutout_tool = CutOut(self)
  1978. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  1979. before=self.measurement_tool.menuAction)
  1980. self.ncclear_tool = NonCopperClear(self)
  1981. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  1982. before=self.measurement_tool.menuAction, separator=True)
  1983. self.paint_tool = ToolPaint(self)
  1984. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1985. before=self.measurement_tool.menuAction, separator=True)
  1986. self.transform_tool = ToolTransform(self)
  1987. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1988. self.properties_tool = Properties(self)
  1989. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1990. self.pdf_tool = ToolPDF(self)
  1991. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  1992. separator=True)
  1993. self.image_tool = ToolImage(self)
  1994. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1995. separator=True)
  1996. self.pcb_wizard_tool = PcbWizard(self)
  1997. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  1998. self.log.debug("Tools are installed.")
  1999. def remove_tools(self):
  2000. for act in self.ui.menutool.actions():
  2001. self.ui.menutool.removeAction(act)
  2002. def init_tools(self):
  2003. log.debug("init_tools()")
  2004. # delete the data currently in the Tools Tab and the Tab itself
  2005. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2006. if widget is not None:
  2007. widget.deleteLater()
  2008. self.ui.notebook.removeTab(2)
  2009. # rebuild the Tools Tab
  2010. self.ui.tool_tab = QtWidgets.QWidget()
  2011. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2012. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2013. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2014. self.ui.tool_scroll_area = VerticalScrollArea()
  2015. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2016. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2017. # first remove all of them
  2018. self.remove_tools()
  2019. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2020. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2021. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2022. # third install all of them
  2023. self.install_tools()
  2024. self.log.debug("Tools are initialized.")
  2025. # def parse_system_fonts(self):
  2026. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2027. # 'params': []})
  2028. def connect_toolbar_signals(self):
  2029. # Toolbar
  2030. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2031. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2032. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2033. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2034. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2035. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2036. self.ui.replot_btn.triggered.connect(self.plot_all)
  2037. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2038. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2039. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2040. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2041. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2042. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2043. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2044. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2045. self.ui.delete_btn.triggered.connect(self.on_delete)
  2046. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2047. # Tools Toolbar Signals
  2048. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2049. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2050. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2051. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2052. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2053. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2054. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2055. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2056. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2057. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2058. def object2editor(self):
  2059. """
  2060. Send the current Geometry or Excellon object (if any) into the editor.
  2061. :return: None
  2062. """
  2063. self.report_usage("object2editor()")
  2064. edited_object = self.collection.get_active()
  2065. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2066. isinstance(edited_object, FlatCAMExcellon):
  2067. pass
  2068. else:
  2069. self.inform.emit(_("[WARNING_NOTCL] Select a Geometry, Gerber or Excellon Object to edit."))
  2070. return
  2071. if isinstance(edited_object, FlatCAMGeometry):
  2072. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2073. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2074. # we set the notebook to hidden
  2075. self.ui.splitter.setSizes([0, 1])
  2076. if edited_object.multigeo is True:
  2077. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2078. if len(edited_tools) > 1:
  2079. self.inform.emit(_("[WARNING_NOTCL] Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2080. "is not possible.\n"
  2081. "Edit only one geometry at a time."))
  2082. # determine the tool dia of the selected tool
  2083. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2084. # now find the key in the edited_object.tools that has this tooldia
  2085. multi_tool = 1
  2086. for tool in edited_object.tools:
  2087. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2088. multi_tool = tool
  2089. break
  2090. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2091. else:
  2092. self.geo_editor.edit_fcgeometry(edited_object)
  2093. # set call source to the Editor we go into
  2094. self.call_source = 'geo_editor'
  2095. elif isinstance(edited_object, FlatCAMExcellon):
  2096. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2097. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2098. if self.ui.splitter.sizes()[0] == 0:
  2099. self.ui.splitter.setSizes([1, 1])
  2100. self.exc_editor.edit_fcexcellon(edited_object)
  2101. # set call source to the Editor we go into
  2102. self.call_source = 'exc_editor'
  2103. elif isinstance(edited_object, FlatCAMGerber):
  2104. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2105. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2106. if self.ui.splitter.sizes()[0] == 0:
  2107. self.ui.splitter.setSizes([1, 1])
  2108. self.grb_editor.edit_fcgerber(edited_object)
  2109. # set call source to the Editor we go into
  2110. self.call_source = 'grb_editor'
  2111. # make sure that we can't select another object while in Editor Mode:
  2112. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2113. self.ui.project_frame.setDisabled(True)
  2114. # delete any selection shape that might be active as they are not relevant in Editor
  2115. self.delete_selection_shape()
  2116. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2117. self.ui.plot_tab_area.protectTab(0)
  2118. self.inform.emit(_("[WARNING_NOTCL] Editor is activated ..."))
  2119. self.should_we_save = True
  2120. def editor2object(self, cleanup=None):
  2121. """
  2122. Transfers the Geometry or Excellon from the editor to the current object.
  2123. :return: None
  2124. """
  2125. self.report_usage("editor2object()")
  2126. # do not update a geometry or excellon object unless it comes out of an editor
  2127. if self.call_source != 'app':
  2128. edited_obj = self.collection.get_active()
  2129. if cleanup is None:
  2130. msgbox = QtWidgets.QMessageBox()
  2131. msgbox.setText(_("Do you want to save the edited object?"))
  2132. msgbox.setWindowTitle(_("Close Editor"))
  2133. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2134. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2135. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2136. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2137. msgbox.setDefaultButton(bt_yes)
  2138. msgbox.exec_()
  2139. response = msgbox.clickedButton()
  2140. if response == bt_yes:
  2141. # clean the Tools Tab
  2142. self.ui.tool_scroll_area.takeWidget()
  2143. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2144. self.ui.notebook.setTabText(2, "Tool")
  2145. if isinstance(edited_obj, FlatCAMGeometry):
  2146. obj_type = "Geometry"
  2147. if cleanup is None:
  2148. self.geo_editor.update_fcgeometry(edited_obj)
  2149. self.geo_editor.update_options(edited_obj)
  2150. self.geo_editor.deactivate()
  2151. # update the geo object options so it is including the bounding box values
  2152. try:
  2153. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2154. edited_obj.options['xmin'] = xmin
  2155. edited_obj.options['ymin'] = ymin
  2156. edited_obj.options['xmax'] = xmax
  2157. edited_obj.options['ymax'] = ymax
  2158. except AttributeError as e:
  2159. self.inform.emit(_("[WARNING] Object empty after edit."))
  2160. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2161. elif isinstance(edited_obj, FlatCAMGerber):
  2162. obj_type = "Gerber"
  2163. if cleanup is None:
  2164. self.grb_editor.update_fcgerber()
  2165. self.grb_editor.update_options(edited_obj)
  2166. self.grb_editor.deactivate_grb_editor()
  2167. # delete the old object (the source object) if it was an empty one
  2168. if len(edited_obj.solid_geometry) == 0:
  2169. old_name = edited_obj.options['name']
  2170. self.collection.set_active(old_name)
  2171. self.collection.delete_active()
  2172. elif isinstance(edited_obj, FlatCAMExcellon):
  2173. obj_type = "Excellon"
  2174. if cleanup is None:
  2175. self.exc_editor.update_fcexcellon(edited_obj)
  2176. self.exc_editor.update_options(edited_obj)
  2177. self.exc_editor.deactivate()
  2178. else:
  2179. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2180. return
  2181. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  2182. elif response == bt_no:
  2183. # clean the Tools Tab
  2184. self.ui.tool_scroll_area.takeWidget()
  2185. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2186. self.ui.notebook.setTabText(2, "Tool")
  2187. if isinstance(edited_obj, FlatCAMGeometry):
  2188. self.geo_editor.deactivate()
  2189. elif isinstance(edited_obj, FlatCAMGerber):
  2190. self.grb_editor.deactivate_grb_editor()
  2191. elif isinstance(edited_obj, FlatCAMExcellon):
  2192. self.exc_editor.deactivate()
  2193. # set focus on the project tab
  2194. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2195. else:
  2196. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2197. return
  2198. elif response == bt_cancel:
  2199. return
  2200. else:
  2201. if isinstance(edited_obj, FlatCAMGeometry):
  2202. self.geo_editor.deactivate()
  2203. elif isinstance(edited_obj, FlatCAMGerber):
  2204. self.grb_editor.deactivate_grb_editor()
  2205. elif isinstance(edited_obj, FlatCAMExcellon):
  2206. self.exc_editor.deactivate()
  2207. else:
  2208. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2209. return
  2210. # if notebook is hidden we show it
  2211. if self.ui.splitter.sizes()[0] == 0:
  2212. self.ui.splitter.setSizes([1, 1])
  2213. # restore the call_source to app
  2214. self.call_source = 'app'
  2215. edited_obj.plot()
  2216. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2217. self.ui.plot_tab_area.protectTab(0)
  2218. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2219. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2220. self.ui.project_frame.setDisabled(False)
  2221. def get_last_folder(self):
  2222. return self.defaults["global_last_folder"]
  2223. def get_last_save_folder(self):
  2224. loc = self.defaults["global_last_save_folder"]
  2225. if loc is None:
  2226. loc = self.defaults["global_last_folder"]
  2227. if loc is None:
  2228. loc = os.path.dirname(__file__)
  2229. return loc
  2230. def report_usage(self, resource):
  2231. """
  2232. Increments usage counter for the given resource
  2233. in self.defaults['global_stats'].
  2234. :param resource: Name of the resource.
  2235. :return: None
  2236. """
  2237. if resource in self.defaults['global_stats']:
  2238. self.defaults['global_stats'][resource] += 1
  2239. else:
  2240. self.defaults['global_stats'][resource] = 1
  2241. def init_tcl(self):
  2242. if hasattr(self, 'tcl'):
  2243. # self.tcl = None
  2244. # TODO we need to clean non default variables and procedures here
  2245. # new object cannot be used here as it will not remember values created for next passes,
  2246. # because tcl was execudted in old instance of TCL
  2247. pass
  2248. else:
  2249. self.tcl = tk.Tcl()
  2250. self.setup_shell()
  2251. self.log.debug("TCL Shell has been initialized.")
  2252. # TODO: This shouldn't be here.
  2253. class TclErrorException(Exception):
  2254. """
  2255. this exception is defined here, to be able catch it if we ssuccessfully handle all errors from shell command
  2256. """
  2257. pass
  2258. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2259. """
  2260. Shows a message on the FlatCAM Shell
  2261. :param msg: Message to display.
  2262. :param show: Opens the shell.
  2263. :param error: Shows the message as an error.
  2264. :param warning: Shows the message as an warning.
  2265. :param success: Shows the message as an success.
  2266. :param selected: Indicate that something was selected on canvas
  2267. :return: None
  2268. """
  2269. if show:
  2270. self.ui.shell_dock.show()
  2271. try:
  2272. if error:
  2273. self.shell.append_error(msg + "\n")
  2274. elif warning:
  2275. self.shell.append_warning(msg + "\n")
  2276. elif success:
  2277. self.shell.append_success(msg + "\n")
  2278. elif selected:
  2279. self.shell.append_selected(msg + "\n")
  2280. else:
  2281. self.shell.append_output(msg + "\n")
  2282. except AttributeError:
  2283. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2284. def raise_tcl_unknown_error(self, unknownException):
  2285. """
  2286. Raise exception if is different type than TclErrorException
  2287. this is here mainly to show unknown errors inside TCL shell console.
  2288. :param unknownException:
  2289. :return:
  2290. """
  2291. if not isinstance(unknownException, self.TclErrorException):
  2292. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2293. else:
  2294. raise unknownException
  2295. def display_tcl_error(self, error, error_info=None):
  2296. """
  2297. Escape bracket [ with '\' otherwise there is error
  2298. "ERROR: missing close-bracket" instead of real error
  2299. :param error: it may be text or exception
  2300. :param error_info: Some informations about the error
  2301. :return: None
  2302. """
  2303. if isinstance(error, Exception):
  2304. exc_type, exc_value, exc_traceback = error_info
  2305. if not isinstance(error, self.TclErrorException):
  2306. show_trace = 1
  2307. else:
  2308. show_trace = int(self.defaults['global_verbose_error_level'])
  2309. if show_trace > 0:
  2310. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2311. trc_formated = []
  2312. for a in reversed(trc):
  2313. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2314. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2315. else:
  2316. text = "%s" % error
  2317. else:
  2318. text = error
  2319. text = text.replace('[', '\\[').replace('"', '\\"')
  2320. self.tcl.eval('return -code error "%s"' % text)
  2321. def raise_tcl_error(self, text):
  2322. """
  2323. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2324. :param text: text of error
  2325. :return: raise exception
  2326. """
  2327. self.display_tcl_error(text)
  2328. raise self.TclErrorException(text)
  2329. def exec_command(self, text):
  2330. """
  2331. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2332. Also handles execution in separated threads
  2333. :param text:
  2334. :return: output if there was any
  2335. """
  2336. self.report_usage('exec_command')
  2337. result = self.exec_command_test(text, False)
  2338. # MS: added this method call so the geometry is updated once the TCL command is executed
  2339. self.plot_all()
  2340. return result
  2341. def exec_command_test(self, text, reraise=True):
  2342. """
  2343. Same as exec_command(...) with additional control over exceptions.
  2344. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2345. :param text: Input command
  2346. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2347. :return: Output from the command
  2348. """
  2349. text = str(text)
  2350. try:
  2351. self.shell.open_proccessing() # Disables input box.
  2352. result = self.tcl.eval(str(text))
  2353. if result != 'None':
  2354. self.shell.append_output(result + '\n')
  2355. except tk.TclError as e:
  2356. # This will display more precise answer if something in TCL shell fails
  2357. result = self.tcl.eval("set errorInfo")
  2358. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2359. self.shell.append_error('ERROR: ' + result + '\n')
  2360. # Show error in console and just return or in test raise exception
  2361. if reraise:
  2362. raise e
  2363. finally:
  2364. self.shell.close_proccessing()
  2365. pass
  2366. return result
  2367. # """
  2368. # Code below is unsused. Saved for later.
  2369. # """
  2370. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2371. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2372. # self.log.debug(parts)
  2373. # try:
  2374. # if parts[0] not in commands:
  2375. # self.shell.append_error("Unknown command\n")
  2376. # return
  2377. #
  2378. # #import inspect
  2379. # #inspect.getargspec(someMethod)
  2380. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2381. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2382. # self.shell.append_error(
  2383. # "Command %s takes %d arguments. %d given.\n" %
  2384. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2385. # )
  2386. # return
  2387. #
  2388. # cmdfcn = commands[parts[0]]["fcn"]
  2389. # cmdconv = commands[parts[0]]["converters"]
  2390. # if len(parts) - 1 > 0:
  2391. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2392. # else:
  2393. # retval = cmdfcn()
  2394. # retfcn = commands[parts[0]]["retfcn"]
  2395. # if retval and retfcn(retval):
  2396. # self.shell.append_output(retfcn(retval) + "\n")
  2397. #
  2398. # except Exception as e:
  2399. # #self.shell.append_error(''.join(traceback.format_exc()))
  2400. # #self.shell.append_error("?\n")
  2401. # self.shell.append_error(str(e) + "\n")
  2402. def info(self, msg):
  2403. """
  2404. Informs the user. Normally on the status bar, optionally
  2405. also on the shell.
  2406. :param msg: Text to write.
  2407. :return: None
  2408. """
  2409. # Type of message in brackets at the beginning of the message.
  2410. match = re.search("\[([^\]]+)\](.*)", msg)
  2411. if match:
  2412. level = match.group(1)
  2413. msg_ = match.group(2)
  2414. self.ui.fcinfo.set_status(str(msg_), level=level)
  2415. if level.lower() == "error":
  2416. self.shell_message(msg, error=True, show=True)
  2417. elif level.lower() == "warning":
  2418. self.shell_message(msg, warning=True, show=True)
  2419. elif level.lower() == "error_notcl":
  2420. self.shell_message(msg, error=True, show=False)
  2421. elif level.lower() == "warning_notcl":
  2422. self.shell_message(msg, warning=True, show=False)
  2423. elif level.lower() == "success":
  2424. self.shell_message(msg, success=True, show=False)
  2425. elif level.lower() == "selected":
  2426. self.shell_message(msg, selected=True, show=False)
  2427. else:
  2428. self.shell_message(msg, show=False)
  2429. else:
  2430. self.ui.fcinfo.set_status(str(msg), level="info")
  2431. # make sure that if the message is to clear the infobar with a space
  2432. # is not printed over and over on the shell
  2433. if msg != '':
  2434. self.shell_message(msg)
  2435. def restore_toolbar_view(self):
  2436. tb = self.defaults["global_toolbar_view"]
  2437. if tb & 1:
  2438. self.ui.toolbarfile.setVisible(True)
  2439. else:
  2440. self.ui.toolbarfile.setVisible(False)
  2441. if tb & 2:
  2442. self.ui.toolbargeo.setVisible(True)
  2443. else:
  2444. self.ui.toolbargeo.setVisible(False)
  2445. if tb & 4:
  2446. self.ui.toolbarview.setVisible(True)
  2447. else:
  2448. self.ui.toolbarview.setVisible(False)
  2449. if tb & 8:
  2450. self.ui.toolbartools.setVisible(True)
  2451. else:
  2452. self.ui.toolbartools.setVisible(False)
  2453. if tb & 16:
  2454. self.ui.exc_edit_toolbar.setVisible(True)
  2455. else:
  2456. self.ui.exc_edit_toolbar.setVisible(False)
  2457. if tb & 32:
  2458. self.ui.geo_edit_toolbar.setVisible(True)
  2459. else:
  2460. self.ui.geo_edit_toolbar.setVisible(False)
  2461. if tb & 64:
  2462. self.ui.grb_edit_toolbar.setVisible(True)
  2463. else:
  2464. self.ui.grb_edit_toolbar.setVisible(False)
  2465. if tb & 128:
  2466. self.ui.snap_toolbar.setVisible(True)
  2467. else:
  2468. self.ui.snap_toolbar.setVisible(False)
  2469. if tb & 256:
  2470. self.ui.toolbarshell.setVisible(True)
  2471. else:
  2472. self.ui.toolbarshell.setVisible(False)
  2473. def load_defaults(self, filename):
  2474. """
  2475. Loads the aplication's default settings from current_defaults.FlatConfig into
  2476. ``self.defaults``.
  2477. :return: None
  2478. """
  2479. try:
  2480. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2481. options = f.read()
  2482. f.close()
  2483. except IOError:
  2484. self.log.error("Could not load defaults file.")
  2485. self.inform.emit(_("[ERROR] Could not load defaults file."))
  2486. # in case the defaults file can't be loaded, show all toolbars
  2487. self.defaults["global_toolbar_view"] = 511
  2488. return
  2489. try:
  2490. defaults = json.loads(options)
  2491. except:
  2492. # in case the defaults file can't be loaded, show all toolbars
  2493. self.defaults["global_toolbar_view"] = 511
  2494. e = sys.exc_info()[0]
  2495. App.log.error(str(e))
  2496. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  2497. return
  2498. self.defaults.update(defaults)
  2499. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2500. # restore the toolbar view
  2501. self.restore_toolbar_view()
  2502. def on_import_preferences(self):
  2503. """
  2504. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2505. ``self.defaults``.
  2506. :return: None
  2507. """
  2508. self.report_usage("on_import_preferences")
  2509. App.log.debug("on_import_preferences()")
  2510. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2511. try:
  2512. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2513. directory=self.data_path,
  2514. filter=filter_)
  2515. except TypeError:
  2516. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2517. filter=filter_)
  2518. filename = str(filename)
  2519. if filename == "":
  2520. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences import cancelled."))
  2521. else:
  2522. try:
  2523. f = open(filename)
  2524. options = f.read()
  2525. f.close()
  2526. except IOError:
  2527. self.log.error("Could not load defaults file.")
  2528. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2529. return
  2530. try:
  2531. defaults_from_file = json.loads(options)
  2532. except Exception as e:
  2533. e = sys.exc_info()[0]
  2534. App.log.error(str(e))
  2535. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2536. return
  2537. self.defaults.update(defaults_from_file)
  2538. self.on_preferences_edited()
  2539. self.inform.emit(_("[success] Imported Defaults from %s") % filename)
  2540. def on_export_preferences(self):
  2541. self.report_usage("on_export_preferences")
  2542. App.log.debug("on_export_preferences()")
  2543. defaults_file_content = None
  2544. self.date = str(datetime.today()).rpartition('.')[0]
  2545. self.date = ''.join(c for c in self.date if c not in ':-')
  2546. self.date = self.date.replace(' ', '_')
  2547. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2548. try:
  2549. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2550. caption=_("Export FlatCAM Preferences"),
  2551. directory=self.data_path + '/preferences_' + self.date,
  2552. filter=filter__
  2553. )
  2554. except TypeError:
  2555. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2556. filter=filter__)
  2557. filename = str(filename)
  2558. defaults_from_file = {}
  2559. if filename == "":
  2560. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences export cancelled."))
  2561. return
  2562. else:
  2563. try:
  2564. f = open(filename, 'w')
  2565. defaults_file_content = f.read()
  2566. f.close()
  2567. except PermissionError:
  2568. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  2569. "Most likely another app is holding the file open and not accessible."))
  2570. return
  2571. except IOError:
  2572. App.log.debug('Creating a new preferences file ...')
  2573. f = open(filename, 'w')
  2574. json.dump({}, f)
  2575. f.close()
  2576. except:
  2577. e = sys.exc_info()[0]
  2578. App.log.error("Could not load defaults file.")
  2579. App.log.error(str(e))
  2580. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2581. return
  2582. try:
  2583. defaults_from_file = json.loads(defaults_file_content)
  2584. except:
  2585. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2586. # Update options
  2587. self.defaults_read_form()
  2588. defaults_from_file.update(self.defaults)
  2589. self.propagate_defaults(silent=True)
  2590. # Save update options
  2591. try:
  2592. f = open(filename, "w")
  2593. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2594. f.close()
  2595. except:
  2596. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2597. return
  2598. if self.defaults["global_open_style"] is False:
  2599. self.file_opened.emit("preferences", filename)
  2600. self.file_saved.emit("preferences", filename)
  2601. self.inform.emit("[success] Exported Defaults to %s" % filename)
  2602. def on_preferences_open_folder(self):
  2603. self.report_usage("on_preferences_open_folder()")
  2604. if sys.platform == 'win32':
  2605. subprocess.Popen('explorer %s' % self.data_path)
  2606. elif sys.platform == 'darwin':
  2607. os.system('open "%s"' % self.data_path)
  2608. else:
  2609. subprocess.Popen(['xdg-open', self.data_path])
  2610. self.inform.emit("[success] FlatCAM Preferences Folder opened.")
  2611. def save_geometry(self, x, y, width, height, notebook_width):
  2612. self.defaults["global_def_win_x"] = x
  2613. self.defaults["global_def_win_y"] = y
  2614. self.defaults["global_def_win_w"] = width
  2615. self.defaults["global_def_win_h"] = height
  2616. self.defaults["global_def_notebook_width"] = notebook_width
  2617. self.save_defaults()
  2618. def message_dialog(self, title, message, kind="info"):
  2619. icon = {"info": QtWidgets.QMessageBox.Information,
  2620. "warning": QtWidgets.QMessageBox.Warning,
  2621. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2622. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2623. dlg.setText(message)
  2624. dlg.exec_()
  2625. def register_recent(self, kind, filename):
  2626. self.log.debug("register_recent()")
  2627. self.log.debug(" %s" % kind)
  2628. self.log.debug(" %s" % filename)
  2629. record = {'kind': str(kind), 'filename': str(filename)}
  2630. if record in self.recent:
  2631. return
  2632. if record in self.recent_projects:
  2633. return
  2634. if record['kind'] == 'project':
  2635. self.recent_projects.insert(0, record)
  2636. else:
  2637. self.recent.insert(0, record)
  2638. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2639. self.recent.pop()
  2640. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2641. self.recent_projects.pop()
  2642. try:
  2643. f = open(self.data_path + '/recent.json', 'w')
  2644. except IOError:
  2645. App.log.error("Failed to open recent items file for writing.")
  2646. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.'))
  2647. return
  2648. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2649. f.close()
  2650. try:
  2651. fp = open(self.data_path + '/recent_projects.json', 'w')
  2652. except IOError:
  2653. App.log.error("Failed to open recent items file for writing.")
  2654. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent projects file for writing.'))
  2655. return
  2656. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2657. fp.close()
  2658. # Re-build the recent items menu
  2659. self.setup_recent_items()
  2660. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2661. """
  2662. Creates a new specialized FlatCAMObj and attaches it to the application,
  2663. this is, updates the GUI accordingly, any other records and plots it.
  2664. This method is thread-safe.
  2665. Notes:
  2666. * If the name is in use, the self.collection will modify it
  2667. when appending it to the collection. There is no need to handle
  2668. name conflicts here.
  2669. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2670. :type kind: str
  2671. :param name: Name for the object.
  2672. :type name: str
  2673. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2674. The function is called with 2 parameters: the new object and the App instance.
  2675. :type initialize: function
  2676. :param active:
  2677. :param fit:
  2678. :param plot: If to plot the resulting object
  2679. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2680. self.colleaction
  2681. :return: None
  2682. :rtype: None
  2683. """
  2684. App.log.debug("new_object()")
  2685. obj_plot = plot
  2686. obj_autoselected = autoselected
  2687. t0 = time.time() # Debug
  2688. # ## Create object
  2689. classdict = {
  2690. "gerber": FlatCAMGerber,
  2691. "excellon": FlatCAMExcellon,
  2692. "cncjob": FlatCAMCNCjob,
  2693. "geometry": FlatCAMGeometry
  2694. }
  2695. App.log.debug("Calling object constructor...")
  2696. obj = classdict[kind](name)
  2697. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2698. # Set options from "Project options" form
  2699. self.options_read_form()
  2700. # IMPORTANT
  2701. # The key names in defaults and options dictionary's are not random:
  2702. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2703. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2704. # the options from project options form into the self.options. After that, below, depending on the type of
  2705. # object that is created, it will strip the name of the object and the underline (if the original key was
  2706. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2707. # "toolchange"
  2708. for option in self.options:
  2709. if option.find(kind + "_") == 0:
  2710. oname = option[len(kind) + 1:]
  2711. obj.options[oname] = self.options[option]
  2712. obj.isHovering = False
  2713. obj.notHovering = True
  2714. # Initialize as per user request
  2715. # User must take care to implement initialize
  2716. # in a thread-safe way as is is likely that we
  2717. # have been invoked in a separate thread.
  2718. t1 = time.time()
  2719. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2720. try:
  2721. return_value = initialize(obj, self)
  2722. except Exception as e:
  2723. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2724. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2725. msg += traceback.format_exc()
  2726. self.inform.emit(msg)
  2727. # if str(e) == "Empty Geometry":
  2728. # self.inform.emit("[ERROR_NOTCL] )
  2729. # else:
  2730. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2731. return "fail"
  2732. t2 = time.time()
  2733. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2734. if return_value == 'fail':
  2735. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2736. return "fail"
  2737. # Check units and convert if necessary
  2738. # This condition CAN be true because initialize() can change obj.units
  2739. if self.options["units"].upper() != obj.units.upper():
  2740. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2741. obj.convert_units(self.options["units"])
  2742. t3 = time.time()
  2743. self.log.debug("%f seconds converting units." % (t3 - t2))
  2744. # Create the bounding box for the object and then add the results to the obj.options
  2745. try:
  2746. xmin, ymin, xmax, ymax = obj.bounds()
  2747. obj.options['xmin'] = xmin
  2748. obj.options['ymin'] = ymin
  2749. obj.options['xmax'] = xmax
  2750. obj.options['ymax'] = ymax
  2751. except Exception as e:
  2752. log.warning("The object has no bounds properties. %s" % str(e))
  2753. return "fail"
  2754. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2755. # Move the object to the main thread and let the app know that it is available.
  2756. obj.moveToThread(self.main_thread)
  2757. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2758. return obj
  2759. def new_excellon_object(self):
  2760. self.report_usage("new_excellon_object()")
  2761. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2762. def new_geometry_object(self):
  2763. self.report_usage("new_geometry_object()")
  2764. def initialize(obj, self):
  2765. obj.multitool = False
  2766. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2767. def new_gerber_object(self):
  2768. self.report_usage("new_gerber_object()")
  2769. def initialize(grb_obj, self):
  2770. grb_obj.multitool = False
  2771. grb_obj.source_file = []
  2772. grb_obj.multigeo = False
  2773. grb_obj.follow = False
  2774. grb_obj.apertures = {}
  2775. grb_obj.solid_geometry = []
  2776. try:
  2777. grb_obj.options['xmin'] = 0
  2778. grb_obj.options['ymin'] = 0
  2779. grb_obj.options['xmax'] = 0
  2780. grb_obj.options['ymax'] = 0
  2781. except KeyError:
  2782. pass
  2783. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2784. def on_object_created(self, obj, plot, autoselect):
  2785. """
  2786. Event callback for object creation.
  2787. :param obj: The newly created FlatCAM object.
  2788. :return: None
  2789. """
  2790. t0 = time.time() # DEBUG
  2791. self.log.debug("on_object_created()")
  2792. # The Collection might change the name if there is a collision
  2793. self.collection.append(obj)
  2794. # after adding the object to the collection always update the list of objects that are in the collection
  2795. self.all_objects_list = self.collection.get_list()
  2796. # self.inform.emit('[selected] %s created & selected: %s' %
  2797. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2798. if obj.kind == 'gerber':
  2799. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2800. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  2801. elif obj.kind == 'excellon':
  2802. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2803. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  2804. elif obj.kind == 'cncjob':
  2805. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2806. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  2807. elif obj.kind == 'geometry':
  2808. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2809. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  2810. # update the SHELL auto-completer model with the name of the new object
  2811. self.myKeywords.append(obj.options['name'])
  2812. self.shell._edit.set_model_data(self.myKeywords)
  2813. self.ui.code_editor.set_model_data(self.myKeywords)
  2814. if autoselect:
  2815. # select the just opened object but deselect the previous ones
  2816. self.collection.set_all_inactive()
  2817. self.collection.set_active(obj.options["name"])
  2818. else:
  2819. self.collection.set_all_inactive()
  2820. # here it is done the object plotting
  2821. def worker_task(t_obj):
  2822. with self.proc_container.new("Plotting"):
  2823. if isinstance(t_obj, FlatCAMCNCjob):
  2824. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2825. else:
  2826. t_obj.plot()
  2827. t1 = time.time() # DEBUG
  2828. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2829. self.object_plotted.emit(t_obj)
  2830. # Send to worker
  2831. # self.worker.add_task(worker_task, [self])
  2832. if plot is True:
  2833. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2834. def on_object_changed(self, obj):
  2835. # update the bounding box data from obj.options
  2836. xmin, ymin, xmax, ymax = obj.bounds()
  2837. obj.options['xmin'] = xmin
  2838. obj.options['ymin'] = ymin
  2839. obj.options['xmax'] = xmax
  2840. obj.options['ymax'] = ymax
  2841. log.debug("Object changed, updating the bounding box data on self.options")
  2842. # delete the old selection shape
  2843. self.delete_selection_shape()
  2844. self.should_we_save = True
  2845. def on_object_plotted(self, obj):
  2846. self.on_zoom_fit(None)
  2847. def options_read_form(self):
  2848. for option in self.options_form_fields:
  2849. self.options[option] = self.options_form_fields[option].get_value()
  2850. def options_write_form(self):
  2851. for option in self.options:
  2852. self.options_write_form_field(option)
  2853. def options_write_form_field(self, field):
  2854. try:
  2855. self.options_form_fields[field].set_value(self.options[field])
  2856. except KeyError:
  2857. # Changed from error to debug. This allows to have data stored
  2858. # which is not user-editable.
  2859. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2860. pass
  2861. def on_about(self):
  2862. """
  2863. Displays the "about" dialog.
  2864. :return: None
  2865. """
  2866. self.report_usage("on_about")
  2867. version = self.version
  2868. version_date = self.version_date
  2869. beta = self.beta
  2870. class AboutDialog(QtWidgets.QDialog):
  2871. def __init__(self, parent=None):
  2872. QtWidgets.QDialog.__init__(self, parent)
  2873. # Icon and title
  2874. self.setWindowIcon(parent.app_icon)
  2875. self.setWindowTitle("FlatCAM")
  2876. layout1 = QtWidgets.QVBoxLayout()
  2877. self.setLayout(layout1)
  2878. layout2 = QtWidgets.QHBoxLayout()
  2879. layout1.addLayout(layout2)
  2880. logo = QtWidgets.QLabel()
  2881. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2882. layout2.addWidget(logo, stretch=0)
  2883. title = QtWidgets.QLabel(
  2884. _(
  2885. "<font size=8><B>FlatCAM</B></font><BR>"
  2886. "Version {version} {beta} ({date}) - {arch} <BR>"
  2887. "<BR>"
  2888. "2D Computer-Aided Printed Circuit Board<BR>"
  2889. "Manufacturing.<BR>"
  2890. "<BR>"
  2891. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2892. "<BR>"
  2893. "<B> Main Contributors:</B><BR>"
  2894. "Denis Hayrullin<BR>"
  2895. "Kamil Sopko<BR>"
  2896. "Marius Stanciu<BR>"
  2897. "Matthieu Berthomé<BR>"
  2898. "and many others found "
  2899. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2900. "<BR>"
  2901. "Development is done "
  2902. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2903. "DOWNLOAD area "
  2904. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2905. ""
  2906. ).format(version=version,
  2907. beta=('BETA' if beta else ''),
  2908. date=version_date,
  2909. arch=platform.architecture()[0])
  2910. )
  2911. title.setOpenExternalLinks(True)
  2912. layout2.addWidget(title, stretch=1)
  2913. layout3 = QtWidgets.QHBoxLayout()
  2914. layout1.addLayout(layout3)
  2915. layout3.addStretch()
  2916. okbtn = QtWidgets.QPushButton(_("Close"))
  2917. layout3.addWidget(okbtn)
  2918. okbtn.clicked.connect(self.accept)
  2919. AboutDialog(self.ui).exec_()
  2920. def on_file_savedefaults(self):
  2921. """
  2922. Callback for menu item File->Save Defaults. Saves application default options
  2923. ``self.defaults`` to current_defaults.FlatConfig.
  2924. :return: None
  2925. """
  2926. self.save_defaults()
  2927. # def on_app_exit(self):
  2928. # self.report_usage("on_app_exit()")
  2929. #
  2930. # if self.collection.get_list():
  2931. # msgbox = QtWidgets.QMessageBox()
  2932. # # msgbox.setText("<B>Save changes ...</B>")
  2933. # msgbox.setText("There are files/objects opened in FlatCAM. "
  2934. # "\n"
  2935. # "Do you want to Save the project?")
  2936. # msgbox.setWindowTitle("Save changes")
  2937. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2938. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2939. # QtWidgets.QMessageBox.Cancel)
  2940. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2941. #
  2942. # response = msgbox.exec_()
  2943. #
  2944. # if response == QtWidgets.QMessageBox.Yes:
  2945. # self.on_file_saveprojectas(thread=False)
  2946. # elif response == QtWidgets.QMessageBox.Cancel:
  2947. # return
  2948. # self.save_defaults()
  2949. # else:
  2950. # self.save_defaults()
  2951. # log.debug("Application defaults saved ... Exit event.")
  2952. # QtWidgets.qApp.quit()
  2953. def save_defaults(self, silent=False, data_path=None):
  2954. """
  2955. Saves application default options
  2956. ``self.defaults`` to current_defaults.FlatConfig.
  2957. :return: None
  2958. """
  2959. self.report_usage("save_defaults")
  2960. if data_path is None:
  2961. data_path = self.data_path
  2962. # Read options from file
  2963. try:
  2964. f = open(data_path + "/current_defaults.FlatConfig")
  2965. defaults_file_content = f.read()
  2966. f.close()
  2967. except:
  2968. e = sys.exc_info()[0]
  2969. App.log.error("Could not load defaults file.")
  2970. App.log.error(str(e))
  2971. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2972. return
  2973. try:
  2974. defaults = json.loads(defaults_file_content)
  2975. except:
  2976. e = sys.exc_info()[0]
  2977. App.log.error("Failed to parse defaults file.")
  2978. App.log.error(str(e))
  2979. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2980. return
  2981. # Update options
  2982. self.defaults_read_form()
  2983. defaults.update(self.defaults)
  2984. self.propagate_defaults(silent=True)
  2985. # Save the toolbar view
  2986. tb_status = 0
  2987. if self.ui.toolbarfile.isVisible():
  2988. tb_status += 1
  2989. if self.ui.toolbargeo.isVisible():
  2990. tb_status += 2
  2991. if self.ui.toolbarview.isVisible():
  2992. tb_status += 4
  2993. if self.ui.toolbartools.isVisible():
  2994. tb_status += 8
  2995. if self.ui.exc_edit_toolbar.isVisible():
  2996. tb_status += 16
  2997. if self.ui.geo_edit_toolbar.isVisible():
  2998. tb_status += 32
  2999. if self.ui.grb_edit_toolbar.isVisible():
  3000. tb_status += 64
  3001. if self.ui.snap_toolbar.isVisible():
  3002. tb_status += 128
  3003. if self.ui.toolbarshell.isVisible():
  3004. tb_status += 256
  3005. self.defaults["global_toolbar_view"] = tb_status
  3006. # Save update options
  3007. try:
  3008. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3009. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3010. f.close()
  3011. except:
  3012. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  3013. return
  3014. if not silent:
  3015. self.inform.emit(_("[success] Defaults saved."))
  3016. def save_factory_defaults(self, silent=False, data_path=None):
  3017. """
  3018. Saves application factory default options
  3019. ``self.defaults`` to factory_defaults.FlatConfig.
  3020. It's a one time job done just after the first install.
  3021. :return: None
  3022. """
  3023. self.report_usage("save_factory_defaults")
  3024. if data_path is None:
  3025. data_path = self.data_path
  3026. # Read options from file
  3027. try:
  3028. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3029. factory_defaults_file_content = f_f_def.read()
  3030. f_f_def.close()
  3031. except:
  3032. e = sys.exc_info()[0]
  3033. App.log.error("Could not load factory defaults file.")
  3034. App.log.error(str(e))
  3035. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  3036. return
  3037. try:
  3038. factory_defaults = json.loads(factory_defaults_file_content)
  3039. except:
  3040. e = sys.exc_info()[0]
  3041. App.log.error("Failed to parse factory defaults file.")
  3042. App.log.error(str(e))
  3043. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  3044. return
  3045. # Update options
  3046. self.defaults_read_form()
  3047. factory_defaults.update(self.defaults)
  3048. self.propagate_defaults(silent=True)
  3049. # Save update options
  3050. try:
  3051. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3052. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3053. f_f_def_s.close()
  3054. except:
  3055. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  3056. return
  3057. if silent is False:
  3058. self.inform.emit(_("Factory defaults saved."))
  3059. def final_save(self):
  3060. if self.save_in_progress:
  3061. self.inform.emit(_("[WARNING_NOTCL] Application is saving the project. Please wait ..."))
  3062. return
  3063. if self.should_we_save and self.collection.get_list():
  3064. msgbox = QtWidgets.QMessageBox()
  3065. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3066. "\n"
  3067. "Do you want to Save the project?"))
  3068. msgbox.setWindowTitle(_("Save changes"))
  3069. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3070. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3071. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3072. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3073. msgbox.setDefaultButton(bt_yes)
  3074. msgbox.exec_()
  3075. response = msgbox.clickedButton()
  3076. if response == bt_yes:
  3077. self.on_file_saveprojectas(thread=True, quit=True)
  3078. elif response == bt_no:
  3079. self.quit_application()
  3080. elif response == bt_cancel:
  3081. return
  3082. else:
  3083. self.quit_application()
  3084. def quit_application(self):
  3085. self.save_defaults()
  3086. log.debug("App.final_save() --> App Defaults saved.")
  3087. # save toolbar state to file
  3088. settings = QSettings("Open Source", "FlatCAM")
  3089. settings.setValue('saved_gui_state', self.ui.saveState())
  3090. settings.setValue('maximized_gui', self.ui.isMaximized())
  3091. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3092. settings.setValue('notebook_font_size',
  3093. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3094. settings.setValue('axis_font_size',
  3095. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3096. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3097. # This will write the setting to the platform specific storage.
  3098. del settings
  3099. log.debug("App.final_save() --> App UI state saved.")
  3100. QtWidgets.qApp.quit()
  3101. def on_portable_checked(self, state):
  3102. line_no = 0
  3103. data = None
  3104. if sys.platform != 'win32':
  3105. # this won't work in Linux or MacOS
  3106. return
  3107. # test if the app was frozen and choose the path for the configuration file
  3108. if getattr(sys, "frozen", False) is True:
  3109. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3110. else:
  3111. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3112. config_file = current_data_path + '\\configuration.txt'
  3113. try:
  3114. with open(config_file, 'r') as f:
  3115. try:
  3116. data = f.readlines()
  3117. except Exception as e:
  3118. log.debug('App.__init__() -->%s' % str(e))
  3119. return
  3120. except FileNotFoundError:
  3121. pass
  3122. for line in data:
  3123. line = line.strip('\n')
  3124. param = str(line).rpartition('=')
  3125. if param[0] == 'portable':
  3126. break
  3127. line_no += 1
  3128. if state:
  3129. data[line_no] = 'portable=True\n'
  3130. # create the new defauults files
  3131. # create current_defaults.FlatConfig file if there is none
  3132. try:
  3133. f = open(current_data_path + '/current_defaults.FlatConfig')
  3134. f.close()
  3135. except IOError:
  3136. App.log.debug('Creating empty current_defaults.FlatConfig')
  3137. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3138. json.dump({}, f)
  3139. f.close()
  3140. # create factory_defaults.FlatConfig file if there is none
  3141. try:
  3142. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3143. f.close()
  3144. except IOError:
  3145. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3146. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3147. json.dump({}, f)
  3148. f.close()
  3149. try:
  3150. f = open(current_data_path + '/recent.json')
  3151. f.close()
  3152. except IOError:
  3153. App.log.debug('Creating empty recent.json')
  3154. f = open(current_data_path + '/recent.json', 'w')
  3155. json.dump([], f)
  3156. f.close()
  3157. try:
  3158. fp = open(current_data_path + '/recent_projects.json')
  3159. fp.close()
  3160. except IOError:
  3161. App.log.debug('Creating empty recent_projects.json')
  3162. fp = open(current_data_path + '/recent_projects.json', 'w')
  3163. json.dump([], fp)
  3164. fp.close()
  3165. # save the current defaults to the new defaults file
  3166. self.save_defaults(silent=True, data_path=current_data_path)
  3167. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3168. else:
  3169. data[line_no] = 'portable=False\n'
  3170. with open(config_file, 'w') as f:
  3171. f.writelines(data)
  3172. def on_toggle_shell(self):
  3173. """
  3174. toggle shell if is visible close it if closed open it
  3175. :return:
  3176. """
  3177. self.report_usage("on_toggle_shell()")
  3178. if self.ui.shell_dock.isVisible():
  3179. self.ui.shell_dock.hide()
  3180. else:
  3181. self.ui.shell_dock.show()
  3182. def on_edit_join(self, name=None):
  3183. """
  3184. Callback for Edit->Join. Joins the selected geometry objects into
  3185. a new one.
  3186. :return: None
  3187. """
  3188. self.report_usage("on_edit_join()")
  3189. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3190. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3191. tooldias = []
  3192. geo_type_list = set()
  3193. objs = self.collection.get_selected()
  3194. for obj in objs:
  3195. geo_type_list.add(obj.multigeo)
  3196. # if len(geo_type_list) == 1 means that all list elements are the same
  3197. if len(geo_type_list) != 1:
  3198. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  3199. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3200. "convert from one to another and retry joining \n"
  3201. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3202. "the result may not be what was expected. \n"
  3203. "Check the generated GCODE."))
  3204. return
  3205. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3206. if True in geo_type_list:
  3207. def initialize(obj, app):
  3208. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  3209. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3210. for v in obj.tools.values():
  3211. v['data']['name'] = obj_name_multi
  3212. self.new_object("geometry", obj_name_multi, initialize)
  3213. else:
  3214. def initialize(obj, app):
  3215. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  3216. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3217. for v in obj.tools.values():
  3218. v['data']['name'] = obj_name_single
  3219. self.new_object("geometry", obj_name_single, initialize)
  3220. self.should_we_save = True
  3221. def on_edit_join_exc(self):
  3222. """
  3223. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  3224. a new one.
  3225. :return: None
  3226. """
  3227. self.report_usage("on_edit_join_exc()")
  3228. objs = self.collection.get_selected()
  3229. for obj in objs:
  3230. if not isinstance(obj, FlatCAMExcellon):
  3231. self.inform.emit(_("[ERROR_NOTCL] Failed. Excellon joining works only on Excellon objects."))
  3232. return
  3233. def initialize(obj, app):
  3234. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  3235. self.new_object("excellon", 'Combo_Excellon', initialize)
  3236. self.should_we_save = True
  3237. def on_edit_join_grb(self):
  3238. """
  3239. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3240. a new one.
  3241. :return: None
  3242. """
  3243. self.report_usage("on_edit_join_grb()")
  3244. objs = self.collection.get_selected()
  3245. for obj in objs:
  3246. if not isinstance(obj, FlatCAMGerber):
  3247. self.inform.emit(_("[ERROR_NOTCL] Failed. Gerber joining works only on Gerber objects."))
  3248. return
  3249. def initialize(obj, app):
  3250. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  3251. self.new_object("gerber", 'Combo_Gerber', initialize)
  3252. self.should_we_save = True
  3253. def on_convert_singlegeo_to_multigeo(self):
  3254. self.report_usage("on_convert_singlegeo_to_multigeo()")
  3255. obj = self.collection.get_active()
  3256. if obj is None:
  3257. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  3258. return
  3259. if not isinstance(obj, FlatCAMGeometry):
  3260. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  3261. return
  3262. obj.multigeo = True
  3263. for tooluid, dict_value in obj.tools.items():
  3264. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3265. if not isinstance(obj.solid_geometry, list):
  3266. obj.solid_geometry = [obj.solid_geometry]
  3267. obj.solid_geometry[:] = []
  3268. obj.plot()
  3269. self.should_we_save = True
  3270. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  3271. def on_convert_multigeo_to_singlegeo(self):
  3272. self.report_usage("on_convert_multigeo_to_singlegeo()")
  3273. obj = self.collection.get_active()
  3274. if obj is None:
  3275. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  3276. return
  3277. if not isinstance(obj, FlatCAMGeometry):
  3278. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  3279. return
  3280. obj.multigeo = False
  3281. total_solid_geometry = []
  3282. for tooluid, dict_value in obj.tools.items():
  3283. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3284. # clear the original geometry
  3285. dict_value['solid_geometry'][:] = []
  3286. obj.solid_geometry = deepcopy(total_solid_geometry)
  3287. obj.plot()
  3288. self.should_we_save = True
  3289. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  3290. def on_options_dict_change(self, field):
  3291. self.options_write_form_field(field)
  3292. if field == "units":
  3293. self.set_screen_units(self.options['units'])
  3294. def on_defaults_dict_change(self, field):
  3295. self.defaults_write_form_field(field)
  3296. if field == "units":
  3297. self.set_screen_units(self.defaults['units'])
  3298. def set_screen_units(self, units):
  3299. self.ui.units_label.setText("[" + units.lower() + "]")
  3300. def on_toggle_units(self, no_pref=False):
  3301. """
  3302. Callback for the Units radio-button change in the Options tab.
  3303. Changes the application's default units or the current project's units.
  3304. If changing the project's units, the change propagates to all of
  3305. the objects in the project.
  3306. :return: None
  3307. """
  3308. self.report_usage("on_toggle_units")
  3309. if self.toggle_units_ignore:
  3310. return
  3311. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3312. # If option is the same, then ignore
  3313. if new_units == self.defaults["units"].upper():
  3314. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3315. return
  3316. # Options to scale
  3317. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3318. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  3319. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3320. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  3321. "excellon_z_pdepth",
  3322. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3323. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3324. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  3325. "geometry_feedrate_probe",
  3326. 'cncjob_tooldia',
  3327. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3328. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  3329. "tools_2sided_drilldia", "tools_film_boundary",
  3330. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3331. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3332. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3333. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3334. "tools_transform_offset_y",
  3335. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3336. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3337. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3338. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3339. 'global_gridx', 'global_gridy', 'global_snap_max']
  3340. def scale_options(sfactor):
  3341. for dim in dimensions:
  3342. if dim == 'excellon_toolchangexy':
  3343. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3344. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3345. coords_xy[0] *= sfactor
  3346. coords_xy[1] *= sfactor
  3347. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3348. elif dim == 'geometry_toolchangexy':
  3349. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3350. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3351. coords_xy[0] *= sfactor
  3352. coords_xy[1] *= sfactor
  3353. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3354. elif dim == 'geometry_cnctooldia':
  3355. tools_diameters = []
  3356. try:
  3357. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3358. tools_diameters = [eval(a) for a in tools_string if a != '']
  3359. except Exception as e:
  3360. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3361. self.options['geometry_cnctooldia'] = ''
  3362. for t in range(len(tools_diameters)):
  3363. tools_diameters[t] *= sfactor
  3364. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  3365. elif dim == 'tools_ncctools':
  3366. ncctools = []
  3367. try:
  3368. tools_string = self.defaults["tools_ncctools"].split(",")
  3369. ncctools = [eval(a) for a in tools_string if a != '']
  3370. except Exception as e:
  3371. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3372. self.options['tools_ncctools'] = ''
  3373. for t in range(len(ncctools)):
  3374. ncctools[t] *= sfactor
  3375. self.options['tools_ncctools'] += "%f," % ncctools[t]
  3376. elif dim == 'tools_solderpaste_tools':
  3377. sptools = []
  3378. try:
  3379. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3380. sptools = [eval(a) for a in tools_string if a != '']
  3381. except Exception as e:
  3382. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3383. self.options['tools_solderpaste_tools'] = ""
  3384. for t in range(len(sptools)):
  3385. sptools[t] *= sfactor
  3386. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  3387. elif dim == 'tools_solderpaste_xy_toolchange':
  3388. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3389. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3390. sp_coords[0] *= sfactor
  3391. sp_coords[1] *= sfactor
  3392. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  3393. elif dim == 'global_gridx' or dim == 'global_gridy':
  3394. if new_units == 'IN':
  3395. val = 0.1
  3396. try:
  3397. val = float(self.defaults[dim]) * sfactor
  3398. except Exception as e:
  3399. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3400. self.options[dim] = float('%.6f' % val)
  3401. else:
  3402. val = 0.1
  3403. try:
  3404. val = float(self.defaults[dim]) * sfactor
  3405. except Exception as e:
  3406. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3407. self.options[dim] = float('%.4f' % val)
  3408. else:
  3409. val = 0.1
  3410. try:
  3411. val = float(self.options[dim]) * sfactor
  3412. except Exception as e:
  3413. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  3414. self.options[dim] = val
  3415. def scale_defaults(sfactor):
  3416. for dim in dimensions:
  3417. if dim == 'excellon_toolchangexy':
  3418. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3419. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3420. coords_xy[0] *= sfactor
  3421. coords_xy[1] *= sfactor
  3422. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3423. elif dim == 'geometry_toolchangexy':
  3424. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3425. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3426. coords_xy[0] *= sfactor
  3427. coords_xy[1] *= sfactor
  3428. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3429. elif dim == 'geometry_cnctooldia':
  3430. tools_diameters = []
  3431. try:
  3432. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3433. tools_diameters = [eval(a) for a in tools_string if a != '']
  3434. except Exception as e:
  3435. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3436. self.defaults['geometry_cnctooldia'] = ''
  3437. for t in range(len(tools_diameters)):
  3438. tools_diameters[t] *= sfactor
  3439. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  3440. elif dim == 'tools_ncctools':
  3441. ncctools = []
  3442. try:
  3443. tools_string = self.defaults["tools_ncctools"].split(",")
  3444. ncctools = [eval(a) for a in tools_string if a != '']
  3445. except Exception as e:
  3446. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3447. self.defaults['tools_ncctools'] = ''
  3448. for t in range(len(ncctools)):
  3449. ncctools[t] *= sfactor
  3450. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  3451. elif dim == 'tools_solderpaste_tools':
  3452. sptools = []
  3453. try:
  3454. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3455. sptools = [eval(a) for a in tools_string if a != '']
  3456. except Exception as e:
  3457. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3458. self.defaults['tools_solderpaste_tools'] = ""
  3459. for t in range(len(sptools)):
  3460. sptools[t] *= sfactor
  3461. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  3462. elif dim == 'tools_solderpaste_xy_toolchange':
  3463. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3464. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3465. sp_coords[0] *= sfactor
  3466. sp_coords[1] *= sfactor
  3467. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  3468. elif dim == 'global_gridx' or dim == 'global_gridy':
  3469. if new_units == 'IN':
  3470. val = 0.1
  3471. try:
  3472. val = float(self.defaults[dim]) * sfactor
  3473. except Exception as e:
  3474. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3475. self.defaults[dim] = float('%.6f' % val)
  3476. else:
  3477. val = 0.1
  3478. try:
  3479. val = float(self.defaults[dim]) * sfactor
  3480. except Exception as e:
  3481. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3482. self.defaults[dim] = float('%.4f' % val)
  3483. else:
  3484. val = 0.1
  3485. try:
  3486. val = float(self.defaults[dim]) * sfactor
  3487. except Exception as e:
  3488. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3489. self.defaults[dim] = val
  3490. # The scaling factor depending on choice of units.
  3491. factor = 1/25.4
  3492. if new_units == 'MM':
  3493. factor = 25.4
  3494. # Changing project units. Warn user.
  3495. msgbox = QtWidgets.QMessageBox()
  3496. msgbox.setWindowTitle(_("Toggle Units"))
  3497. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  3498. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3499. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  3500. "properties of all objects to be scaled accordingly.\nContinue?"))
  3501. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3502. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3503. msgbox.setDefaultButton(bt_ok)
  3504. msgbox.exec_()
  3505. response = msgbox.clickedButton()
  3506. if response == bt_ok:
  3507. if no_pref is False:
  3508. self.options_read_form()
  3509. scale_options(factor)
  3510. self.options_write_form()
  3511. self.defaults_read_form()
  3512. scale_defaults(factor)
  3513. self.defaults_write_form(fl_units=new_units)
  3514. # save the defaults to file, some may assume that the conversion is enough and it's not
  3515. self.on_save_button()
  3516. self.should_we_save = True
  3517. # change this only if the workspace is active
  3518. if self.defaults['global_workspace'] is True:
  3519. self.plotcanvas.draw_workspace()
  3520. # adjust the grid values on the main toolbar
  3521. dec = 6 if new_units == 'IN'else 4
  3522. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  3523. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  3524. if not self.ui.grid_gap_link_cb.isChecked():
  3525. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  3526. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  3527. for obj in self.collection.get_list():
  3528. obj.convert_units(new_units)
  3529. # make that the properties stored in the object are also updated
  3530. self.object_changed.emit(obj)
  3531. obj.build_ui()
  3532. current = self.collection.get_active()
  3533. if current is not None:
  3534. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3535. if not isinstance(current, FlatCAMGeometry):
  3536. current.to_form()
  3537. self.plot_all()
  3538. self.inform.emit(_("[success] Converted units to %s") % new_units)
  3539. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  3540. self.set_screen_units(new_units)
  3541. else:
  3542. # Undo toggling
  3543. self.toggle_units_ignore = True
  3544. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3545. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3546. else:
  3547. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3548. self.toggle_units_ignore = False
  3549. self.inform.emit(_("[WARNING_NOTCL] Units conversion cancelled."))
  3550. self.options_read_form()
  3551. self.defaults_read_form()
  3552. def on_toggle_units_click(self):
  3553. try:
  3554. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3555. except (TypeError, AttributeError):
  3556. pass
  3557. if self.defaults["units"] == 'MM':
  3558. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3559. else:
  3560. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3561. self.on_toggle_units(no_pref=True)
  3562. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3563. lambda: self.on_toggle_units(no_pref=False))
  3564. def on_fullscreen(self):
  3565. self.report_usage("on_fullscreen()")
  3566. if self.toggle_fscreen is False:
  3567. if sys.platform == 'win32':
  3568. self.ui.showFullScreen()
  3569. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3570. tb.setVisible(False)
  3571. self.ui.splitter_left.setVisible(False)
  3572. self.toggle_fscreen = True
  3573. else:
  3574. if sys.platform == 'win32':
  3575. self.ui.showNormal()
  3576. self.restore_toolbar_view()
  3577. self.ui.splitter_left.setVisible(True)
  3578. self.toggle_fscreen = False
  3579. def on_toggle_plotarea(self):
  3580. self.report_usage("on_toggle_plotarea()")
  3581. try:
  3582. name = self.ui.plot_tab_area.widget(0).objectName()
  3583. except AttributeError:
  3584. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3585. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3586. self.ui.plot_tab_area.protectTab(0)
  3587. return
  3588. if name != 'plotarea':
  3589. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3590. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3591. self.ui.plot_tab_area.protectTab(0)
  3592. else:
  3593. self.ui.plot_tab_area.closeTab(0)
  3594. def on_toggle_notebook(self):
  3595. if self.ui.splitter.sizes()[0] == 0:
  3596. self.ui.splitter.setSizes([1, 1])
  3597. else:
  3598. self.ui.splitter.setSizes([0, 1])
  3599. def on_toggle_axis(self):
  3600. self.report_usage("on_toggle_axis()")
  3601. if self.toggle_axis is False:
  3602. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3603. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3604. self.plotcanvas.redraw()
  3605. self.toggle_axis = True
  3606. else:
  3607. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3608. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3609. self.plotcanvas.redraw()
  3610. self.toggle_axis = False
  3611. def on_toggle_grid(self):
  3612. self.report_usage("on_toggle_grid()")
  3613. self.ui.grid_snap_btn.trigger()
  3614. def on_options_combo_change(self, sel):
  3615. """
  3616. Called when the combo box to choose between application defaults and
  3617. project option changes value. The corresponding variables are
  3618. copied to the UI.
  3619. :param sel: The option index that was chosen.
  3620. :return: None
  3621. """
  3622. # combo_sel = self.ui.notebook.combo_options.get_active()
  3623. App.log.debug("Options --> %s" % sel)
  3624. # form = [self.defaults_form, self.options_form][sel]
  3625. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  3626. if sel == 0:
  3627. self.gen_form = self.ui.general_defaults_form
  3628. self.ger_form = self.ui.gerber_defaults_form
  3629. self.exc_form = self.ui.excellon_defaults_form
  3630. self.geo_form = self.ui.geometry_defaults_form
  3631. self.cnc_form = self.ui.cncjob_defaults_form
  3632. self.tools_form = self.ui.tools_defaults_form
  3633. elif sel == 1:
  3634. self.gen_form = self.ui.general_options_form
  3635. self.ger_form = self.ui.gerber_options_form
  3636. self.exc_form = self.ui.excellon_options_form
  3637. self.geo_form = self.ui.geometry_options_form
  3638. self.cnc_form = self.ui.cncjob_options_form
  3639. self.tools_form = self.ui.tools_options_form
  3640. else:
  3641. return
  3642. try:
  3643. self.ui.general_scroll_area.takeWidget()
  3644. except:
  3645. self.log.debug("Nothing to remove")
  3646. self.ui.general_scroll_area.setWidget(self.gen_form)
  3647. self.gen_form.show()
  3648. try:
  3649. self.ui.gerber_scroll_area.takeWidget()
  3650. except:
  3651. self.log.debug("Nothing to remove")
  3652. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  3653. self.ger_form.show()
  3654. try:
  3655. self.ui.excellon_scroll_area.takeWidget()
  3656. except:
  3657. self.log.debug("Nothing to remove")
  3658. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  3659. self.exc_form.show()
  3660. try:
  3661. self.ui.geometry_scroll_area.takeWidget()
  3662. except:
  3663. self.log.debug("Nothing to remove")
  3664. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  3665. self.geo_form.show()
  3666. try:
  3667. self.ui.cncjob_scroll_area.takeWidget()
  3668. except:
  3669. self.log.debug("Nothing to remove")
  3670. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  3671. self.cnc_form.show()
  3672. try:
  3673. self.ui.tools_scroll_area.takeWidget()
  3674. except:
  3675. self.log.debug("Nothing to remove")
  3676. self.ui.tools_scroll_area.setWidget(self.tools_form)
  3677. self.tools_form.show()
  3678. self.log.debug("Finished GUI form initialization.")
  3679. # self.options2form()
  3680. def on_excellon_defaults_button(self):
  3681. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  3682. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  3683. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  3684. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  3685. self.defaults_form_fields["excellon_zeros"].set_value('L')
  3686. self.defaults_form_fields["excellon_units"].set_value('INCH')
  3687. log.debug("Excellon app defaults loaded ...")
  3688. def on_excellon_options_button(self):
  3689. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  3690. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  3691. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  3692. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  3693. self.options_form_fields["excellon_zeros"].set_value('L')
  3694. self.options_form_fields["excellon_units"].set_value('INCH')
  3695. log.debug("Excellon options defaults loaded ...")
  3696. # Setting plot colors handlers
  3697. def on_pf_color_entry(self):
  3698. self.defaults['global_plot_fill'] = \
  3699. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  3700. self.defaults['global_plot_fill'][7:9]
  3701. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3702. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  3703. def on_pf_color_button(self):
  3704. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  3705. c_dialog = QtWidgets.QColorDialog()
  3706. plot_fill_color = c_dialog.getColor(initial=current_color)
  3707. if plot_fill_color.isValid() is False:
  3708. return
  3709. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3710. "background-color:%s" % str(plot_fill_color.name()))
  3711. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  3712. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  3713. self.defaults['global_plot_fill'] = new_val
  3714. def on_pf_color_spinner(self):
  3715. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  3716. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  3717. self.defaults['global_plot_fill'] = \
  3718. self.defaults['global_plot_fill'][:7] + \
  3719. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3720. self.defaults['global_plot_line'] = \
  3721. self.defaults['global_plot_line'][:7] + \
  3722. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3723. def on_pf_color_slider(self):
  3724. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  3725. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  3726. def on_pl_color_entry(self):
  3727. self.defaults['global_plot_line'] = \
  3728. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  3729. self.defaults['global_plot_line'][7:9]
  3730. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3731. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  3732. def on_pl_color_button(self):
  3733. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  3734. # print(current_color)
  3735. c_dialog = QtWidgets.QColorDialog()
  3736. plot_line_color = c_dialog.getColor(initial=current_color)
  3737. if plot_line_color.isValid() is False:
  3738. return
  3739. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3740. "background-color:%s" % str(plot_line_color.name()))
  3741. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  3742. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  3743. self.defaults['global_plot_line'] = new_val_line
  3744. # Setting selection colors (left - right) handlers
  3745. def on_sf_color_entry(self):
  3746. self.defaults['global_sel_fill'] = \
  3747. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  3748. self.defaults['global_sel_fill'][7:9]
  3749. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3750. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  3751. def on_sf_color_button(self):
  3752. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  3753. c_dialog = QtWidgets.QColorDialog()
  3754. plot_fill_color = c_dialog.getColor(initial=current_color)
  3755. if plot_fill_color.isValid() is False:
  3756. return
  3757. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3758. "background-color:%s" % str(plot_fill_color.name()))
  3759. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  3760. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  3761. self.defaults['global_sel_fill'] = new_val
  3762. def on_sf_color_spinner(self):
  3763. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  3764. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  3765. self.defaults['global_sel_fill'] = \
  3766. self.defaults['global_sel_fill'][:7] + \
  3767. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3768. self.defaults['global_sel_line'] = \
  3769. self.defaults['global_sel_line'][:7] + \
  3770. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3771. def on_sf_color_slider(self):
  3772. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  3773. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  3774. def on_sl_color_entry(self):
  3775. self.defaults['global_sel_line'] = \
  3776. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  3777. self.defaults['global_sel_line'][7:9]
  3778. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3779. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  3780. def on_sl_color_button(self):
  3781. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  3782. c_dialog = QtWidgets.QColorDialog()
  3783. plot_line_color = c_dialog.getColor(initial=current_color)
  3784. if plot_line_color.isValid() is False:
  3785. return
  3786. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3787. "background-color:%s" % str(plot_line_color.name()))
  3788. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  3789. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  3790. self.defaults['global_sel_line'] = new_val_line
  3791. # Setting selection colors (right - left) handlers
  3792. def on_alt_sf_color_entry(self):
  3793. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  3794. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  3795. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3796. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  3797. def on_alt_sf_color_button(self):
  3798. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  3799. c_dialog = QtWidgets.QColorDialog()
  3800. plot_fill_color = c_dialog.getColor(initial=current_color)
  3801. if plot_fill_color.isValid() is False:
  3802. return
  3803. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3804. "background-color:%s" % str(plot_fill_color.name()))
  3805. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  3806. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  3807. self.defaults['global_alt_sel_fill'] = new_val
  3808. def on_alt_sf_color_spinner(self):
  3809. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  3810. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  3811. self.defaults['global_alt_sel_fill'] = \
  3812. self.defaults['global_alt_sel_fill'][:7] + \
  3813. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3814. self.defaults['global_alt_sel_line'] = \
  3815. self.defaults['global_alt_sel_line'][:7] + \
  3816. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3817. def on_alt_sf_color_slider(self):
  3818. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  3819. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  3820. def on_alt_sl_color_entry(self):
  3821. self.defaults['global_alt_sel_line'] = \
  3822. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  3823. self.defaults['global_alt_sel_line'][7:9]
  3824. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3825. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  3826. def on_alt_sl_color_button(self):
  3827. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  3828. c_dialog = QtWidgets.QColorDialog()
  3829. plot_line_color = c_dialog.getColor(initial=current_color)
  3830. if plot_line_color.isValid() is False:
  3831. return
  3832. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3833. "background-color:%s" % str(plot_line_color.name()))
  3834. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  3835. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  3836. self.defaults['global_alt_sel_line'] = new_val_line
  3837. # Setting Editor colors
  3838. def on_draw_color_entry(self):
  3839. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3840. .draw_color_entry.get_value()
  3841. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3842. "background-color:%s" % str(self.defaults['global_draw_color']))
  3843. def on_draw_color_button(self):
  3844. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  3845. c_dialog = QtWidgets.QColorDialog()
  3846. draw_color = c_dialog.getColor(initial=current_color)
  3847. if draw_color.isValid() is False:
  3848. return
  3849. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3850. "background-color:%s" % str(draw_color.name()))
  3851. new_val = str(draw_color.name())
  3852. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  3853. self.defaults['global_draw_color'] = new_val
  3854. def on_sel_draw_color_entry(self):
  3855. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3856. .sel_draw_color_entry.get_value()
  3857. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3858. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3859. def on_sel_draw_color_button(self):
  3860. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3861. c_dialog = QtWidgets.QColorDialog()
  3862. sel_draw_color = c_dialog.getColor(initial=current_color)
  3863. if sel_draw_color.isValid() is False:
  3864. return
  3865. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3866. "background-color:%s" % str(sel_draw_color.name()))
  3867. new_val_sel = str(sel_draw_color.name())
  3868. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3869. self.defaults['global_sel_draw_color'] = new_val_sel
  3870. def on_proj_color_entry(self):
  3871. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  3872. .proj_color_entry.get_value()
  3873. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3874. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  3875. def on_proj_color_button(self):
  3876. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  3877. c_dialog = QtWidgets.QColorDialog()
  3878. proj_color = c_dialog.getColor(initial=current_color)
  3879. if proj_color.isValid() is False:
  3880. return
  3881. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3882. "background-color:%s" % str(proj_color.name()))
  3883. new_val_sel = str(proj_color.name())
  3884. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  3885. self.defaults['global_proj_item_color'] = new_val_sel
  3886. def on_proj_color_dis_entry(self):
  3887. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  3888. .proj_color_dis_entry.get_value()
  3889. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3890. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  3891. def on_proj_color_dis_button(self):
  3892. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  3893. c_dialog = QtWidgets.QColorDialog()
  3894. proj_color = c_dialog.getColor(initial=current_color)
  3895. if proj_color.isValid() is False:
  3896. return
  3897. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3898. "background-color:%s" % str(proj_color.name()))
  3899. new_val_sel = str(proj_color.name())
  3900. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  3901. self.defaults['global_proj_item_dis_color'] = new_val_sel
  3902. def on_annotation_fontcolor_entry(self):
  3903. self.defaults['cncjob_annotation_fontcolor'] = \
  3904. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.get_value()
  3905. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  3906. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  3907. def on_annotation_fontcolor_button(self):
  3908. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  3909. c_dialog = QtWidgets.QColorDialog()
  3910. annotation_color = c_dialog.getColor(initial=current_color)
  3911. if annotation_color.isValid() is False:
  3912. return
  3913. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  3914. "background-color:%s" % str(annotation_color.name()))
  3915. new_val_sel = str(annotation_color.name())
  3916. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(new_val_sel)
  3917. self.defaults['global_proj_item_dis_color'] = new_val_sel
  3918. def on_notebook_tab_rmb_click(self, checked):
  3919. self.ui.notebook.set_detachable(val=checked)
  3920. self.defaults["global_tabs_detachable"] = checked
  3921. self.ui.plot_tab_area.set_detachable(val=checked)
  3922. self.defaults["global_tabs_detachable"] = checked
  3923. def on_deselect_all(self):
  3924. self.collection.set_all_inactive()
  3925. self.delete_selection_shape()
  3926. def on_workspace_modified(self):
  3927. self.save_defaults(silent=True)
  3928. self.plotcanvas.draw_workspace()
  3929. def on_workspace(self):
  3930. self.report_usage("on_workspace()")
  3931. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3932. self.plotcanvas.restore_workspace()
  3933. else:
  3934. self.plotcanvas.delete_workspace()
  3935. self.save_defaults(silent=True)
  3936. def on_workspace_menu(self):
  3937. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3938. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3939. else:
  3940. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3941. self.on_workspace()
  3942. def on_layout(self, index=None, lay=None):
  3943. self.report_usage("on_layout()")
  3944. if lay:
  3945. current_layout = lay
  3946. else:
  3947. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  3948. settings = QSettings("Open Source", "FlatCAM")
  3949. settings.setValue('layout', current_layout)
  3950. # This will write the setting to the platform specific storage.
  3951. del settings
  3952. # first remove the toolbars:
  3953. try:
  3954. self.ui.removeToolBar(self.ui.toolbarfile)
  3955. self.ui.removeToolBar(self.ui.toolbargeo)
  3956. self.ui.removeToolBar(self.ui.toolbarview)
  3957. self.ui.removeToolBar(self.ui.toolbarshell)
  3958. self.ui.removeToolBar(self.ui.toolbartools)
  3959. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3960. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3961. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  3962. self.ui.removeToolBar(self.ui.snap_toolbar)
  3963. self.ui.removeToolBar(self.ui.toolbarshell)
  3964. except Exception as e:
  3965. pass
  3966. if current_layout == 'standard':
  3967. # ## TOOLBAR INSTALLATION # ##
  3968. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3969. self.ui.toolbarfile.setObjectName('File_TB')
  3970. self.ui.addToolBar(self.ui.toolbarfile)
  3971. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3972. self.ui.toolbargeo.setObjectName('Edit_TB')
  3973. self.ui.addToolBar(self.ui.toolbargeo)
  3974. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3975. self.ui.toolbarview.setObjectName('View_TB')
  3976. self.ui.addToolBar(self.ui.toolbarview)
  3977. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3978. self.ui.toolbarshell.setObjectName('Shell_TB')
  3979. self.ui.addToolBar(self.ui.toolbarshell)
  3980. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3981. self.ui.toolbartools.setObjectName('Tools_TB')
  3982. self.ui.addToolBar(self.ui.toolbartools)
  3983. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3984. self.ui.exc_edit_toolbar.setVisible(False)
  3985. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3986. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3987. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3988. self.ui.geo_edit_toolbar.setVisible(False)
  3989. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3990. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3991. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3992. self.ui.grb_edit_toolbar.setVisible(False)
  3993. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3994. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  3995. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3996. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3997. # self.ui.snap_toolbar.setMaximumHeight(30)
  3998. self.ui.addToolBar(self.ui.snap_toolbar)
  3999. self.ui.corner_snap_btn.setVisible(False)
  4000. self.ui.snap_magnet.setVisible(False)
  4001. elif current_layout == 'compact':
  4002. # ## TOOLBAR INSTALLATION # ##
  4003. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4004. self.ui.toolbarfile.setObjectName('File_TB')
  4005. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  4006. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4007. self.ui.toolbargeo.setObjectName('Edit_TB')
  4008. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  4009. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4010. self.ui.toolbarview.setObjectName('View_TB')
  4011. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  4012. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4013. self.ui.toolbarshell.setObjectName('Shell_TB')
  4014. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  4015. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4016. self.ui.toolbartools.setObjectName('Tools_TB')
  4017. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  4018. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4019. # self.ui.geo_edit_toolbar.setVisible(False)
  4020. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4021. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  4022. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4023. # self.ui.grb_edit_toolbar.setVisible(False)
  4024. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4025. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  4026. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4027. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4028. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  4029. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4030. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4031. self.ui.snap_toolbar.setMaximumHeight(30)
  4032. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  4033. self.ui.corner_snap_btn.setVisible(True)
  4034. self.ui.snap_magnet.setVisible(True)
  4035. # add all the actions to the toolbars
  4036. self.ui.populate_toolbars()
  4037. # reconnect all the signals to the toolbar actions
  4038. self.connect_toolbar_signals()
  4039. self.ui.grid_snap_btn.setChecked(True)
  4040. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  4041. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  4042. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  4043. self.ui.grid_gap_link_cb.setChecked(True)
  4044. def on_cnc_custom_parameters(self, signal_text):
  4045. if signal_text == 'Parameters':
  4046. return
  4047. else:
  4048. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4049. def on_save_button(self):
  4050. log.debug("App.on_save_button() --> Saving preferences to file.")
  4051. self.preferences_changed_flag = False
  4052. self.save_defaults(silent=False)
  4053. # load the defaults so they are updated into the app
  4054. self.load_defaults(filename='current_defaults')
  4055. # Re-fresh project options
  4056. self.on_options_app2project()
  4057. # save the notebook font size
  4058. settings = QSettings("Open Source", "FlatCAM")
  4059. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4060. settings.setValue('notebook_font_size', fsize)
  4061. # save the axis font size
  4062. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4063. settings.setValue('axis_font_size', g_fsize)
  4064. # This will write the setting to the platform specific storage.
  4065. del settings
  4066. def handlePrint(self):
  4067. self.report_usage("handlePrint()")
  4068. dialog = QtPrintSupport.QPrintDialog()
  4069. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  4070. self.ui.code_editor.document().print_(dialog.printer())
  4071. def handlePreview(self):
  4072. self.report_usage("handlePreview()")
  4073. dialog = QtPrintSupport.QPrintPreviewDialog()
  4074. dialog.paintRequested.connect(self.ui.code_editor.print_)
  4075. dialog.exec_()
  4076. def handleTextChanged(self):
  4077. # enable = not self.ui.code_editor.document().isEmpty()
  4078. # self.ui.buttonPrint.setEnabled(enable)
  4079. # self.ui.buttonPreview.setEnabled(enable)
  4080. pass
  4081. def handleOpen(self, filt=None):
  4082. self.report_usage("handleOpen()")
  4083. if filt:
  4084. _filter_ = filt
  4085. else:
  4086. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4087. "All Files (*.*)"
  4088. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  4089. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  4090. if path:
  4091. file = QtCore.QFile(path)
  4092. if file.open(QtCore.QIODevice.ReadOnly):
  4093. stream = QtCore.QTextStream(file)
  4094. self.gcode_edited = stream.readAll()
  4095. self.ui.code_editor.setPlainText(self.gcode_edited)
  4096. file.close()
  4097. def handleSaveGCode(self, name=None, filt=None):
  4098. self.report_usage("handleSaveGCode()")
  4099. if filt:
  4100. _filter_ = filt
  4101. else:
  4102. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4103. "All Files (*.*)"
  4104. if name:
  4105. obj_name = name
  4106. else:
  4107. try:
  4108. obj_name = self.collection.get_active().options['name']
  4109. except AttributeError:
  4110. obj_name = 'file'
  4111. if filt is None:
  4112. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  4113. try:
  4114. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  4115. caption=_("Export G-Code ..."),
  4116. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  4117. filter=_filter_
  4118. )[0])
  4119. except TypeError:
  4120. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  4121. if filename == "":
  4122. self.inform.emit(_("[WARNING_NOTCL] Export Code cancelled."))
  4123. return
  4124. else:
  4125. try:
  4126. my_gcode = self.ui.code_editor.toPlainText()
  4127. with open(filename, 'w') as f:
  4128. for line in my_gcode:
  4129. f.write(line)
  4130. except FileNotFoundError:
  4131. self.inform.emit(_("[WARNING] No such file or directory"))
  4132. return
  4133. except PermissionError:
  4134. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  4135. "Most likely another app is holding the file open and not accessible."))
  4136. return
  4137. # Just for adding it to the recent files list.
  4138. if self.defaults["global_open_style"] is False:
  4139. self.file_opened.emit("cncjob", filename)
  4140. self.file_saved.emit("cncjob", filename)
  4141. self.inform.emit(_("Saved to: %s") % filename)
  4142. def handleFindGCode(self):
  4143. self.report_usage("handleFindGCode()")
  4144. flags = QtGui.QTextDocument.FindCaseSensitively
  4145. text_to_be_found = self.ui.entryFind.get_value()
  4146. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  4147. if r is False:
  4148. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4149. def handleReplaceGCode(self):
  4150. self.report_usage("handleReplaceGCode()")
  4151. old = self.ui.entryFind.get_value()
  4152. new = self.ui.entryReplace.get_value()
  4153. if self.ui.sel_all_cb.isChecked():
  4154. while True:
  4155. cursor = self.ui.code_editor.textCursor()
  4156. cursor.beginEditBlock()
  4157. flags = QtGui.QTextDocument.FindCaseSensitively
  4158. # self.ui.editor is the QPlainTextEdit
  4159. r = self.ui.code_editor.find(str(old), flags)
  4160. if r:
  4161. qc = self.ui.code_editor.textCursor()
  4162. if qc.hasSelection():
  4163. qc.insertText(new)
  4164. else:
  4165. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4166. break
  4167. # Mark end of undo block
  4168. cursor.endEditBlock()
  4169. else:
  4170. cursor = self.ui.code_editor.textCursor()
  4171. cursor.beginEditBlock()
  4172. qc = self.ui.code_editor.textCursor()
  4173. if qc.hasSelection():
  4174. qc.insertText(new)
  4175. # Mark end of undo block
  4176. cursor.endEditBlock()
  4177. def on_tool_add_keypress(self):
  4178. # ## Current application units in Upper Case
  4179. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4180. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4181. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4182. if notebook_widget_name == 'selected_tab':
  4183. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4184. # Tool add works for Geometry only if Advanced is True in Preferences
  4185. if self.defaults["global_app_level"] == 'a':
  4186. tool_add_popup = FCInputDialog(title="New Tool ...",
  4187. text='Enter a Tool Diameter:',
  4188. min=0.0000, max=99.9999, decimals=4)
  4189. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4190. val, ok = tool_add_popup.get_value()
  4191. if ok:
  4192. if float(val) == 0:
  4193. self.inform.emit(
  4194. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4195. return
  4196. self.collection.get_active().on_tool_add(dia=float(val))
  4197. else:
  4198. self.inform.emit(
  4199. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4200. else:
  4201. msgbox = QtWidgets.QMessageBox()
  4202. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4203. "Go to Preferences -> General - Show Advanced Options."))
  4204. msgbox.setWindowTitle("Tool adding ...")
  4205. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  4206. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4207. msgbox.setDefaultButton(bt_ok)
  4208. msgbox.exec_()
  4209. # work only if the notebook tab on focus is the Tools_Tab
  4210. if notebook_widget_name == 'tool_tab':
  4211. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4212. tool_add_popup = FCInputDialog(title="New Tool ...",
  4213. text='Enter a Tool Diameter:',
  4214. min=0.0000, max=99.9999, decimals=4)
  4215. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4216. val, ok = tool_add_popup.get_value()
  4217. # and only if the tool is NCC Tool
  4218. if tool_widget == self.ncclear_tool.toolName:
  4219. if ok:
  4220. if float(val) == 0:
  4221. self.inform.emit(
  4222. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4223. return
  4224. self.ncclear_tool.on_tool_add(dia=float(val))
  4225. else:
  4226. self.inform.emit(
  4227. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4228. # and only if the tool is Paint Area Tool
  4229. elif tool_widget == self.paint_tool.toolName:
  4230. if ok:
  4231. if float(val) == 0:
  4232. self.inform.emit(
  4233. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4234. return
  4235. self.paint_tool.on_tool_add(dia=float(val))
  4236. else:
  4237. self.inform.emit(
  4238. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4239. # and only if the tool is Solder Paste Dispensing Tool
  4240. elif tool_widget == self.paste_tool.toolName:
  4241. if ok:
  4242. if float(val) == 0:
  4243. self.inform.emit(
  4244. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4245. return
  4246. self.paste_tool.on_tool_add(dia=float(val))
  4247. else:
  4248. self.inform.emit(
  4249. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4250. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4251. # See description bellow.
  4252. def on_delete_keypress(self):
  4253. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4254. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4255. if notebook_widget_name == 'selected_tab':
  4256. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4257. self.collection.get_active().on_tool_delete()
  4258. # work only if the notebook tab on focus is the Tools_Tab
  4259. elif notebook_widget_name == 'tool_tab':
  4260. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4261. # and only if the tool is NCC Tool
  4262. if tool_widget == self.ncclear_tool.toolName:
  4263. self.ncclear_tool.on_tool_delete()
  4264. # and only if the tool is Paint Tool
  4265. elif tool_widget == self.paint_tool.toolName:
  4266. self.paint_tool.on_tool_delete()
  4267. # and only if the tool is Solder Paste Dispensing Tool
  4268. elif tool_widget == self.paste_tool.toolName:
  4269. self.paste_tool.on_tool_delete()
  4270. else:
  4271. self.on_delete()
  4272. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4273. # some screens you have to be careful where you hover with your mouse.
  4274. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4275. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4276. # Complicated, I know :)
  4277. def on_delete(self):
  4278. """
  4279. Delete the currently selected FlatCAMObjs.
  4280. :return: None
  4281. """
  4282. self.report_usage("on_delete()")
  4283. response = None
  4284. bt_ok = None
  4285. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4286. # a geometry object before we update it.
  4287. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4288. and self.grb_editor.editor_active is False:
  4289. if self.defaults["global_delete_confirmation"] is True:
  4290. msgbox = QtWidgets.QMessageBox()
  4291. msgbox.setWindowTitle(_("Delete objects"))
  4292. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  4293. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4294. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4295. "the selected objects?"))
  4296. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4297. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4298. msgbox.setDefaultButton(bt_ok)
  4299. msgbox.exec_()
  4300. response = msgbox.clickedButton()
  4301. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  4302. if self.collection.get_active():
  4303. self.log.debug("App.on_delete()")
  4304. while self.collection.get_active():
  4305. obj_active = self.collection.get_active()
  4306. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  4307. if isinstance(obj_active, FlatCAMGerber):
  4308. for el in obj_active.mark_shapes:
  4309. obj_active.mark_shapes[el].clear(update=True)
  4310. obj_active.mark_shapes[el].enabled = False
  4311. obj_active.mark_shapes[el] = None
  4312. elif isinstance(obj_active, FlatCAMCNCjob):
  4313. try:
  4314. obj_active.annotation.clear(update=True)
  4315. obj_active.annotation.enabled = False
  4316. except AttributeError:
  4317. pass
  4318. self.delete_first_selected()
  4319. self.inform.emit(_("Object(s) deleted ..."))
  4320. # make sure that the selection shape is deleted, too
  4321. self.delete_selection_shape()
  4322. else:
  4323. self.inform.emit(_("Failed. No object(s) selected..."))
  4324. else:
  4325. self.inform.emit(_("Save the work in Editor and try again ..."))
  4326. def delete_first_selected(self):
  4327. # Keep this for later
  4328. try:
  4329. sel_obj = self.collection.get_active()
  4330. name = sel_obj.options["name"]
  4331. except AttributeError:
  4332. self.log.debug("Nothing selected for deletion")
  4333. return
  4334. # Remove from dictionary
  4335. self.collection.delete_active()
  4336. # Clear form
  4337. self.setup_component_editor()
  4338. self.inform.emit("Object deleted: %s" % name)
  4339. def on_set_origin(self):
  4340. """
  4341. Set the origin to the left mouse click position
  4342. :return: None
  4343. """
  4344. # display the message for the user
  4345. # and ask him to click on the desired position
  4346. self.report_usage("on_set_origin()")
  4347. self.inform.emit(_('Click to set the origin ...'))
  4348. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  4349. def on_jump_to(self, custom_location=None, fit_center=True):
  4350. """
  4351. Jump to a location by setting the mouse cursor location
  4352. :return:
  4353. """
  4354. self.report_usage("on_jump_to()")
  4355. if not custom_location:
  4356. dia_box = Dialog_box(title=_("Jump to ..."),
  4357. label=_("Enter the coordinates in format X,Y:"),
  4358. icon=QtGui.QIcon('share/jump_to16.png'))
  4359. if dia_box.ok is True:
  4360. try:
  4361. location = eval(dia_box.location)
  4362. if not isinstance(location, tuple):
  4363. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4364. return
  4365. except:
  4366. return
  4367. else:
  4368. return
  4369. else:
  4370. location = custom_location
  4371. if fit_center:
  4372. self.plotcanvas.fit_center(loc=location)
  4373. cursor = QtGui.QCursor()
  4374. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4375. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  4376. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  4377. self.inform.emit(_("[success] Done."))
  4378. return location
  4379. def on_copy_object(self):
  4380. self.report_usage("on_copy_object()")
  4381. def initialize(obj_init, app):
  4382. obj_init.solid_geometry = obj.solid_geometry
  4383. try:
  4384. obj_init.follow_geometry = obj.follow_geometry
  4385. except AttributeError:
  4386. pass
  4387. try:
  4388. obj_init.apertures = obj.apertures
  4389. except AttributeError:
  4390. pass
  4391. try:
  4392. if obj.tools:
  4393. obj_init.tools = obj.tools
  4394. except Exception as e:
  4395. log.debug("App.on_copy_object() --> %s" % str(e))
  4396. def initialize_excellon(obj_init, app):
  4397. obj_init.tools = obj.tools
  4398. # drills are offset, so they need to be deep copied
  4399. obj_init.drills = deepcopy(obj.drills)
  4400. # slots are offset, so they need to be deep copied
  4401. obj_init.slots = deepcopy(obj.slots)
  4402. obj_init.create_geometry()
  4403. for obj in self.collection.get_selected():
  4404. obj_name = obj.options["name"]
  4405. try:
  4406. if isinstance(obj, FlatCAMExcellon):
  4407. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4408. elif isinstance(obj, FlatCAMGerber):
  4409. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4410. elif isinstance(obj, FlatCAMGeometry):
  4411. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4412. except Exception as e:
  4413. return "Operation failed: %s" % str(e)
  4414. def on_copy_object2(self, custom_name):
  4415. def initialize_geometry(obj_init, app):
  4416. obj_init.solid_geometry = obj.solid_geometry
  4417. try:
  4418. obj_init.follow_geometry = obj.follow_geometry
  4419. except AttributeError:
  4420. pass
  4421. try:
  4422. obj_init.apertures = obj.apertures
  4423. except AttributeError:
  4424. pass
  4425. try:
  4426. if obj.tools:
  4427. obj_init.tools = obj.tools
  4428. except Exception as e:
  4429. log.debug("on_copy_object2() --> %s" % str(e))
  4430. def initialize_gerber(obj_init, app):
  4431. obj_init.solid_geometry = obj.solid_geometry
  4432. obj_init.apertures = deepcopy(obj.apertures)
  4433. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4434. def initialize_excellon(obj_init, app):
  4435. obj_init.tools = obj.tools
  4436. # drills are offset, so they need to be deep copied
  4437. obj_init.drills = deepcopy(obj.drills)
  4438. # slots are offset, so they need to be deep copied
  4439. obj_init.slots = deepcopy(obj.slots)
  4440. obj_init.create_geometry()
  4441. for obj in self.collection.get_selected():
  4442. obj_name = obj.options["name"]
  4443. try:
  4444. if isinstance(obj, FlatCAMExcellon):
  4445. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4446. elif isinstance(obj, FlatCAMGerber):
  4447. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4448. elif isinstance(obj, FlatCAMGeometry):
  4449. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4450. except Exception as e:
  4451. return "Operation failed: %s" % str(e)
  4452. def on_rename_object(self, text):
  4453. self.report_usage("on_rename_object()")
  4454. named_obj = self.collection.get_active()
  4455. for obj in named_obj:
  4456. if obj is list:
  4457. self.on_rename_object(text)
  4458. else:
  4459. try:
  4460. obj.options['name'] = text
  4461. except Exception as e:
  4462. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4463. def convert_any2geo(self):
  4464. self.report_usage("convert_any2geo()")
  4465. def initialize(obj_init, app):
  4466. obj_init.solid_geometry = obj.solid_geometry
  4467. try:
  4468. obj_init.follow_geometry = obj.follow_geometry
  4469. except AttributeError:
  4470. pass
  4471. try:
  4472. obj_init.apertures = obj.apertures
  4473. except AttributeError:
  4474. pass
  4475. try:
  4476. if obj.tools:
  4477. obj_init.tools = obj.tools
  4478. except AttributeError:
  4479. pass
  4480. def initialize_excellon(obj_init, app):
  4481. # objs = self.collection.get_selected()
  4482. # FlatCAMGeometry.merge(objs, obj)
  4483. solid_geo = []
  4484. for tool in obj.tools:
  4485. for geo in obj.tools[tool]['solid_geometry']:
  4486. solid_geo.append(geo)
  4487. obj_init.solid_geometry = deepcopy(solid_geo)
  4488. if not self.collection.get_selected():
  4489. log.warning("App.convert_any2geo --> No object selected")
  4490. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4491. return
  4492. for obj in self.collection.get_selected():
  4493. obj_name = obj.options["name"]
  4494. try:
  4495. if isinstance(obj, FlatCAMExcellon):
  4496. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4497. else:
  4498. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4499. except Exception as e:
  4500. return "Operation failed: %s" % str(e)
  4501. def convert_any2gerber(self):
  4502. self.report_usage("convert_any2gerber()")
  4503. def initialize_geometry(obj_init, app):
  4504. apertures = {}
  4505. apid = 0
  4506. apertures[str(apid)] = {}
  4507. apertures[str(apid)]['geometry'] = []
  4508. for obj_orig in obj.solid_geometry:
  4509. new_elem = dict()
  4510. new_elem['solid'] = obj_orig
  4511. new_elem['follow'] = obj_orig.exterior
  4512. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4513. apertures[str(apid)]['size'] = 0.0
  4514. apertures[str(apid)]['type'] = 'C'
  4515. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4516. obj_init.apertures = deepcopy(apertures)
  4517. def initialize_excellon(obj_init, app):
  4518. apertures = {}
  4519. apid = 10
  4520. for tool in obj.tools:
  4521. apertures[str(apid)] = {}
  4522. apertures[str(apid)]['geometry'] = []
  4523. for geo in obj.tools[tool]['solid_geometry']:
  4524. new_el = dict()
  4525. new_el['solid'] = geo
  4526. new_el['follow'] = geo.exterior
  4527. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4528. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4529. apertures[str(apid)]['type'] = 'C'
  4530. apid += 1
  4531. # create solid_geometry
  4532. solid_geometry = []
  4533. for apid in apertures:
  4534. for geo_el in apertures[apid]['geometry']:
  4535. solid_geometry.append(geo_el['solid'])
  4536. solid_geometry = MultiPolygon(solid_geometry)
  4537. solid_geometry = solid_geometry.buffer(0.0000001)
  4538. obj_init.solid_geometry = deepcopy(solid_geometry)
  4539. obj_init.apertures = deepcopy(apertures)
  4540. # clear the working objects (perhaps not necessary due of Python GC)
  4541. apertures.clear()
  4542. if not self.collection.get_selected():
  4543. log.warning("App.convert_any2gerber --> No object selected")
  4544. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4545. return
  4546. for obj in self.collection.get_selected():
  4547. obj_name = obj.options["name"]
  4548. try:
  4549. if isinstance(obj, FlatCAMExcellon):
  4550. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4551. elif isinstance(obj, FlatCAMGeometry):
  4552. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4553. else:
  4554. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4555. except Exception as e:
  4556. return "Operation failed: %s" % str(e)
  4557. def on_set_zero_click(self, event):
  4558. # this function will be available only for mouse left click
  4559. pos = []
  4560. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  4561. if event.button == 1:
  4562. if self.grid_status() == True:
  4563. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4564. else:
  4565. pos = pos_canvas
  4566. x = 0 - pos[0]
  4567. y = 0 - pos[1]
  4568. for obj in self.collection.get_list():
  4569. obj.offset((x, y))
  4570. self.object_changed.emit(obj)
  4571. obj.plot()
  4572. # Update the object bounding box options
  4573. a, b, c, d = obj.bounds()
  4574. obj.options['xmin'] = a
  4575. obj.options['ymin'] = b
  4576. obj.options['xmax'] = c
  4577. obj.options['ymax'] = d
  4578. # self.plot_all(zoom=False)
  4579. self.inform.emit(_('[success] Origin set ...'))
  4580. self.plotcanvas.fit_view()
  4581. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  4582. self.should_we_save = True
  4583. def on_selectall(self):
  4584. self.report_usage("on_selectall()")
  4585. # delete the possible selection box around a possible selected object
  4586. self.delete_selection_shape()
  4587. for name in self.collection.get_names():
  4588. self.collection.set_active(name)
  4589. curr_sel_obj = self.collection.get_by_name(name)
  4590. # create the selection box around the selected object
  4591. if self.defaults['global_selection_shape'] is True:
  4592. self.draw_selection_shape(curr_sel_obj)
  4593. def on_preferences(self):
  4594. # add the tab if it was closed
  4595. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4596. # delete the absolute and relative position and messages in the infobar
  4597. self.ui.position_label.setText("")
  4598. self.ui.rel_position_label.setText("")
  4599. # Switch plot_area to preferences page
  4600. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4601. self.ui.show()
  4602. # this disconnect() is done so the slot will be connected only once
  4603. try:
  4604. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  4605. except (TypeError, AttributeError):
  4606. pass
  4607. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  4608. # detect changes in the preferences
  4609. for idx in range(self.ui.pref_tab_area.count()):
  4610. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4611. try:
  4612. try:
  4613. tb.textEdited.disconnect(self.on_preferences_edited)
  4614. except (TypeError, AttributeError):
  4615. pass
  4616. tb.textEdited.connect(self.on_preferences_edited)
  4617. except AttributeError:
  4618. pass
  4619. try:
  4620. try:
  4621. tb.modificationChanged.disconnect(self.on_preferences_edited)
  4622. except (TypeError, AttributeError):
  4623. pass
  4624. tb.modificationChanged.connect(self.on_preferences_edited)
  4625. except AttributeError:
  4626. pass
  4627. try:
  4628. try:
  4629. tb.toggled.disconnect(self.on_preferences_edited)
  4630. except (TypeError, AttributeError):
  4631. pass
  4632. tb.toggled.connect(self.on_preferences_edited)
  4633. except AttributeError:
  4634. pass
  4635. try:
  4636. try:
  4637. tb.valueChanged.disconnect(self.on_preferences_edited)
  4638. except (TypeError, AttributeError):
  4639. pass
  4640. tb.valueChanged.connect(self.on_preferences_edited)
  4641. except AttributeError:
  4642. pass
  4643. try:
  4644. try:
  4645. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  4646. except (TypeError, AttributeError):
  4647. pass
  4648. tb.currentIndexChanged.connect(self.on_preferences_edited)
  4649. except AttributeError:
  4650. pass
  4651. def on_preferences_edited(self):
  4652. self.inform.emit(_("[WARNING_NOTCL] Preferences edited but not saved."))
  4653. self.preferences_changed_flag = True
  4654. def on_preferences_closed(self):
  4655. # disconnect
  4656. for idx in range(self.ui.pref_tab_area.count()):
  4657. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4658. try:
  4659. tb.textEdited.disconnect(self.on_preferences_edited)
  4660. except (TypeError, AttributeError):
  4661. pass
  4662. try:
  4663. tb.modificationChanged.disconnect(self.on_preferences_edited)
  4664. except (TypeError, AttributeError):
  4665. pass
  4666. try:
  4667. tb.toggled.disconnect(self.on_preferences_edited)
  4668. except (TypeError, AttributeError):
  4669. pass
  4670. try:
  4671. tb.valueChanged.disconnect(self.on_preferences_edited)
  4672. except (TypeError, AttributeError):
  4673. pass
  4674. try:
  4675. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  4676. except (TypeError, AttributeError):
  4677. pass
  4678. if self.preferences_changed_flag is True:
  4679. msgbox = QtWidgets.QMessageBox()
  4680. msgbox.setText(_("One or more values are changed.\n"
  4681. "Do you want to save the Preferences?"))
  4682. msgbox.setWindowTitle(_("Save Preferences"))
  4683. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4684. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4685. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4686. msgbox.setDefaultButton(bt_yes)
  4687. msgbox.exec_()
  4688. response = msgbox.clickedButton()
  4689. if response == bt_yes:
  4690. self.on_save_button()
  4691. self.inform.emit(_("[success] Preferences saved."))
  4692. else:
  4693. self.preferences_changed_flag = False
  4694. return
  4695. def on_flipy(self):
  4696. self.report_usage("on_flipy()")
  4697. obj_list = self.collection.get_selected()
  4698. xminlist = []
  4699. yminlist = []
  4700. xmaxlist = []
  4701. ymaxlist = []
  4702. if not obj_list:
  4703. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  4704. else:
  4705. try:
  4706. # first get a bounding box to fit all
  4707. for obj in obj_list:
  4708. xmin, ymin, xmax, ymax = obj.bounds()
  4709. xminlist.append(xmin)
  4710. yminlist.append(ymin)
  4711. xmaxlist.append(xmax)
  4712. ymaxlist.append(ymax)
  4713. # get the minimum x,y and maximum x,y for all objects selected
  4714. xminimal = min(xminlist)
  4715. yminimal = min(yminlist)
  4716. xmaximal = max(xmaxlist)
  4717. ymaximal = max(ymaxlist)
  4718. px = 0.5 * (xminimal + xmaximal)
  4719. py = 0.5 * (yminimal + ymaximal)
  4720. # execute mirroring
  4721. for obj in obj_list:
  4722. obj.mirror('X', [px, py])
  4723. obj.plot()
  4724. self.object_changed.emit(obj)
  4725. self.inform.emit(_("[success] Flip on Y axis done."))
  4726. except Exception as e:
  4727. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4728. return
  4729. def on_flipx(self):
  4730. self.report_usage("on_flipx()")
  4731. obj_list = self.collection.get_selected()
  4732. xminlist = []
  4733. yminlist = []
  4734. xmaxlist = []
  4735. ymaxlist = []
  4736. if not obj_list:
  4737. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  4738. else:
  4739. try:
  4740. # first get a bounding box to fit all
  4741. for obj in obj_list:
  4742. xmin, ymin, xmax, ymax = obj.bounds()
  4743. xminlist.append(xmin)
  4744. yminlist.append(ymin)
  4745. xmaxlist.append(xmax)
  4746. ymaxlist.append(ymax)
  4747. # get the minimum x,y and maximum x,y for all objects selected
  4748. xminimal = min(xminlist)
  4749. yminimal = min(yminlist)
  4750. xmaximal = max(xmaxlist)
  4751. ymaximal = max(ymaxlist)
  4752. px = 0.5 * (xminimal + xmaximal)
  4753. py = 0.5 * (yminimal + ymaximal)
  4754. # execute mirroring
  4755. for obj in obj_list:
  4756. obj.mirror('Y', [px, py])
  4757. obj.plot()
  4758. self.object_changed.emit(obj)
  4759. self.inform.emit(_("[success] Flip on X axis done."))
  4760. except Exception as e:
  4761. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4762. return
  4763. def on_rotate(self, silent=False, preset=None):
  4764. self.report_usage("on_rotate()")
  4765. obj_list = self.collection.get_selected()
  4766. xminlist = []
  4767. yminlist = []
  4768. xmaxlist = []
  4769. ymaxlist = []
  4770. if not obj_list:
  4771. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  4772. else:
  4773. if silent is False:
  4774. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4775. min=-360, max=360, decimals=4,
  4776. init_val=float(self.defaults['tools_transform_rotate']))
  4777. num, ok = rotatebox.get_value()
  4778. else:
  4779. num = preset
  4780. ok = True
  4781. if ok:
  4782. try:
  4783. # first get a bounding box to fit all
  4784. for obj in obj_list:
  4785. xmin, ymin, xmax, ymax = obj.bounds()
  4786. xminlist.append(xmin)
  4787. yminlist.append(ymin)
  4788. xmaxlist.append(xmax)
  4789. ymaxlist.append(ymax)
  4790. # get the minimum x,y and maximum x,y for all objects selected
  4791. xminimal = min(xminlist)
  4792. yminimal = min(yminlist)
  4793. xmaximal = max(xmaxlist)
  4794. ymaximal = max(ymaxlist)
  4795. px = 0.5 * (xminimal + xmaximal)
  4796. py = 0.5 * (yminimal + ymaximal)
  4797. for sel_obj in obj_list:
  4798. sel_obj.rotate(-float(num), point=(px, py))
  4799. sel_obj.plot()
  4800. self.object_changed.emit(sel_obj)
  4801. self.inform.emit(_("[success] Rotation done."))
  4802. except Exception as e:
  4803. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  4804. return
  4805. def on_skewx(self):
  4806. self.report_usage("on_skewx()")
  4807. obj_list = self.collection.get_selected()
  4808. xminlist = []
  4809. yminlist = []
  4810. if not obj_list:
  4811. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  4812. else:
  4813. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4814. min=-360, max=360, decimals=4,
  4815. init_val=float(self.defaults['tools_transform_skew_x']))
  4816. num, ok = skewxbox.get_value()
  4817. if ok:
  4818. # first get a bounding box to fit all
  4819. for obj in obj_list:
  4820. xmin, ymin, xmax, ymax = obj.bounds()
  4821. xminlist.append(xmin)
  4822. yminlist.append(ymin)
  4823. # get the minimum x,y and maximum x,y for all objects selected
  4824. xminimal = min(xminlist)
  4825. yminimal = min(yminlist)
  4826. for obj in obj_list:
  4827. obj.skew(num, 0, point=(xminimal, yminimal))
  4828. obj.plot()
  4829. self.object_changed.emit(obj)
  4830. self.inform.emit(_("[success] Skew on X axis done."))
  4831. def on_skewy(self):
  4832. self.report_usage("on_skewy()")
  4833. obj_list = self.collection.get_selected()
  4834. xminlist = []
  4835. yminlist = []
  4836. if not obj_list:
  4837. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  4838. else:
  4839. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4840. min=-360, max=360, decimals=4,
  4841. init_val=float(self.defaults['tools_transform_skew_y']))
  4842. num, ok = skewybox.get_value()
  4843. if ok:
  4844. # first get a bounding box to fit all
  4845. for obj in obj_list:
  4846. xmin, ymin, xmax, ymax = obj.bounds()
  4847. xminlist.append(xmin)
  4848. yminlist.append(ymin)
  4849. # get the minimum x,y and maximum x,y for all objects selected
  4850. xminimal = min(xminlist)
  4851. yminimal = min(yminlist)
  4852. for obj in obj_list:
  4853. obj.skew(0, num, point=(xminimal, yminimal))
  4854. obj.plot()
  4855. self.object_changed.emit(obj)
  4856. self.inform.emit(_("[success] Skew on Y axis done."))
  4857. def on_plots_updated(self):
  4858. """
  4859. Callback used to report when the plots have changed.
  4860. Adjust axes and zooms to fit.
  4861. :return: None
  4862. """
  4863. self.plotcanvas.update() # TODO: Need update canvas?
  4864. self.on_zoom_fit(None)
  4865. self.collection.update_view()
  4866. # self.inform.emit(_("Plots updated ..."))
  4867. # TODO: Rework toolbar 'clear', 'replot' functions
  4868. def on_toolbar_replot(self):
  4869. """
  4870. Callback for toolbar button. Re-plots all objects.
  4871. :return: None
  4872. """
  4873. self.report_usage("on_toolbar_replot")
  4874. self.log.debug("on_toolbar_replot()")
  4875. try:
  4876. self.collection.get_active().read_form()
  4877. except AttributeError:
  4878. self.log.debug("on_toolbar_replot(): AttributeError")
  4879. pass
  4880. self.plot_all()
  4881. def on_row_activated(self, index):
  4882. if index.isValid():
  4883. if index.internalPointer().parent_item != self.collection.root_item:
  4884. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4885. self.collection.on_item_activated(index)
  4886. def grid_status(self):
  4887. if self.ui.grid_snap_btn.isChecked():
  4888. return True
  4889. else:
  4890. return False
  4891. def populate_cmenu_grids(self):
  4892. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4893. self.ui.cmenu_gridmenu.clear()
  4894. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4895. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  4896. grid_toggle.setCheckable(True)
  4897. if self.grid_status() == True:
  4898. grid_toggle.setChecked(True)
  4899. else:
  4900. grid_toggle.setChecked(False)
  4901. self.ui.cmenu_gridmenu.addSeparator()
  4902. for grid in sorted_list:
  4903. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  4904. action.triggered.connect(self.set_grid)
  4905. self.ui.cmenu_gridmenu.addSeparator()
  4906. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  4907. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  4908. grid_add.triggered.connect(self.on_grid_add)
  4909. grid_delete.triggered.connect(self.on_grid_delete)
  4910. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4911. def set_grid(self):
  4912. self.ui.grid_gap_x_entry.setText(self.sender().text())
  4913. self.ui.grid_gap_y_entry.setText(self.sender().text())
  4914. def on_grid_add(self):
  4915. # ## Current application units in lower Case
  4916. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4917. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4918. text=_('Enter a Grid Value:'),
  4919. min=0.0000, max=99.9999, decimals=4)
  4920. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  4921. val, ok = grid_add_popup.get_value()
  4922. if ok:
  4923. if float(val) == 0:
  4924. self.inform.emit(
  4925. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4926. return
  4927. else:
  4928. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4929. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4930. self.inform.emit(
  4931. _("[success] New Grid added ..."))
  4932. else:
  4933. self.inform.emit(
  4934. _("[WARNING_NOTCL] Grid already exists ..."))
  4935. else:
  4936. self.inform.emit(
  4937. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  4938. def on_grid_delete(self):
  4939. # ## Current application units in lower Case
  4940. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4941. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4942. text='Enter a Grid Value:',
  4943. min=0.0000, max=99.9999, decimals=4)
  4944. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  4945. val, ok = grid_del_popup.get_value()
  4946. if ok:
  4947. if float(val) == 0:
  4948. self.inform.emit(
  4949. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4950. return
  4951. else:
  4952. try:
  4953. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4954. except ValueError:
  4955. self.inform.emit(
  4956. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  4957. return
  4958. self.inform.emit(
  4959. _("[success] Grid Value deleted ..."))
  4960. else:
  4961. self.inform.emit(
  4962. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  4963. def on_shortcut_list(self):
  4964. self.report_usage("on_shortcut_list()")
  4965. # add the tab if it was closed
  4966. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4967. # delete the absolute and relative position and messages in the infobar
  4968. self.ui.position_label.setText("")
  4969. self.ui.rel_position_label.setText("")
  4970. # Switch plot_area to preferences page
  4971. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4972. self.ui.show()
  4973. def on_select_tab(self, name):
  4974. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4975. if self.ui.splitter.sizes()[0] == 0:
  4976. self.ui.splitter.setSizes([1, 1])
  4977. else:
  4978. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4979. self.ui.splitter.setSizes([0, 1])
  4980. if name == 'project':
  4981. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4982. elif name == 'selected':
  4983. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4984. elif name == 'tool':
  4985. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4986. def on_copy_name(self):
  4987. self.report_usage("on_copy_name()")
  4988. obj = self.collection.get_active()
  4989. try:
  4990. name = obj.options["name"]
  4991. except AttributeError:
  4992. log.debug("on_copy_name() --> No object selected to copy it's name")
  4993. self.inform.emit(_("[WARNING_NOTCL] No object selected to copy it's name"))
  4994. return
  4995. self.clipboard.setText(name)
  4996. self.inform.emit(_("Name copied on clipboard ..."))
  4997. def on_mouse_click_over_plot(self, event):
  4998. """
  4999. Default actions are:
  5000. :param event: Contains information about the event, like which button
  5001. was clicked, the pixel coordinates and the axes coordinates.
  5002. :return: None
  5003. """
  5004. self.pos = []
  5005. # So it can receive key presses
  5006. self.plotcanvas.native.setFocus()
  5007. # Set the mouse button for panning
  5008. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  5009. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5010. if self.grid_status() == True:
  5011. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5012. self.app_cursor.enabled = True
  5013. else:
  5014. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5015. self.app_cursor.enabled = False
  5016. try:
  5017. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5018. if event.button == 1:
  5019. # Reset here the relative coordinates so there is a new reference on the click position
  5020. if self.rel_point1 is None:
  5021. self.rel_point1 = self.pos
  5022. else:
  5023. self.rel_point2 = copy(self.rel_point1)
  5024. self.rel_point1 = self.pos
  5025. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5026. if modifiers == QtCore.Qt.ShiftModifier:
  5027. # do not auto open the Project Tab
  5028. self.click_noproject = True
  5029. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  5030. self.inform.emit(_("[success] Coordinates copied to clipboard."))
  5031. return
  5032. self.on_mouse_move_over_plot(event, origin_click=True)
  5033. except Exception as e:
  5034. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5035. def on_double_click_over_plot(self, event):
  5036. self.doubleclick = True
  5037. def on_mouse_move_over_plot(self, event, origin_click=None):
  5038. """
  5039. Callback for the mouse motion event over the plot.
  5040. :param event: Contains information about the event.
  5041. :param origin_click
  5042. :return: None
  5043. """
  5044. # So it can receive key presses
  5045. self.plotcanvas.native.setFocus()
  5046. self.pos_jump = event.pos
  5047. self.ui.popMenu.mouse_is_panning = False
  5048. if origin_click != True:
  5049. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5050. if event.button == 2 and event.is_dragging == 1:
  5051. self.ui.popMenu.mouse_is_panning = True
  5052. return
  5053. if self.rel_point1 is not None:
  5054. try: # May fail in case mouse not within axes
  5055. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5056. if self.grid_status() == True:
  5057. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5058. self.app_cursor.enabled = True
  5059. # Update cursor
  5060. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  5061. else:
  5062. pos = (pos_canvas[0], pos_canvas[1])
  5063. self.app_cursor.enabled = False
  5064. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5065. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5066. dx = pos[0] - self.rel_point1[0]
  5067. dy = pos[1] - self.rel_point1[1]
  5068. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5069. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5070. self.mouse = [pos[0], pos[1]]
  5071. # if the mouse is moved and the LMB is clicked then the action is a selection
  5072. if event.is_dragging == 1 and event.button == 1:
  5073. self.delete_selection_shape()
  5074. if dx < 0:
  5075. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5076. face_color=self.defaults['global_alt_sel_fill'])
  5077. self.selection_type = False
  5078. else:
  5079. self.draw_moving_selection_shape(self.pos, pos)
  5080. self.selection_type = True
  5081. # hover effect - enabled in Preferences -> General -> GUI Settings
  5082. if self.defaults['global_hover']:
  5083. for obj in self.collection.get_list():
  5084. try:
  5085. # select the object(s) only if it is enabled (plotted)
  5086. if obj.options['plot']:
  5087. if obj not in self.collection.get_selected():
  5088. poly_obj = Polygon(
  5089. [(obj.options['xmin'], obj.options['ymin']),
  5090. (obj.options['xmax'], obj.options['ymin']),
  5091. (obj.options['xmax'], obj.options['ymax']),
  5092. (obj.options['xmin'], obj.options['ymax'])]
  5093. )
  5094. if Point(pos).within(poly_obj):
  5095. if obj.isHovering is False:
  5096. obj.isHovering = True
  5097. obj.notHovering = True
  5098. # create the selection box around the selected object
  5099. self.draw_hover_shape(obj, color='#d1e0e0')
  5100. else:
  5101. if obj.notHovering is True:
  5102. obj.notHovering = False
  5103. obj.isHovering = False
  5104. self.delete_hover_shape()
  5105. except:
  5106. # the Exception here will happen if we try to select on screen and we have an
  5107. # newly (and empty) just created Geometry or Excellon object that do not have the
  5108. # xmin, xmax, ymin, ymax options.
  5109. # In this case poly_obj creation (see above) will fail
  5110. pass
  5111. except:
  5112. self.ui.position_label.setText("")
  5113. self.ui.rel_position_label.setText("")
  5114. self.mouse = None
  5115. def on_mouse_click_release_over_plot(self, event):
  5116. """
  5117. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5118. and has been registered in ''self.__init__()''.
  5119. :param event: contains information about the event.
  5120. :return:
  5121. """
  5122. pos = 0, 0
  5123. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5124. if self.grid_status() == True:
  5125. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5126. else:
  5127. pos = (pos_canvas[0], pos_canvas[1])
  5128. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5129. # canvas menu
  5130. if event.button == 2: # right click
  5131. if self.ui.popMenu.mouse_is_panning is False:
  5132. self.cursor = QtGui.QCursor()
  5133. self.populate_cmenu_grids()
  5134. self.ui.popMenu.popup(self.cursor.pos())
  5135. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5136. # selection and then select a type of selection ("enclosing" or "touching")
  5137. try:
  5138. if event.button == 1: # left click
  5139. if self.doubleclick is True:
  5140. self.doubleclick = False
  5141. if self.collection.get_selected():
  5142. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5143. if self.ui.splitter.sizes()[0] == 0:
  5144. self.ui.splitter.setSizes([1, 1])
  5145. # delete the selection shape(S) as it may be in the way
  5146. self.delete_selection_shape()
  5147. self.delete_hover_shape()
  5148. else:
  5149. if self.selection_type is not None:
  5150. self.selection_area_handler(self.pos, pos, self.selection_type)
  5151. self.selection_type = None
  5152. else:
  5153. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5154. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5155. # deselect, and if it's not selected then it will be selected
  5156. if modifiers == QtCore.Qt.ControlModifier:
  5157. # If there is no active command (self.command_active is None) then we check if we clicked
  5158. # on a object by checking the bounding limits against mouse click position
  5159. if self.command_active is None:
  5160. self.select_objects(key='CTRL')
  5161. self.delete_hover_shape()
  5162. elif modifiers == QtCore.Qt.ShiftModifier:
  5163. # if SHIFT was pressed and LMB is clicked then we have a coordinates copy to clipboard
  5164. # therefore things should stay as they are
  5165. pass
  5166. else:
  5167. # If there is no active command (self.command_active is None) then we check if we clicked
  5168. # on a object by checking the bounding limits against mouse click position
  5169. if self.command_active is None:
  5170. self.select_objects()
  5171. self.delete_hover_shape()
  5172. except Exception as e:
  5173. log.warning("Error: %s" % str(e))
  5174. return
  5175. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5176. """
  5177. :param start_pos: mouse position when the selection LMB click was done
  5178. :param end_pos: mouse position when the left mouse button is released
  5179. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5180. :return:
  5181. """
  5182. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5183. self.delete_selection_shape()
  5184. for obj in self.collection.get_list():
  5185. try:
  5186. # select the object(s) only if it is enabled (plotted)
  5187. if obj.options['plot']:
  5188. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5189. (obj.options['xmax'], obj.options['ymin']),
  5190. (obj.options['xmax'], obj.options['ymax']),
  5191. (obj.options['xmin'], obj.options['ymax'])])
  5192. if sel_type is True:
  5193. if poly_obj.within(poly_selection):
  5194. # create the selection box around the selected object
  5195. if self.defaults['global_selection_shape'] is True:
  5196. self.draw_selection_shape(obj)
  5197. self.collection.set_active(obj.options['name'])
  5198. else:
  5199. if poly_selection.intersects(poly_obj):
  5200. # create the selection box around the selected object
  5201. if self.defaults['global_selection_shape'] is True:
  5202. self.draw_selection_shape(obj)
  5203. self.collection.set_active(obj.options['name'])
  5204. except Exception as e:
  5205. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5206. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5207. # In this case poly_obj creation (see above) will fail
  5208. log.debug("App.selection_area_handler() --> %s" % str(e))
  5209. def select_objects(self, key=None):
  5210. # list where we store the overlapped objects under our mouse left click position
  5211. objects_under_the_click_list = []
  5212. # Populate the list with the overlapped objects on the click position
  5213. curr_x, curr_y = self.pos
  5214. for obj in self.all_objects_list:
  5215. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5216. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5217. if obj.options['name'] not in objects_under_the_click_list:
  5218. if obj.options['plot']:
  5219. # add objects to the objects_under_the_click list only if the object is plotted
  5220. # (active and not disabled)
  5221. objects_under_the_click_list.append(obj.options['name'])
  5222. try:
  5223. # If there is no element in the overlapped objects list then make everyone inactive
  5224. # because we selected "nothing"
  5225. if not objects_under_the_click_list:
  5226. self.collection.set_all_inactive()
  5227. # delete the possible selection box around a possible selected object
  5228. self.delete_selection_shape()
  5229. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5230. # only when working on App
  5231. if self.call_source == 'app':
  5232. if self.click_noproject is False:
  5233. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5234. else:
  5235. # restore auto open the Project Tab
  5236. self.click_noproject = False
  5237. # delete any text in the status bar, implicitly the last object name that was selected
  5238. self.inform.emit("")
  5239. else:
  5240. self.call_source = 'app'
  5241. else:
  5242. # case when there is only an object under the click and we toggle it
  5243. if len(objects_under_the_click_list) == 1:
  5244. if self.collection.get_active() is None:
  5245. self.collection.set_active(objects_under_the_click_list[0])
  5246. # create the selection box around the selected object
  5247. curr_sel_obj = self.collection.get_active()
  5248. if self.defaults['global_selection_shape'] is True:
  5249. self.draw_selection_shape(curr_sel_obj)
  5250. # self.inform.emit('[selected] %s: %s selected' %
  5251. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5252. if curr_sel_obj.kind == 'gerber':
  5253. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5254. color='green', name=str(curr_sel_obj.options['name'])))
  5255. elif curr_sel_obj.kind == 'excellon':
  5256. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5257. color='brown', name=str(curr_sel_obj.options['name'])))
  5258. elif curr_sel_obj.kind == 'cncjob':
  5259. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5260. color='blue', name=str(curr_sel_obj.options['name'])))
  5261. elif curr_sel_obj.kind == 'geometry':
  5262. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5263. color='red', name=str(curr_sel_obj.options['name'])))
  5264. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  5265. self.collection.set_all_inactive()
  5266. self.delete_selection_shape()
  5267. self.collection.set_active(objects_under_the_click_list[0])
  5268. # create the selection box around the selected object
  5269. curr_sel_obj = self.collection.get_active()
  5270. if self.defaults['global_selection_shape'] is True:
  5271. self.draw_selection_shape(curr_sel_obj)
  5272. # self.inform.emit('[selected] %s: %s selected' %
  5273. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5274. if curr_sel_obj.kind == 'gerber':
  5275. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5276. color='green', name=str(curr_sel_obj.options['name'])))
  5277. elif curr_sel_obj.kind == 'excellon':
  5278. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5279. color='brown', name=str(curr_sel_obj.options['name'])))
  5280. elif curr_sel_obj.kind == 'cncjob':
  5281. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5282. color='blue', name=str(curr_sel_obj.options['name'])))
  5283. elif curr_sel_obj.kind == 'geometry':
  5284. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5285. color='red', name=str(curr_sel_obj.options['name'])))
  5286. else:
  5287. self.collection.set_all_inactive()
  5288. self.delete_selection_shape()
  5289. if self.call_source == 'app':
  5290. # delete any text in the status bar, implicitly the last object name that was selected
  5291. self.inform.emit("")
  5292. else:
  5293. self.call_source = 'app'
  5294. else:
  5295. # If there is no selected object
  5296. # make active the first element of the overlapped objects list
  5297. if self.collection.get_active() is None:
  5298. self.collection.set_active(objects_under_the_click_list[0])
  5299. name_sel_obj = self.collection.get_active().options['name']
  5300. # In case that there is a selected object but it is not in the overlapped object list
  5301. # make that object inactive and activate the first element in the overlapped object list
  5302. if name_sel_obj not in objects_under_the_click_list:
  5303. self.collection.set_inactive(name_sel_obj)
  5304. name_sel_obj = objects_under_the_click_list[0]
  5305. self.collection.set_active(name_sel_obj)
  5306. else:
  5307. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  5308. self.collection.set_all_inactive()
  5309. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  5310. len(objects_under_the_click_list)])
  5311. curr_sel_obj = self.collection.get_active()
  5312. # delete the possible selection box around a possible selected object
  5313. self.delete_selection_shape()
  5314. # create the selection box around the selected object
  5315. if self.defaults['global_selection_shape'] is True:
  5316. self.draw_selection_shape(curr_sel_obj)
  5317. # self.inform.emit('[selected] %s: %s selected' %
  5318. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5319. if curr_sel_obj.kind == 'gerber':
  5320. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5321. color='green', name=str(curr_sel_obj.options['name'])))
  5322. elif curr_sel_obj.kind == 'excellon':
  5323. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5324. color='brown', name=str(curr_sel_obj.options['name'])))
  5325. elif curr_sel_obj.kind == 'cncjob':
  5326. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5327. color='blue', name=str(curr_sel_obj.options['name'])))
  5328. elif curr_sel_obj.kind == 'geometry':
  5329. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5330. color='red', name=str(curr_sel_obj.options['name'])))
  5331. # for obj in self.collection.get_list():
  5332. # obj.plot()
  5333. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  5334. # TODO: on selected objects change the object colors and do not draw the selection box
  5335. # self.plotcanvas.update() # this updates the canvas
  5336. except Exception as e:
  5337. log.error("[ERROR] Something went bad. %s" % str(e))
  5338. return
  5339. def delete_hover_shape(self):
  5340. self.hover_shapes.clear()
  5341. self.hover_shapes.redraw()
  5342. def draw_hover_shape(self, sel_obj, color=None):
  5343. """
  5344. :param sel_obj: the object for which the hover shape must be drawn
  5345. :return:
  5346. """
  5347. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5348. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5349. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5350. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5351. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5352. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5353. hover_rect = hover_rect.buffer(-0.1)
  5354. hover_rect = hover_rect.buffer(0.2)
  5355. else:
  5356. hover_rect = hover_rect.buffer(-0.00393)
  5357. hover_rect = hover_rect.buffer(0.00787)
  5358. if color:
  5359. face = Color(color)
  5360. face.alpha = 0.2
  5361. outline = Color(color, alpha=0.8)
  5362. else:
  5363. face = Color(self.defaults['global_sel_fill'])
  5364. face.alpha = 0.2
  5365. outline = self.defaults['global_sel_line']
  5366. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5367. def delete_selection_shape(self):
  5368. self.move_tool.sel_shapes.clear()
  5369. self.move_tool.sel_shapes.redraw()
  5370. def draw_selection_shape(self, sel_obj, color=None):
  5371. """
  5372. :param sel_obj: the object for which the selection shape must be drawn
  5373. :return:
  5374. """
  5375. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5376. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5377. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5378. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5379. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5380. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5381. sel_rect = sel_rect.buffer(-0.1)
  5382. sel_rect = sel_rect.buffer(0.2)
  5383. else:
  5384. sel_rect = sel_rect.buffer(-0.00393)
  5385. sel_rect = sel_rect.buffer(0.00787)
  5386. if color:
  5387. face = Color(color, alpha=0.2)
  5388. outline = Color(color, alpha=0.8)
  5389. else:
  5390. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  5391. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  5392. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5393. color=outline,
  5394. face_color=face,
  5395. update=True,
  5396. layer=0,
  5397. tolerance=None))
  5398. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5399. """
  5400. :param old_coords: old coordinates
  5401. :param coords: new coordinates
  5402. :return:
  5403. """
  5404. if 'color' in kwargs:
  5405. color = kwargs['color']
  5406. else:
  5407. color = self.defaults['global_sel_line']
  5408. if 'face_color' in kwargs:
  5409. face_color = kwargs['face_color']
  5410. else:
  5411. face_color = self.defaults['global_sel_fill']
  5412. if 'face_alpha' in kwargs:
  5413. face_alpha = kwargs['face_alpha']
  5414. else:
  5415. face_alpha = 0.3
  5416. x0, y0 = old_coords
  5417. x1, y1 = coords
  5418. pt1 = (x0, y0)
  5419. pt2 = (x1, y0)
  5420. pt3 = (x1, y1)
  5421. pt4 = (x0, y1)
  5422. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5423. color_t = Color(face_color)
  5424. color_t.alpha = face_alpha
  5425. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5426. layer=0, tolerance=None)
  5427. def on_file_new_click(self):
  5428. if self.collection.get_list() and self.should_we_save:
  5429. msgbox = QtWidgets.QMessageBox()
  5430. # msgbox.setText("<B>Save changes ...</B>")
  5431. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5432. "Creating a New project will delete them.\n"
  5433. "Do you want to Save the project?"))
  5434. msgbox.setWindowTitle(_("Save changes"))
  5435. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5436. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5437. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5438. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5439. msgbox.setDefaultButton(bt_yes)
  5440. msgbox.exec_()
  5441. response = msgbox.clickedButton()
  5442. if response == bt_yes:
  5443. self.on_file_saveprojectas()
  5444. elif response == bt_cancel:
  5445. return
  5446. elif response == bt_no:
  5447. self.on_file_new()
  5448. else:
  5449. self.on_file_new()
  5450. self.inform.emit(_("[success] New Project created..."))
  5451. def on_file_new(self):
  5452. """
  5453. Callback for menu item File->New. Returns the application to its
  5454. startup state. This method is thread-safe.
  5455. :return: None
  5456. """
  5457. self.report_usage("on_file_new")
  5458. # Remove everything from memory
  5459. App.log.debug("on_file_new()")
  5460. if self.call_source != 'app':
  5461. self.editor2object(cleanup=True)
  5462. # ## EDITOR section
  5463. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  5464. self.exc_editor = FlatCAMExcEditor(self)
  5465. self.grb_editor = FlatCAMGrbEditor(self)
  5466. # Clear pool
  5467. self.clear_pool()
  5468. for obj in self.collection.get_list():
  5469. # delete shapes left drawn from mark shape_collections, if any
  5470. if isinstance(obj, FlatCAMGerber):
  5471. try:
  5472. obj.mark_shapes.enabled = False
  5473. obj.mark_shapes.clear(update=True)
  5474. except AttributeError:
  5475. pass
  5476. # also delete annotation shapes, if any
  5477. elif isinstance(obj, FlatCAMCNCjob):
  5478. try:
  5479. obj.annotation.enabled = False
  5480. obj.annotation.clear(update=True)
  5481. except AttributeError:
  5482. pass
  5483. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5484. self.init_tcl()
  5485. self.delete_selection_shape()
  5486. self.collection.delete_all()
  5487. self.setup_component_editor()
  5488. # Clear project filename
  5489. self.project_filename = None
  5490. # Load the application defaults
  5491. self.load_defaults(filename='current_defaults')
  5492. # Re-fresh project options
  5493. self.on_options_app2project()
  5494. # Init Tools
  5495. self.init_tools()
  5496. # Close any Tabs opened in the Plot Tab Area section
  5497. for index in range(self.ui.plot_tab_area.count()):
  5498. self.ui.plot_tab_area.closeTab(index)
  5499. # for whatever reason previous command does not close the last tab so I do it manually
  5500. self.ui.plot_tab_area.closeTab(0)
  5501. # # And then add again the Plot Area
  5502. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  5503. self.ui.plot_tab_area.protectTab(0)
  5504. # take the focus of the Notebook on Project Tab.
  5505. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5506. self.set_ui_title(name=_("New Project - Not saved"))
  5507. def obj_properties(self):
  5508. self.report_usage("obj_properties()")
  5509. self.properties_tool.run(toggle=False)
  5510. def on_project_context_save(self):
  5511. obj = self.collection.get_active()
  5512. if type(obj) == FlatCAMGeometry:
  5513. self.on_file_exportdxf()
  5514. elif type(obj) == FlatCAMExcellon:
  5515. self.on_file_saveexcellon()
  5516. elif type(obj) == FlatCAMCNCjob:
  5517. obj.on_exportgcode_button_click()
  5518. elif type(obj) == FlatCAMGerber:
  5519. self.on_file_savegerber()
  5520. def obj_move(self):
  5521. self.report_usage("obj_move()")
  5522. self.move_tool.run(toggle=False)
  5523. def on_fileopengerber(self):
  5524. """
  5525. File menu callback for opening a Gerber.
  5526. :return: None
  5527. """
  5528. self.report_usage("on_fileopengerber")
  5529. App.log.debug("on_fileopengerber()")
  5530. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5531. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5532. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  5533. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5534. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5535. "*.mil);;" \
  5536. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5537. "Allegro Files (*.art);;" \
  5538. "Mentor Files (*.pho *.gdo);;" \
  5539. "All Files (*.*)"
  5540. try:
  5541. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5542. directory=self.get_last_folder(), filter=_filter_)
  5543. except TypeError:
  5544. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5545. filenames = [str(filename) for filename in filenames]
  5546. if len(filenames) == 0:
  5547. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  5548. else:
  5549. for filename in filenames:
  5550. if filename != '':
  5551. self.worker_task.emit({'fcn': self.open_gerber,
  5552. 'params': [filename]})
  5553. def on_fileopenexcellon(self):
  5554. """
  5555. File menu callback for opening an Excellon file.
  5556. :return: None
  5557. """
  5558. self.report_usage("on_fileopenexcellon")
  5559. App.log.debug("on_fileopenexcellon()")
  5560. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5561. "All Files (*.*)"
  5562. try:
  5563. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5564. directory=self.get_last_folder(), filter=_filter_)
  5565. except TypeError:
  5566. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5567. filenames = [str(filename) for filename in filenames]
  5568. if len(filenames) == 0:
  5569. self.inform.emit(_("[WARNING_NOTCL] Open Excellon cancelled."))
  5570. else:
  5571. for filename in filenames:
  5572. if filename != '':
  5573. self.worker_task.emit({'fcn': self.open_excellon,
  5574. 'params': [filename]})
  5575. def on_fileopengcode(self):
  5576. """
  5577. File menu call back for opening gcode.
  5578. :return: None
  5579. """
  5580. self.report_usage("on_fileopengcode")
  5581. App.log.debug("on_fileopengcode()")
  5582. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5583. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5584. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  5585. "All Files (*.*)"
  5586. try:
  5587. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5588. directory=self.get_last_folder(), filter=_filter_)
  5589. except TypeError:
  5590. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5591. filenames = [str(filename) for filename in filenames]
  5592. if len(filenames) == 0:
  5593. self.inform.emit(_("[WARNING_NOTCL] Open G-Code cancelled."))
  5594. else:
  5595. for filename in filenames:
  5596. if filename != '':
  5597. self.worker_task.emit({'fcn': self.open_gcode,
  5598. 'params': [filename]})
  5599. def on_file_openproject(self):
  5600. """
  5601. File menu callback for opening a project.
  5602. :return: None
  5603. """
  5604. self.report_usage("on_file_openproject")
  5605. App.log.debug("on_file_openproject()")
  5606. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5607. try:
  5608. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5609. directory=self.get_last_folder(), filter=_filter_)
  5610. except TypeError:
  5611. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5612. # The Qt methods above will return a QString which can cause problems later.
  5613. # So far json.dump() will fail to serialize it.
  5614. # TODO: Improve the serialization methods and remove this fix.
  5615. filename = str(filename)
  5616. if filename == "":
  5617. self.inform.emit(_("[WARNING_NOTCL] Open Project cancelled."))
  5618. else:
  5619. # self.worker_task.emit({'fcn': self.open_project,
  5620. # 'params': [filename]})
  5621. # The above was failing because open_project() is not
  5622. # thread safe. The new_project()
  5623. self.open_project(filename)
  5624. def on_file_openconfig(self):
  5625. """
  5626. File menu callback for opening a config file.
  5627. :return: None
  5628. """
  5629. self.report_usage("on_file_openconfig")
  5630. App.log.debug("on_file_openconfig()")
  5631. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5632. try:
  5633. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5634. directory=self.data_path, filter=_filter_)
  5635. except TypeError:
  5636. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5637. filter=_filter_)
  5638. if filename == "":
  5639. self.inform.emit(_("[WARNING_NOTCL] Open Config cancelled."))
  5640. else:
  5641. self.open_config_file(filename)
  5642. def on_file_exportsvg(self):
  5643. """
  5644. Callback for menu item File->Export SVG.
  5645. :return: None
  5646. """
  5647. self.report_usage("on_file_exportsvg")
  5648. App.log.debug("on_file_exportsvg()")
  5649. obj = self.collection.get_active()
  5650. if obj is None:
  5651. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5652. msg = _("Please Select a Geometry object to export")
  5653. msgbox = QtWidgets.QMessageBox()
  5654. msgbox.setInformativeText(msg)
  5655. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5656. msgbox.setDefaultButton(bt_ok)
  5657. msgbox.exec_()
  5658. return
  5659. # Check for more compatible types and add as required
  5660. if (not isinstance(obj, FlatCAMGeometry)
  5661. and not isinstance(obj, FlatCAMGerber)
  5662. and not isinstance(obj, FlatCAMCNCjob)
  5663. and not isinstance(obj, FlatCAMExcellon)):
  5664. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  5665. msgbox = QtWidgets.QMessageBox()
  5666. msgbox.setInformativeText(msg)
  5667. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5668. msgbox.setDefaultButton(bt_ok)
  5669. msgbox.exec_()
  5670. return
  5671. name = obj.options["name"]
  5672. _filter = "SVG File (*.svg);;All Files (*.*)"
  5673. try:
  5674. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5675. caption=_("Export SVG"),
  5676. directory=self.get_last_save_folder() + '/' + str(name),
  5677. filter=_filter)
  5678. except TypeError:
  5679. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  5680. filename = str(filename)
  5681. if filename == "":
  5682. self.inform.emit(_("[WARNING_NOTCL] Export SVG cancelled."))
  5683. return
  5684. else:
  5685. self.export_svg(name, filename)
  5686. if self.defaults["global_open_style"] is False:
  5687. self.file_opened.emit("SVG", filename)
  5688. self.file_saved.emit("SVG", filename)
  5689. def on_file_exportpng(self):
  5690. self.report_usage("on_file_exportpng")
  5691. App.log.debug("on_file_exportpng()")
  5692. self.date = str(datetime.today()).rpartition('.')[0]
  5693. self.date = ''.join(c for c in self.date if c not in ':-')
  5694. self.date = self.date.replace(' ', '_')
  5695. image = _screenshot()
  5696. data = np.asarray(image)
  5697. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5698. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  5699. return
  5700. filter_ = "PNG File (*.png);;All Files (*.*)"
  5701. try:
  5702. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5703. caption=_("Export PNG Image"),
  5704. directory=self.get_last_save_folder() + '/png_' + self.date,
  5705. filter=filter_)
  5706. except TypeError:
  5707. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  5708. filename = str(filename)
  5709. if filename == "":
  5710. self.inform.emit(_("Export PNG cancelled."))
  5711. return
  5712. else:
  5713. write_png(filename, data)
  5714. if self.defaults["global_open_style"] is False:
  5715. self.file_opened.emit("png", filename)
  5716. self.file_saved.emit("png", filename)
  5717. def on_file_savegerber(self):
  5718. """
  5719. Callback for menu item File->Export Gerber.
  5720. :return: None
  5721. """
  5722. self.report_usage("on_file_savegerber")
  5723. App.log.debug("on_file_savegerber()")
  5724. obj = self.collection.get_active()
  5725. if obj is None:
  5726. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  5727. return
  5728. # Check for more compatible types and add as required
  5729. if not isinstance(obj, FlatCAMGerber):
  5730. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5731. return
  5732. name = self.collection.get_active().options["name"]
  5733. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5734. try:
  5735. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5736. caption="Save Gerber source file",
  5737. directory=self.get_last_save_folder() + '/' + name,
  5738. filter=_filter)
  5739. except TypeError:
  5740. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  5741. filename = str(filename)
  5742. if filename == "":
  5743. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  5744. return
  5745. else:
  5746. self.save_source_file(name, filename)
  5747. if self.defaults["global_open_style"] is False:
  5748. self.file_opened.emit("Gerber", filename)
  5749. self.file_saved.emit("Gerber", filename)
  5750. def on_file_saveexcellon(self):
  5751. """
  5752. Callback for menu item File->Export Gerber.
  5753. :return: None
  5754. """
  5755. self.report_usage("on_file_saveexcellon")
  5756. App.log.debug("on_file_saveexcellon()")
  5757. obj = self.collection.get_active()
  5758. if obj is None:
  5759. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  5760. return
  5761. # Check for more compatible types and add as required
  5762. if not isinstance(obj, FlatCAMExcellon):
  5763. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5764. return
  5765. name = self.collection.get_active().options["name"]
  5766. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5767. try:
  5768. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5769. caption=_("Save Excellon source file"),
  5770. directory=self.get_last_save_folder() + '/' + name,
  5771. filter=_filter)
  5772. except TypeError:
  5773. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  5774. filename = str(filename)
  5775. if filename == "":
  5776. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  5777. return
  5778. else:
  5779. self.save_source_file(name, filename)
  5780. if self.defaults["global_open_style"] is False:
  5781. self.file_opened.emit("Excellon", filename)
  5782. self.file_saved.emit("Excellon", filename)
  5783. def on_file_exportexcellon(self):
  5784. """
  5785. Callback for menu item File->Export->Excellon.
  5786. :return: None
  5787. """
  5788. self.report_usage("on_file_exportexcellon")
  5789. App.log.debug("on_file_exportexcellon()")
  5790. obj = self.collection.get_active()
  5791. if obj is None:
  5792. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  5793. return
  5794. # Check for more compatible types and add as required
  5795. if not isinstance(obj, FlatCAMExcellon):
  5796. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5797. return
  5798. name = self.collection.get_active().options["name"]
  5799. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5800. try:
  5801. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5802. caption=_("Export Excellon"),
  5803. directory=self.get_last_save_folder() + '/' + name,
  5804. filter=_filter)
  5805. except TypeError:
  5806. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  5807. filename = str(filename)
  5808. if filename == "":
  5809. self.inform.emit(_("[WARNING_NOTCL] Export Excellon cancelled."))
  5810. return
  5811. else:
  5812. self.export_excellon(name, filename)
  5813. if self.defaults["global_open_style"] is False:
  5814. self.file_opened.emit("Excellon", filename)
  5815. self.file_saved.emit("Excellon", filename)
  5816. def on_file_exportgerber(self):
  5817. """
  5818. Callback for menu item File->Export->Gerber.
  5819. :return: None
  5820. """
  5821. self.report_usage("on_file_exportgerber")
  5822. App.log.debug("on_file_exportgerber()")
  5823. obj = self.collection.get_active()
  5824. if obj is None:
  5825. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Gerber object to export."))
  5826. return
  5827. # Check for more compatible types and add as required
  5828. if not isinstance(obj, FlatCAMGerber):
  5829. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5830. return
  5831. name = self.collection.get_active().options["name"]
  5832. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  5833. try:
  5834. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5835. caption=_("Export Gerber"),
  5836. directory=self.get_last_save_folder() + '/' + name,
  5837. filter=_filter_)
  5838. except TypeError:
  5839. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  5840. filename = str(filename)
  5841. if filename == "":
  5842. self.inform.emit(_("[WARNING_NOTCL] Export Gerber cancelled."))
  5843. return
  5844. else:
  5845. self.export_gerber(name, filename)
  5846. if self.defaults["global_open_style"] is False:
  5847. self.file_opened.emit("Gerber", filename)
  5848. self.file_saved.emit("Gerber", filename)
  5849. def on_file_exportdxf(self):
  5850. """
  5851. Callback for menu item File->Export DXF.
  5852. :return: None
  5853. """
  5854. self.report_usage("on_file_exportdxf")
  5855. App.log.debug("on_file_exportdxf()")
  5856. obj = self.collection.get_active()
  5857. if obj is None:
  5858. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5859. msg = _("Please Select a Geometry object to export")
  5860. msgbox = QtWidgets.QMessageBox()
  5861. msgbox.setInformativeText(msg)
  5862. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5863. msgbox.setDefaultButton(bt_ok)
  5864. msgbox.exec_()
  5865. return
  5866. # Check for more compatible types and add as required
  5867. if not isinstance(obj, FlatCAMGeometry):
  5868. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  5869. msgbox = QtWidgets.QMessageBox()
  5870. msgbox.setInformativeText(msg)
  5871. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5872. msgbox.setDefaultButton(bt_ok)
  5873. msgbox.exec_()
  5874. return
  5875. name = self.collection.get_active().options["name"]
  5876. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5877. try:
  5878. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5879. caption=_("Export DXF"),
  5880. directory=self.get_last_save_folder() + '/' + name,
  5881. filter=_filter_)
  5882. except TypeError:
  5883. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  5884. filter=_filter_)
  5885. filename = str(filename)
  5886. if filename == "":
  5887. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  5888. return
  5889. else:
  5890. self.export_dxf(name, filename)
  5891. if self.defaults["global_open_style"] is False:
  5892. self.file_opened.emit("DXF", filename)
  5893. self.file_saved.emit("DXF", filename)
  5894. def on_file_importsvg(self, type_of_obj):
  5895. """
  5896. Callback for menu item File->Import SVG.
  5897. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5898. :type type_of_obj: str
  5899. :return: None
  5900. """
  5901. self.report_usage("on_file_importsvg")
  5902. App.log.debug("on_file_importsvg()")
  5903. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  5904. try:
  5905. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5906. directory=self.get_last_folder(), filter=_filter_)
  5907. except TypeError:
  5908. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5909. filter=_filter_)
  5910. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5911. type_of_obj = "geometry"
  5912. filenames = [str(filename) for filename in filenames]
  5913. if len(filenames) == 0:
  5914. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  5915. else:
  5916. for filename in filenames:
  5917. if filename != '':
  5918. self.worker_task.emit({'fcn': self.import_svg,
  5919. 'params': [filename, type_of_obj]})
  5920. def on_file_importdxf(self, type_of_obj):
  5921. """
  5922. Callback for menu item File->Import DXF.
  5923. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5924. :type type_of_obj: str
  5925. :return: None
  5926. """
  5927. self.report_usage("on_file_importdxf")
  5928. App.log.debug("on_file_importdxf()")
  5929. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5930. try:
  5931. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5932. directory=self.get_last_folder(),
  5933. filter=_filter_)
  5934. except TypeError:
  5935. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5936. filter=_filter_)
  5937. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5938. type_of_obj = "geometry"
  5939. filenames = [str(filename) for filename in filenames]
  5940. if len(filenames) == 0:
  5941. self.inform.emit(_("[WARNING_NOTCL] Open DXF cancelled."))
  5942. else:
  5943. for filename in filenames:
  5944. if filename != '':
  5945. self.worker_task.emit({'fcn': self.import_dxf,
  5946. 'params': [filename, type_of_obj]})
  5947. # ###############################################################################################################
  5948. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5949. # ###############################################################################################################
  5950. def init_code_editor(self, name):
  5951. # Signals section
  5952. # Disconnect the old signals
  5953. self.ui.buttonOpen.clicked.disconnect()
  5954. self.ui.buttonSave.clicked.disconnect()
  5955. # add the tab if it was closed
  5956. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  5957. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  5958. # delete the absolute and relative position and messages in the infobar
  5959. self.ui.position_label.setText("")
  5960. self.ui.rel_position_label.setText("")
  5961. # first clear previous text in text editor (if any)
  5962. self.ui.code_editor.clear()
  5963. self.ui.code_editor.setReadOnly(False)
  5964. self.toggle_codeeditor = True
  5965. self.ui.code_editor.completer_enable = False
  5966. # Switch plot_area to CNCJob tab
  5967. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5968. def on_view_source(self):
  5969. try:
  5970. obj = self.collection.get_active()
  5971. except:
  5972. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  5973. return 'fail'
  5974. # then append the text from GCode to the text editor
  5975. try:
  5976. file = StringIO(obj.source_file)
  5977. except AttributeError:
  5978. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  5979. return 'fail'
  5980. if obj.kind == 'gerber':
  5981. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  5982. elif obj.kind == 'excellon':
  5983. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  5984. self.init_code_editor(name=_("Source Editor"))
  5985. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5986. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5987. try:
  5988. for line in file:
  5989. proc_line = str(line).strip('\n')
  5990. self.ui.code_editor.append(proc_line)
  5991. except Exception as e:
  5992. log.debug('App.on_view_source() -->%s' % str(e))
  5993. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  5994. return
  5995. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5996. self.handleTextChanged()
  5997. self.ui.show()
  5998. def on_toggle_code_editor(self):
  5999. self.report_usage("on_toggle_code_editor()")
  6000. if self.toggle_codeeditor is False:
  6001. self.init_code_editor(name=_("Code Editor"))
  6002. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  6003. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  6004. else:
  6005. for idx in range(self.ui.plot_tab_area.count()):
  6006. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  6007. self.ui.plot_tab_area.closeTab(idx)
  6008. break
  6009. self.toggle_codeeditor = False
  6010. def on_filenewscript(self):
  6011. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6012. self.init_code_editor(name=_("Script Editor"))
  6013. self.ui.code_editor.completer_enable = True
  6014. self.ui.code_editor.append(_(
  6015. "#\n"
  6016. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  6017. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  6018. "#\n\n"
  6019. "# FlatCAM commands list:\n"
  6020. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  6021. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  6022. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  6023. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  6024. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  6025. "# WriteGCode\n"
  6026. "#\n\n"
  6027. ))
  6028. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6029. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6030. self.handleTextChanged()
  6031. self.ui.code_editor.show()
  6032. def on_fileopenscript(self):
  6033. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6034. try:
  6035. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  6036. directory=self.get_last_folder(), filter=_filter_)
  6037. except TypeError:
  6038. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  6039. # The Qt methods above will return a QString which can cause problems later.
  6040. # So far json.dump() will fail to serialize it.
  6041. # TODO: Improve the serialization methods and remove this fix.
  6042. filename = str(filename)
  6043. if filename == "":
  6044. self.inform.emit(_("[WARNING_NOTCL] Open TCL script cancelled."))
  6045. else:
  6046. self.on_filenewscript()
  6047. try:
  6048. with open(filename, "r") as opened_script:
  6049. try:
  6050. for line in opened_script:
  6051. proc_line = str(line).strip('\n')
  6052. self.ui.code_editor.append(proc_line)
  6053. except Exception as e:
  6054. log.debug('App.on_fileopenscript() -->%s' % str(e))
  6055. self.inform.emit(_('[ERROR]App.on_fileopenscript() -->%s') % str(e))
  6056. return
  6057. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6058. self.handleTextChanged()
  6059. self.ui.show()
  6060. except Exception as e:
  6061. log.debug("App.on_fileopenscript() -> %s" % str(e))
  6062. def on_filerunscript(self, name=None):
  6063. """
  6064. File menu callback for loading and running a TCL script.
  6065. :return: None
  6066. """
  6067. self.report_usage("on_filerunscript")
  6068. App.log.debug("on_file_runscript()")
  6069. if name:
  6070. filename = name
  6071. else:
  6072. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6073. try:
  6074. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6075. directory=self.get_last_folder(), filter=_filter_)
  6076. except TypeError:
  6077. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6078. # The Qt methods above will return a QString which can cause problems later.
  6079. # So far json.dump() will fail to serialize it.
  6080. # TODO: Improve the serialization methods and remove this fix.
  6081. filename = str(filename)
  6082. if filename == "":
  6083. self.inform.emit(_("[WARNING_NOTCL] Run TCL script cancelled."))
  6084. else:
  6085. try:
  6086. with open(filename, "r") as tcl_script:
  6087. cmd_line_shellfile_content = tcl_script.read()
  6088. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  6089. except Exception as e:
  6090. log.debug("App.on_filerunscript() -> %s" % str(e))
  6091. sys.exit(2)
  6092. def on_file_saveproject(self):
  6093. """
  6094. Callback for menu item File->Save Project. Saves the project to
  6095. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6096. if set to None. The project is saved by calling ``self.save_project()``.
  6097. :return: None
  6098. """
  6099. self.report_usage("on_file_saveproject")
  6100. if self.project_filename is None:
  6101. self.on_file_saveprojectas()
  6102. else:
  6103. self.worker_task.emit({'fcn': self.save_project,
  6104. 'params': [self.project_filename]})
  6105. if self.defaults["global_open_style"] is False:
  6106. self.file_opened.emit("project", self.project_filename)
  6107. self.file_saved.emit("project", self.project_filename)
  6108. self.set_ui_title(name=self.project_filename)
  6109. self.should_we_save = False
  6110. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6111. """
  6112. Callback for menu item File->Save Project As... Opens a file
  6113. chooser and saves the project to the given file via
  6114. ``self.save_project()``.
  6115. :param make_copy if to be create a copy of the project; boolean
  6116. :param use_thread: if to be run in a separate thread; boolean
  6117. :param quit_action: if to be followed by quiting the application; boolean
  6118. :return: None
  6119. """
  6120. self.report_usage("on_file_saveprojectas")
  6121. self.date = str(datetime.today()).rpartition('.')[0]
  6122. self.date = ''.join(c for c in self.date if c not in ':-')
  6123. self.date = self.date.replace(' ', '_')
  6124. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  6125. try:
  6126. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6127. caption=_("Save Project As ..."),
  6128. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  6129. filter=filter_)
  6130. except TypeError:
  6131. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  6132. filename = str(filename)
  6133. if filename == '':
  6134. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  6135. return
  6136. try:
  6137. f = open(filename, 'r')
  6138. f.close()
  6139. except IOError:
  6140. pass
  6141. if use_thread is True:
  6142. self.worker_task.emit({'fcn': self.save_project,
  6143. 'params': [filename, quit_action]})
  6144. else:
  6145. self.save_project(filename, quit_action)
  6146. # self.save_project(filename)
  6147. if self.defaults["global_open_style"] is False:
  6148. self.file_opened.emit("project", filename)
  6149. self.file_saved.emit("project", filename)
  6150. if not make_copy:
  6151. self.project_filename = filename
  6152. self.set_ui_title(name=self.project_filename)
  6153. self.should_we_save = False
  6154. def export_svg(self, obj_name, filename, scale_factor=0.00):
  6155. """
  6156. Exports a Geometry Object to an SVG file.
  6157. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6158. :param filename: Path to the SVG file to save to.
  6159. :param scale_factor: factor by which to change/scale the thickness of the features
  6160. :return:
  6161. """
  6162. self.report_usage("export_svg()")
  6163. if filename is None:
  6164. filename = self.defaults["global_last_save_folder"]
  6165. self.log.debug("export_svg()")
  6166. try:
  6167. obj = self.collection.get_by_name(str(obj_name))
  6168. except:
  6169. # TODO: The return behavior has not been established... should raise exception?
  6170. return "Could not retrieve object: %s" % obj_name
  6171. with self.proc_container.new(_("Exporting SVG")) as proc:
  6172. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6173. # Determine bounding area for svg export
  6174. bounds = obj.bounds()
  6175. size = obj.size()
  6176. # Convert everything to strings for use in the xml doc
  6177. svgwidth = str(size[0])
  6178. svgheight = str(size[1])
  6179. minx = str(bounds[0])
  6180. miny = str(bounds[1] - size[1])
  6181. uom = obj.units.lower()
  6182. # Add a SVG Header and footer to the svg output from shapely
  6183. # The transform flips the Y Axis so that everything renders
  6184. # properly within svg apps such as inkscape
  6185. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6186. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6187. svg_header += 'width="' + svgwidth + uom + '" '
  6188. svg_header += 'height="' + svgheight + uom + '" '
  6189. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6190. svg_header += '<g transform="scale(1,-1)">'
  6191. svg_footer = '</g> </svg>'
  6192. svg_elem = svg_header + exported_svg + svg_footer
  6193. # Parse the xml through a xml parser just to add line feeds
  6194. # and to make it look more pretty for the output
  6195. svgcode = parse_xml_string(svg_elem)
  6196. try:
  6197. with open(filename, 'w') as fp:
  6198. fp.write(svgcode.toprettyxml())
  6199. except PermissionError:
  6200. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6201. "Most likely another app is holding the file open and not accessible."))
  6202. return 'fail'
  6203. if self.defaults["global_open_style"] is False:
  6204. self.file_opened.emit("SVG", filename)
  6205. self.file_saved.emit("SVG", filename)
  6206. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  6207. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  6208. """
  6209. Exports a Geometry Object to an SVG file in negative.
  6210. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6211. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6212. :param filename: Path to the SVG file to save to.
  6213. :param boundary: thickness of a black border to surround all the features
  6214. :param scale_factor: factor by which to change/scale the thickness of the features
  6215. :param use_thread: if to be run in a separate thread; boolean
  6216. :return:
  6217. """
  6218. self.report_usage("export_negative()")
  6219. if filename is None:
  6220. filename = self.defaults["global_last_save_folder"]
  6221. self.log.debug("export_svg() negative")
  6222. try:
  6223. obj = self.collection.get_by_name(str(obj_name))
  6224. except:
  6225. # TODO: The return behavior has not been established... should raise exception?
  6226. return "Could not retrieve object: %s" % obj_name
  6227. try:
  6228. box = self.collection.get_by_name(str(box_name))
  6229. except:
  6230. # TODO: The return behavior has not been established... should raise exception?
  6231. return "Could not retrieve object: %s" % box_name
  6232. if box is None:
  6233. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  6234. box = obj
  6235. def make_negative_film():
  6236. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6237. self.progress.emit(40)
  6238. # Determine bounding area for svg export
  6239. bounds = box.bounds()
  6240. size = box.size()
  6241. uom = obj.units.lower()
  6242. # Convert everything to strings for use in the xml doc
  6243. svgwidth = str(size[0] + (2 * boundary))
  6244. svgheight = str(size[1] + (2 * boundary))
  6245. minx = str(bounds[0] - boundary)
  6246. miny = str(bounds[1] + boundary + size[1])
  6247. miny_rect = str(bounds[1] - boundary)
  6248. # Add a SVG Header and footer to the svg output from shapely
  6249. # The transform flips the Y Axis so that everything renders
  6250. # properly within svg apps such as inkscape
  6251. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6252. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6253. svg_header += 'width="' + svgwidth + uom + '" '
  6254. svg_header += 'height="' + svgheight + uom + '" '
  6255. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6256. svg_header += '>'
  6257. svg_header += '<g transform="scale(1,-1)">'
  6258. svg_footer = '</g> </svg>'
  6259. self.progress.emit(60)
  6260. # Change the attributes of the exported SVG
  6261. # We don't need stroke-width - wrong, we do when we have lines with certain width
  6262. # We set opacity to maximum
  6263. # We set the color to WHITE
  6264. root = ET.fromstring(exported_svg)
  6265. for child in root:
  6266. child.set('fill', '#FFFFFF')
  6267. child.set('opacity', '1.0')
  6268. child.set('stroke', '#FFFFFF')
  6269. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  6270. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  6271. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  6272. first_svg_elem_tag = 'rect'
  6273. first_svg_elem_attribs = {
  6274. 'x': minx,
  6275. 'y': miny_rect,
  6276. 'width': svgwidth,
  6277. 'height': svgheight,
  6278. 'id': 'neg_rect',
  6279. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  6280. }
  6281. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  6282. exported_svg = ET.tostring(root)
  6283. svg_elem = svg_header + str(exported_svg) + svg_footer
  6284. self.progress.emit(80)
  6285. # Parse the xml through a xml parser just to add line feeds
  6286. # and to make it look more pretty for the output
  6287. doc = parse_xml_string(svg_elem)
  6288. try:
  6289. with open(filename, 'w') as fp:
  6290. fp.write(doc.toprettyxml())
  6291. except PermissionError:
  6292. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6293. "Most likely another app is holding the file open and not accessible."))
  6294. return 'fail'
  6295. self.progress.emit(100)
  6296. if self.defaults["global_open_style"] is False:
  6297. self.file_opened.emit("SVG", filename)
  6298. self.file_saved.emit("SVG", filename)
  6299. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  6300. if use_thread is True:
  6301. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  6302. def job_thread_film(app_obj):
  6303. try:
  6304. make_negative_film()
  6305. except Exception as e:
  6306. proc.done()
  6307. return
  6308. proc.done()
  6309. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  6310. else:
  6311. make_negative_film()
  6312. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  6313. """
  6314. Exports a Geometry Object to an SVG file in positive black.
  6315. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6316. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6317. :param filename: Path to the SVG file to save to.
  6318. :param scale_factor: factor by which to change/scale the thickness of the features
  6319. :param use_thread: if to be run in a separate thread; boolean
  6320. :return:
  6321. """
  6322. self.report_usage("export_svg_black()")
  6323. if filename is None:
  6324. filename = self.defaults["global_last_save_folder"]
  6325. self.log.debug("export_svg() black")
  6326. try:
  6327. obj = self.collection.get_by_name(str(obj_name))
  6328. except:
  6329. # TODO: The return behavior has not been established... should raise exception?
  6330. return "Could not retrieve object: %s" % obj_name
  6331. try:
  6332. box = self.collection.get_by_name(str(box_name))
  6333. except:
  6334. # TODO: The return behavior has not been established... should raise exception?
  6335. return "Could not retrieve object: %s" % box_name
  6336. if box is None:
  6337. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  6338. box = obj
  6339. def make_black_film():
  6340. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6341. self.progress.emit(40)
  6342. # Change the attributes of the exported SVG
  6343. # We don't need stroke-width
  6344. # We set opacity to maximum
  6345. # We set the colour to WHITE
  6346. root = ET.fromstring(exported_svg)
  6347. for child in root:
  6348. child.set('fill', '#000000')
  6349. child.set('opacity', '1.0')
  6350. child.set('stroke', '#000000')
  6351. exported_svg = ET.tostring(root)
  6352. # Determine bounding area for svg export
  6353. bounds = box.bounds()
  6354. size = box.size()
  6355. # This contain the measure units
  6356. uom = obj.units.lower()
  6357. # Define a boundary around SVG of about 1.0mm (~39mils)
  6358. if uom in "mm":
  6359. boundary = 1.0
  6360. else:
  6361. boundary = 0.0393701
  6362. self.progress.emit(80)
  6363. # Convert everything to strings for use in the xml doc
  6364. svgwidth = str(size[0] + (2 * boundary))
  6365. svgheight = str(size[1] + (2 * boundary))
  6366. minx = str(bounds[0] - boundary)
  6367. miny = str(bounds[1] + boundary + size[1])
  6368. self.log.debug(minx)
  6369. self.log.debug(miny)
  6370. # Add a SVG Header and footer to the svg output from shapely
  6371. # The transform flips the Y Axis so that everything renders
  6372. # properly within svg apps such as inkscape
  6373. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6374. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6375. svg_header += 'width="' + svgwidth + uom + '" '
  6376. svg_header += 'height="' + svgheight + uom + '" '
  6377. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6378. svg_header += '>'
  6379. svg_header += '<g transform="scale(1,-1)">'
  6380. svg_footer = '</g> </svg>'
  6381. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  6382. self.progress.emit(90)
  6383. # Parse the xml through a xml parser just to add line feeds
  6384. # and to make it look more pretty for the output
  6385. doc = parse_xml_string(svg_elem)
  6386. try:
  6387. with open(filename, 'w') as fp:
  6388. fp.write(doc.toprettyxml())
  6389. except PermissionError:
  6390. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6391. "Most likely another app is holding the file open and not accessible."))
  6392. return 'fail'
  6393. self.progress.emit(100)
  6394. if self.defaults["global_open_style"] is False:
  6395. self.file_opened.emit("SVG", filename)
  6396. self.file_saved.emit("SVG", filename)
  6397. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  6398. if use_thread is True:
  6399. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  6400. def job_thread_film(app_obj):
  6401. try:
  6402. make_black_film()
  6403. except Exception as e:
  6404. proc.done()
  6405. return
  6406. proc.done()
  6407. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  6408. else:
  6409. make_black_film()
  6410. def save_source_file(self, obj_name, filename, use_thread=True):
  6411. """
  6412. Exports a FlatCAM Object to an Gerber/Excellon file.
  6413. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6414. :param filename: Path to the Gerber file to save to.
  6415. :param use_thread: if to be run in a separate thread
  6416. :return:
  6417. """
  6418. self.report_usage("save source file()")
  6419. if filename is None:
  6420. filename = self.defaults["global_last_save_folder"]
  6421. self.log.debug("save source file()")
  6422. obj = self.collection.get_by_name(obj_name)
  6423. file_string = StringIO(obj.source_file)
  6424. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6425. try:
  6426. with open(filename, 'w') as file:
  6427. file.writelines('G04*\n')
  6428. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6429. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6430. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6431. file.writelines('G04 Created on : %s*\n' % time_string)
  6432. for line in file_string:
  6433. file.writelines(line)
  6434. except PermissionError:
  6435. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6436. "Most likely another app is holding the file open and not accessible."))
  6437. return 'fail'
  6438. def export_excellon(self, obj_name, filename, use_thread=True):
  6439. """
  6440. Exports a Excellon Object to an Excellon file.
  6441. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6442. :param filename: Path to the Excellon file to save to.
  6443. :param use_thread: if to be run in a separate thread
  6444. :return:
  6445. """
  6446. self.report_usage("export_excellon()")
  6447. if filename is None:
  6448. filename = self.defaults["global_last_save_folder"]
  6449. self.log.debug("export_excellon()")
  6450. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6451. self.defaults["excellon_exp_decimals"]
  6452. )
  6453. units = ''
  6454. try:
  6455. obj = self.collection.get_by_name(str(obj_name))
  6456. except:
  6457. # TODO: The return behavior has not been established... should raise exception?
  6458. return "Could not retrieve object: %s" % obj_name
  6459. # updated units
  6460. eunits = self.defaults["excellon_exp_units"]
  6461. ewhole = self.defaults["excellon_exp_integer"]
  6462. efract = self.defaults["excellon_exp_decimals"]
  6463. ezeros = self.defaults["excellon_exp_zeros"]
  6464. eformat = self.defaults["excellon_exp_format"]
  6465. slot_type = self.defaults["excellon_exp_slot_type"]
  6466. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6467. if fc_units == 'MM':
  6468. factor = 1 if eunits == 'METRIC' else 0.03937
  6469. else:
  6470. factor = 25.4 if eunits == 'METRIC' else 1
  6471. def make_excellon():
  6472. try:
  6473. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6474. header = 'M48\n'
  6475. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6476. (str(self.version), str(self.version_date))
  6477. header += ';Filename: %s' % str(obj_name) + '\n'
  6478. header += ';Created on : %s' % time_str + '\n'
  6479. if eformat == 'dec':
  6480. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6481. header += eunits + '\n'
  6482. for tool in obj.tools:
  6483. if eunits == 'METRIC':
  6484. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6485. tool=str(tool),
  6486. dec=2)
  6487. else:
  6488. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6489. tool=str(tool),
  6490. dec=4)
  6491. else:
  6492. if ezeros == 'LZ':
  6493. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6494. form='ndec', e_zeros='LZ', factor=factor,
  6495. slot_type=slot_type)
  6496. header += '%s,%s\n' % (eunits, 'LZ')
  6497. header += format_exc
  6498. for tool in obj.tools:
  6499. if eunits == 'METRIC':
  6500. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6501. tool=str(tool),
  6502. dec=2)
  6503. else:
  6504. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6505. tool=str(tool),
  6506. dec=4)
  6507. else:
  6508. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6509. form='ndec', e_zeros='TZ', factor=factor,
  6510. slot_type=slot_type)
  6511. header += '%s,%s\n' % (eunits, 'TZ')
  6512. header += format_exc
  6513. for tool in obj.tools:
  6514. if eunits == 'METRIC':
  6515. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6516. tool=str(tool),
  6517. dec=2)
  6518. else:
  6519. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6520. tool=str(tool),
  6521. dec=4)
  6522. header += '%\n'
  6523. footer = 'M30\n'
  6524. exported_excellon = header
  6525. exported_excellon += excellon_code
  6526. exported_excellon += footer
  6527. try:
  6528. with open(filename, 'w') as fp:
  6529. fp.write(exported_excellon)
  6530. except PermissionError:
  6531. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6532. "Most likely another app is holding the file open and not accessible."))
  6533. return 'fail'
  6534. if self.defaults["global_open_style"] is False:
  6535. self.file_opened.emit("Excellon", filename)
  6536. self.file_saved.emit("Excellon", filename)
  6537. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  6538. except Exception as e:
  6539. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6540. return 'fail'
  6541. if use_thread is True:
  6542. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6543. def job_thread_exc(app_obj):
  6544. ret = make_excellon()
  6545. if ret == 'fail':
  6546. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  6547. return
  6548. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6549. else:
  6550. ret = make_excellon()
  6551. if ret == 'fail':
  6552. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  6553. return
  6554. def export_gerber(self, obj_name, filename, use_thread=True):
  6555. """
  6556. Exports a Gerber Object to an Gerber file.
  6557. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6558. :param filename: Path to the Gerber file to save to.
  6559. :param use_thread: if to be run in a separate thread
  6560. :return:
  6561. """
  6562. self.report_usage("export_gerber()")
  6563. if filename is None:
  6564. filename = self.defaults["global_last_save_folder"]
  6565. self.log.debug("export_gerber()")
  6566. try:
  6567. obj = self.collection.get_by_name(str(obj_name))
  6568. except:
  6569. # TODO: The return behavior has not been established... should raise exception?
  6570. return "Could not retrieve object: %s" % obj_name
  6571. # updated units
  6572. gunits = self.defaults["gerber_exp_units"]
  6573. gwhole = self.defaults["gerber_exp_integer"]
  6574. gfract = self.defaults["gerber_exp_decimals"]
  6575. gzeros = self.defaults["gerber_exp_zeros"]
  6576. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6577. if fc_units == 'MM':
  6578. factor = 1 if gunits == 'MM' else 0.03937
  6579. else:
  6580. factor = 25.4 if gunits == 'MM' else 1
  6581. def make_gerber():
  6582. try:
  6583. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6584. header = 'G04*\n'
  6585. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6586. (str(self.version), str(self.version_date))
  6587. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6588. header += 'G04 Created on : %s*' % time_str + '\n'
  6589. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6590. header += "%MO{units}*%\n".format(units=gunits)
  6591. for apid in obj.apertures:
  6592. if obj.apertures[apid]['type'] == 'C':
  6593. header += "%ADD{apid}{type},{size}*%\n".format(
  6594. apid=str(apid),
  6595. type='C',
  6596. size=(factor * obj.apertures[apid]['size'])
  6597. )
  6598. elif obj.apertures[apid]['type'] == 'R':
  6599. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6600. apid=str(apid),
  6601. type='R',
  6602. width=(factor * obj.apertures[apid]['width']),
  6603. height=(factor * obj.apertures[apid]['height'])
  6604. )
  6605. elif obj.apertures[apid]['type'] == 'O':
  6606. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6607. apid=str(apid),
  6608. type='O',
  6609. width=(factor * obj.apertures[apid]['width']),
  6610. height=(factor * obj.apertures[apid]['height'])
  6611. )
  6612. header += '\n'
  6613. # obsolete units but some software may need it
  6614. if gunits == 'IN':
  6615. header += 'G70*\n'
  6616. else:
  6617. header += 'G71*\n'
  6618. # Absolute Mode
  6619. header += 'G90*\n'
  6620. header += 'G01*\n'
  6621. # positive polarity
  6622. header += '%LPD*%\n'
  6623. footer = 'M02*\n'
  6624. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6625. exported_gerber = header
  6626. exported_gerber += gerber_code
  6627. exported_gerber += footer
  6628. try:
  6629. with open(filename, 'w') as fp:
  6630. fp.write(exported_gerber)
  6631. except PermissionError:
  6632. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6633. "Most likely another app is holding the file open and not accessible."))
  6634. return 'fail'
  6635. if self.defaults["global_open_style"] is False:
  6636. self.file_opened.emit("Gerber", filename)
  6637. self.file_saved.emit("Gerber", filename)
  6638. self.inform.emit(_("[success] Gerber file exported to %s") % filename)
  6639. except Exception as e:
  6640. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6641. return 'fail'
  6642. if use_thread is True:
  6643. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6644. def job_thread_exc(app_obj):
  6645. ret = make_gerber()
  6646. if ret == 'fail':
  6647. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  6648. return
  6649. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6650. else:
  6651. ret = make_gerber()
  6652. if ret == 'fail':
  6653. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  6654. return
  6655. def export_dxf(self, obj_name, filename, use_thread=True):
  6656. """
  6657. Exports a Geometry Object to an DXF file.
  6658. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6659. :param filename: Path to the DXF file to save to.
  6660. :param use_thread: if to be run in a separate thread
  6661. :return:
  6662. """
  6663. self.report_usage("export_dxf()")
  6664. if filename is None:
  6665. filename = self.defaults["global_last_save_folder"]
  6666. self.log.debug("export_dxf()")
  6667. format_exc = ''
  6668. units = ''
  6669. try:
  6670. obj = self.collection.get_by_name(str(obj_name))
  6671. except:
  6672. # TODO: The return behavior has not been established... should raise exception?
  6673. return "Could not retrieve object: %s" % obj_name
  6674. # updated units
  6675. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6676. if units == 'IN' or units == 'INCH':
  6677. units = 'INCH'
  6678. elif units == 'MM' or units == 'METIRC':
  6679. units ='METRIC'
  6680. def make_dxf():
  6681. try:
  6682. dxf_code = obj.export_dxf()
  6683. dxf_code.saveas(filename)
  6684. if self.defaults["global_open_style"] is False:
  6685. self.file_opened.emit("DXF", filename)
  6686. self.file_saved.emit("DXF", filename)
  6687. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  6688. except:
  6689. return 'fail'
  6690. if use_thread is True:
  6691. with self.proc_container.new(_("Exporting DXF")) as proc:
  6692. def job_thread_exc(app_obj):
  6693. ret = make_dxf()
  6694. if ret == 'fail':
  6695. app_obj.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6696. return
  6697. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6698. else:
  6699. ret = make_dxf()
  6700. if ret == 'fail':
  6701. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6702. return
  6703. def import_svg(self, filename, geo_type='geometry', outname=None):
  6704. """
  6705. Adds a new Geometry Object to the projects and populates
  6706. it with shapes extracted from the SVG file.
  6707. :param filename: Path to the SVG file.
  6708. :param outname:
  6709. :return:
  6710. """
  6711. self.report_usage("import_svg()")
  6712. obj_type = ""
  6713. if geo_type is None or geo_type == "geometry":
  6714. obj_type = "geometry"
  6715. elif geo_type == "gerber":
  6716. obj_type = geo_type
  6717. else:
  6718. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6719. "Only Geometry and Gerber are supported"))
  6720. return
  6721. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6722. def obj_init(geo_obj, app_obj):
  6723. geo_obj.import_svg(filename, obj_type, units=units)
  6724. geo_obj.multigeo = False
  6725. with self.proc_container.new(_("Importing SVG")) as proc:
  6726. # Object name
  6727. name = outname or filename.split('/')[-1].split('\\')[-1]
  6728. self.new_object(obj_type, name, obj_init, autoselected=False)
  6729. self.progress.emit(20)
  6730. # Register recent file
  6731. self.file_opened.emit("svg", filename)
  6732. # GUI feedback
  6733. self.inform.emit(_("[success] Opened: %s") % filename)
  6734. self.progress.emit(100)
  6735. def import_dxf(self, filename, geo_type='geometry', outname=None):
  6736. """
  6737. Adds a new Geometry Object to the projects and populates
  6738. it with shapes extracted from the DXF file.
  6739. :param filename: Path to the DXF file.
  6740. :param outname:
  6741. :type putname: str
  6742. :return:
  6743. """
  6744. self.report_usage("import_dxf()")
  6745. obj_type = ""
  6746. if geo_type is None or geo_type == "geometry":
  6747. obj_type = "geometry"
  6748. elif geo_type == "gerber":
  6749. obj_type = geo_type
  6750. else:
  6751. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6752. "Only Geometry and Gerber are supported"))
  6753. return
  6754. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6755. def obj_init(geo_obj, app_obj):
  6756. geo_obj.import_dxf(filename, obj_type, units=units)
  6757. geo_obj.multigeo = False
  6758. with self.proc_container.new(_("Importing DXF")) as proc:
  6759. # Object name
  6760. name = outname or filename.split('/')[-1].split('\\')[-1]
  6761. self.new_object(obj_type, name, obj_init, autoselected=False)
  6762. self.progress.emit(20)
  6763. # Register recent file
  6764. self.file_opened.emit("dxf", filename)
  6765. # GUI feedback
  6766. self.inform.emit(_("[success] Opened: %s") % filename)
  6767. self.progress.emit(100)
  6768. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  6769. """
  6770. Adds a new Geometry Object to the projects and populates
  6771. it with shapes extracted from the SVG file.
  6772. :param filename: Path to the SVG file.
  6773. :param o_type: type of FlatCAM objeect
  6774. :param dpi: dot per inch
  6775. :param mode: black or color
  6776. :param mask: dictate the level of detail
  6777. :param outname: name for the resulting file
  6778. :return:
  6779. """
  6780. self.report_usage("import_image()")
  6781. if o_type is None or o_type == "geometry":
  6782. obj_type = "geometry"
  6783. elif o_type == "gerber":
  6784. obj_type = o_type
  6785. else:
  6786. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6787. "Only Geometry and Gerber are supported"))
  6788. return
  6789. def obj_init(geo_obj, app_obj):
  6790. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  6791. geo_obj.multigeo = False
  6792. with self.proc_container.new(_("Importing Image")) as proc:
  6793. # Object name
  6794. name = outname or filename.split('/')[-1].split('\\')[-1]
  6795. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  6796. self.new_object(obj_type, name, obj_init)
  6797. self.progress.emit(20)
  6798. # Register recent file
  6799. self.file_opened.emit("image", filename)
  6800. # GUI feedback
  6801. self.inform.emit(_("[success] Opened: %s") % filename)
  6802. self.progress.emit(100)
  6803. def open_gerber(self, filename, outname=None):
  6804. """
  6805. Opens a Gerber file, parses it and creates a new object for
  6806. it in the program. Thread-safe.
  6807. :param outname: Name of the resulting object. None causes the
  6808. name to be that of the file.
  6809. :param filename: Gerber file filename
  6810. :type filename: str
  6811. :param follow: If true, the parser will not create polygons, just lines
  6812. following the gerber path.
  6813. :type follow: bool
  6814. :return: None
  6815. """
  6816. # How the object should be initialized
  6817. def obj_init(gerber_obj, app_obj):
  6818. assert isinstance(gerber_obj, FlatCAMGerber), \
  6819. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  6820. # Opening the file happens here
  6821. self.progress.emit(30)
  6822. try:
  6823. gerber_obj.parse_file(filename)
  6824. except IOError:
  6825. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  6826. app_obj.progress.emit(0)
  6827. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  6828. return "fail"
  6829. except ParseError as err:
  6830. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename,
  6831. error=str(err)))
  6832. app_obj.progress.emit(0)
  6833. self.log.error(str(err))
  6834. return "fail"
  6835. except Exception as e:
  6836. log.debug("App.open_gerber() --> %s" % str(e))
  6837. msg = _("[ERROR] An internal error has occurred. See shell.\n")
  6838. msg += traceback.format_exc()
  6839. app_obj.inform.emit(msg)
  6840. return "fail"
  6841. if gerber_obj.is_empty():
  6842. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  6843. # self.collection.set_active(gerber_obj.options["name"])
  6844. # self.collection.delete_active()
  6845. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  6846. return "fail"
  6847. # Further parsing
  6848. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  6849. App.log.debug("open_gerber()")
  6850. with self.proc_container.new(_("Opening Gerber")) as proc:
  6851. self.progress.emit(10)
  6852. # Object name
  6853. name = outname or filename.split('/')[-1].split('\\')[-1]
  6854. # # ## Object creation # ##
  6855. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  6856. if ret == 'fail':
  6857. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  6858. return
  6859. # Register recent file
  6860. self.file_opened.emit("gerber", filename)
  6861. self.progress.emit(100)
  6862. # GUI feedback
  6863. self.inform.emit(_("[success] Opened: %s") % filename)
  6864. def open_excellon(self, filename, outname=None):
  6865. """
  6866. Opens an Excellon file, parses it and creates a new object for
  6867. it in the program. Thread-safe.
  6868. :param outname: Name of the resulting object. None causes the
  6869. name to be that of the file.
  6870. :param filename: Excellon file filename
  6871. :type filename: str
  6872. :return: None
  6873. """
  6874. App.log.debug("open_excellon()")
  6875. # How the object should be initialized
  6876. def obj_init(excellon_obj, app_obj):
  6877. # self.progress.emit(20)
  6878. try:
  6879. ret = excellon_obj.parse_file(filename=filename)
  6880. if ret == "fail":
  6881. log.debug("Excellon parsing failed.")
  6882. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  6883. return "fail"
  6884. except IOError:
  6885. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  6886. log.debug("Could not open Excellon object.")
  6887. self.progress.emit(0) # TODO: self and app_bjj mixed
  6888. return "fail"
  6889. except:
  6890. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  6891. msg += traceback.format_exc()
  6892. app_obj.inform.emit(msg)
  6893. return "fail"
  6894. ret = excellon_obj.create_geometry()
  6895. if ret == 'fail':
  6896. log.debug("Could not create geometry for Excellon object.")
  6897. return "fail"
  6898. for tool in excellon_obj.tools:
  6899. if excellon_obj.tools[tool]['solid_geometry']:
  6900. return
  6901. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  6902. return "fail"
  6903. with self.proc_container.new(_("Opening Excellon.")):
  6904. # Object name
  6905. name = outname or filename.split('/')[-1].split('\\')[-1]
  6906. ret_val = self.new_object("excellon", name, obj_init, autoselected=False)
  6907. if ret_val == 'fail':
  6908. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  6909. return
  6910. # Register recent file
  6911. self.file_opened.emit("excellon", filename)
  6912. # GUI feedback
  6913. self.inform.emit(_("[success] Opened: %s") % filename)
  6914. def open_gcode(self, filename, outname=None):
  6915. """
  6916. Opens a G-gcode file, parses it and creates a new object for
  6917. it in the program. Thread-safe.
  6918. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6919. :param filename: G-code file filename
  6920. :type filename: str
  6921. :return: None
  6922. """
  6923. App.log.debug("open_gcode()")
  6924. # How the object should be initialized
  6925. def obj_init(job_obj, app_obj_):
  6926. """
  6927. :param job_obj: the resulting object
  6928. :type app_obj_: App
  6929. """
  6930. assert isinstance(app_obj_, App), \
  6931. "Initializer expected App, got %s" % type(app_obj_)
  6932. self.progress.emit(10)
  6933. try:
  6934. f = open(filename)
  6935. gcode = f.read()
  6936. f.close()
  6937. except IOError:
  6938. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  6939. self.progress.emit(0)
  6940. return "fail"
  6941. job_obj.gcode = gcode
  6942. self.progress.emit(20)
  6943. ret = job_obj.gcode_parse()
  6944. if ret == "fail":
  6945. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  6946. return "fail"
  6947. self.progress.emit(60)
  6948. job_obj.create_geometry()
  6949. with self.proc_container.new(_("Opening G-Code.")):
  6950. # Object name
  6951. name = outname or filename.split('/')[-1].split('\\')[-1]
  6952. # New object creation and file processing
  6953. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  6954. if ret == 'fail':
  6955. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  6956. "Attempting to create a FlatCAM CNCJob Object from "
  6957. "G-Code file failed during processing"))
  6958. return "fail"
  6959. # Register recent file
  6960. self.file_opened.emit("cncjob", filename)
  6961. # GUI feedback
  6962. self.inform.emit(_("[success] Opened: %s") % filename)
  6963. self.progress.emit(100)
  6964. def open_config_file(self, filename, run_from_arg=None):
  6965. """
  6966. Loads a config file from the specified file.
  6967. :param filename: Name of the file from which to load.
  6968. :type filename: str
  6969. :return: None
  6970. """
  6971. App.log.debug("Opening config file: " + filename)
  6972. # add the tab if it was closed
  6973. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  6974. # first clear previous text in text editor (if any)
  6975. self.ui.code_editor.clear()
  6976. # Switch plot_area to CNCJob tab
  6977. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6978. try:
  6979. if filename:
  6980. f = QtCore.QFile(filename)
  6981. if f.open(QtCore.QIODevice.ReadOnly):
  6982. stream = QtCore.QTextStream(f)
  6983. gcode_edited = stream.readAll()
  6984. self.ui.code_editor.setPlainText(gcode_edited)
  6985. f.close()
  6986. except IOError:
  6987. App.log.error("Failed to open config file: %s" % filename)
  6988. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  6989. return
  6990. def open_project(self, filename, run_from_arg=None):
  6991. """
  6992. Loads a project from the specified file.
  6993. 1) Loads and parses file
  6994. 2) Registers the file as recently opened.
  6995. 3) Calls on_file_new()
  6996. 4) Updates options
  6997. 5) Calls new_object() with the object's from_dict() as init method.
  6998. 6) Calls plot_all()
  6999. :param filename: Name of the file from which to load.
  7000. :type filename: str
  7001. :param run_from_arg: True if run for arguments
  7002. :return: None
  7003. """
  7004. App.log.debug("Opening project: " + filename)
  7005. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7006. # Open and parse an uncompressed Project file
  7007. try:
  7008. f = open(filename, 'r')
  7009. except IOError:
  7010. App.log.error("Failed to open project file: %s" % filename)
  7011. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  7012. return
  7013. try:
  7014. d = json.load(f, object_hook=dict2obj)
  7015. except Exception as e:
  7016. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7017. (filename, str(e)))
  7018. f.close()
  7019. # Open and parse a compressed Project file
  7020. try:
  7021. with lzma.open(filename) as f:
  7022. file_content = f.read().decode('utf-8')
  7023. d = json.loads(file_content, object_hook=dict2obj)
  7024. except Exception as e:
  7025. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7026. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  7027. return
  7028. # Clear the current project
  7029. # # NOT THREAD SAFE # ##
  7030. if run_from_arg is True:
  7031. pass
  7032. else:
  7033. self.on_file_new()
  7034. # Project options
  7035. self.options.update(d['options'])
  7036. self.project_filename = filename
  7037. self.set_screen_units(self.options["units"])
  7038. # Re create objects
  7039. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7040. for obj in d['objs']:
  7041. def obj_init(obj_inst, app_inst):
  7042. obj_inst.from_dict(obj)
  7043. App.log.debug("Recreating from opened project an %s object: %s" %
  7044. (obj['kind'].capitalize(), obj['options']['name']))
  7045. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  7046. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  7047. # self.plot_all()
  7048. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  7049. self.should_we_save = False
  7050. self.file_opened.emit("project", filename)
  7051. self.set_ui_title(name=self.project_filename)
  7052. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7053. def propagate_defaults(self, silent=False):
  7054. """
  7055. This method is used to set default values in classes. It's
  7056. an alternative to project options but allows the use
  7057. of values invisible to the user.
  7058. :return: None
  7059. """
  7060. if silent is False:
  7061. self.log.debug("propagate_defaults()")
  7062. # Which objects to update the given parameters.
  7063. routes = {
  7064. "global_zdownrate": CNCjob,
  7065. "excellon_zeros": Excellon,
  7066. "excellon_format_upper_in": Excellon,
  7067. "excellon_format_lower_in": Excellon,
  7068. "excellon_format_upper_mm": Excellon,
  7069. "excellon_format_lower_mm": Excellon,
  7070. "excellon_units": Excellon,
  7071. "gerber_use_buffer_for_union": Gerber,
  7072. "geometry_multidepth": Geometry
  7073. }
  7074. for param in routes:
  7075. if param in routes[param].defaults:
  7076. try:
  7077. routes[param].defaults[param] = self.defaults[param]
  7078. if silent is False:
  7079. self.log.debug(" " + param + " OK")
  7080. except KeyError:
  7081. if silent is False:
  7082. self.log.debug(" ERROR: " + param + " not in defaults.")
  7083. else:
  7084. # Try extracting the name:
  7085. # classname_param here is param in the object
  7086. if param.find(routes[param].__name__.lower() + "_") == 0:
  7087. p = param[len(routes[param].__name__) + 1:]
  7088. if p in routes[param].defaults:
  7089. routes[param].defaults[p] = self.defaults[param]
  7090. if silent is False:
  7091. self.log.debug(" " + param + " OK!")
  7092. def restore_main_win_geom(self):
  7093. try:
  7094. self.ui.setGeometry(self.defaults["global_def_win_x"],
  7095. self.defaults["global_def_win_y"],
  7096. self.defaults["global_def_win_w"],
  7097. self.defaults["global_def_win_h"])
  7098. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  7099. settings = QSettings("Open Source", "FlatCAM")
  7100. if settings.contains("maximized_gui"):
  7101. maximized_ui = settings.value('maximized_gui', type=bool)
  7102. if maximized_ui is True:
  7103. self.ui.showMaximized()
  7104. except KeyError as e:
  7105. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  7106. def plot_all(self, zoom=True):
  7107. """
  7108. Re-generates all plots from all objects.
  7109. :return: None
  7110. """
  7111. self.log.debug("Plot_all()")
  7112. for obj in self.collection.get_list():
  7113. def worker_task(obj):
  7114. with self.proc_container.new("Plotting"):
  7115. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7116. if zoom:
  7117. self.object_plotted.emit(obj)
  7118. # Send to worker
  7119. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  7120. def register_folder(self, filename):
  7121. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7122. def register_save_folder(self, filename):
  7123. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7124. def set_progress_bar(self, percentage, text=""):
  7125. self.ui.progress_bar.setValue(int(percentage))
  7126. def setup_shell(self):
  7127. """
  7128. Creates shell functions. Runs once at startup.
  7129. :return: None
  7130. """
  7131. self.log.debug("setup_shell()")
  7132. def shelp(p=None):
  7133. if not p:
  7134. return _("Available commands:\n") + \
  7135. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  7136. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  7137. if p not in commands:
  7138. return "Unknown command: %s" % p
  7139. return commands[p]["help"]
  7140. # --- Migrated to new architecture ---
  7141. # def options(name):
  7142. # ops = self.collection.get_by_name(str(name)).options
  7143. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  7144. def h(*args):
  7145. """
  7146. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  7147. and standalone parameters into list.
  7148. """
  7149. kwa = {}
  7150. a = []
  7151. n = len(args)
  7152. name = None
  7153. for i in range(n):
  7154. match = re.search(r'^-([a-zA-Z].*)', args[i])
  7155. if match:
  7156. assert name is None
  7157. name = match.group(1)
  7158. continue
  7159. if name is None:
  7160. a.append(args[i])
  7161. else:
  7162. kwa[name] = args[i]
  7163. name = None
  7164. return a, kwa
  7165. @contextmanager
  7166. def wait_signal(signal, timeout=10000):
  7167. """
  7168. Block loop until signal emitted, timeout (ms) elapses
  7169. or unhandled exception happens in a thread.
  7170. :param timeout: time after which the loop is exited
  7171. :param signal: Signal to wait for.
  7172. """
  7173. loop = QtCore.QEventLoop()
  7174. # Normal termination
  7175. signal.connect(loop.quit)
  7176. # Termination by exception in thread
  7177. self.thread_exception.connect(loop.quit)
  7178. status = {'timed_out': False}
  7179. def report_quit():
  7180. status['timed_out'] = True
  7181. loop.quit()
  7182. yield
  7183. # Temporarily change how exceptions are managed.
  7184. oeh = sys.excepthook
  7185. ex = []
  7186. def except_hook(type_, value, traceback_):
  7187. ex.append(value)
  7188. oeh(type_, value, traceback_)
  7189. sys.excepthook = except_hook
  7190. # Terminate on timeout
  7191. if timeout is not None:
  7192. QtCore.QTimer.singleShot(timeout, report_quit)
  7193. # # ## Block ## ##
  7194. loop.exec_()
  7195. # Restore exception management
  7196. sys.excepthook = oeh
  7197. if ex:
  7198. self.raiseTclError(str(ex[0]))
  7199. if status['timed_out']:
  7200. raise Exception('Timed out!')
  7201. def make_docs():
  7202. output = ''
  7203. import collections
  7204. od = collections.OrderedDict(sorted(commands.items()))
  7205. for cmd_, val in od.items():
  7206. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  7207. t = val['help']
  7208. usage_i = t.find('>')
  7209. if usage_i < 0:
  7210. expl = t
  7211. output += expl + '\n\n'
  7212. continue
  7213. expl = t[:usage_i - 1]
  7214. output += expl + '\n\n'
  7215. end_usage_i = t[usage_i:].find('\n')
  7216. if end_usage_i < 0:
  7217. end_usage_i = len(t[usage_i:])
  7218. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  7219. else:
  7220. extras = t[usage_i+end_usage_i+1:]
  7221. parts = [s.strip() for s in extras.split('\n')]
  7222. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  7223. for p in parts:
  7224. output += ' ' + p + '\n\n'
  7225. return output
  7226. '''
  7227. Howto implement TCL shell commands:
  7228. All parameters passed to command should be possible to set as None and test it afterwards.
  7229. This is because we need to see error caused in tcl,
  7230. if None value as default parameter is not allowed TCL will return empty error.
  7231. Use:
  7232. def mycommand(name=None,...):
  7233. Test it like this:
  7234. if name is None:
  7235. self.raise_tcl_error('Argument name is missing.')
  7236. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  7237. otherwise we will miss it and processing will silently continue.
  7238. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  7239. which is catched in exec_command and displayed in TCL shell console with red background.
  7240. Error in console is displayed with TCL trace.
  7241. This behavior works only within main thread,
  7242. errors with promissed tasks can be catched and detected only with log.
  7243. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  7244. TCL shell.
  7245. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  7246. '''
  7247. commands = {
  7248. 'help': {
  7249. 'fcn': shelp,
  7250. 'help': _("Shows list of commands.")
  7251. },
  7252. }
  7253. # Import/overwrite tcl commands as objects of TclCommand descendants
  7254. # This modifies the variable 'commands'.
  7255. tclCommands.register_all_commands(self, commands)
  7256. # Add commands to the tcl interpreter
  7257. for cmd in commands:
  7258. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  7259. # Make the tcl puts function return instead of print to stdout
  7260. self.tcl.eval('''
  7261. rename puts original_puts
  7262. proc puts {args} {
  7263. if {[llength $args] == 1} {
  7264. return "[lindex $args 0]"
  7265. } else {
  7266. eval original_puts $args
  7267. }
  7268. }
  7269. ''')
  7270. def setup_recent_items(self):
  7271. # TODO: Move this to constructor
  7272. icons = {
  7273. "gerber": "share/flatcam_icon16.png",
  7274. "excellon": "share/drill16.png",
  7275. 'geometry': "share/geometry16.png",
  7276. "cncjob": "share/cnc16.png",
  7277. "project": "share/project16.png",
  7278. "svg": "share/geometry16.png",
  7279. "dxf": "share/dxf16.png",
  7280. "pdf": "share/pdf32.png",
  7281. "image": "share/image16.png"
  7282. }
  7283. openers = {
  7284. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7285. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7286. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7287. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7288. 'project': self.open_project,
  7289. 'svg': self.import_svg,
  7290. 'dxf': self.import_dxf,
  7291. 'image': self.import_image,
  7292. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7293. }
  7294. # Open recent file for files
  7295. try:
  7296. f = open(self.data_path + '/recent.json')
  7297. except IOError:
  7298. App.log.error("Failed to load recent item list.")
  7299. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  7300. return
  7301. try:
  7302. self.recent = json.load(f)
  7303. except json.scanner.JSONDecodeError:
  7304. App.log.error("Failed to parse recent item list.")
  7305. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  7306. f.close()
  7307. return
  7308. f.close()
  7309. # Open recent file for projects
  7310. try:
  7311. fp = open(self.data_path + '/recent_projects.json')
  7312. except IOError:
  7313. App.log.error("Failed to load recent project item list.")
  7314. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent projects item list."))
  7315. return
  7316. try:
  7317. self.recent_projects = json.load(fp)
  7318. except json.scanner.JSONDecodeError:
  7319. App.log.error("Failed to parse recent project item list.")
  7320. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent project item list."))
  7321. fp.close()
  7322. return
  7323. fp.close()
  7324. # Closure needed to create callbacks in a loop.
  7325. # Otherwise late binding occurs.
  7326. def make_callback(func, fname):
  7327. def opener():
  7328. func(fname)
  7329. return opener
  7330. def reset_recent_files():
  7331. # Reset menu
  7332. self.ui.recent.clear()
  7333. self.recent = []
  7334. try:
  7335. f = open(self.data_path + '/recent.json', 'w')
  7336. except IOError:
  7337. App.log.error("Failed to open recent items file for writing.")
  7338. return
  7339. json.dump(self.recent, f)
  7340. def reset_recent_projects():
  7341. # Reset menu
  7342. self.ui.recent_projects.clear()
  7343. self.recent_projects = []
  7344. try:
  7345. fp = open(self.data_path + '/recent_projects.json', 'w')
  7346. except IOError:
  7347. App.log.error("Failed to open recent projects items file for writing.")
  7348. return
  7349. json.dump(self.recent, fp)
  7350. # Reset menu
  7351. self.ui.recent.clear()
  7352. self.ui.recent_projects.clear()
  7353. # Create menu items for projects
  7354. for recent in self.recent_projects:
  7355. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7356. if recent['kind'] == 'project':
  7357. try:
  7358. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7359. # Attach callback
  7360. o = make_callback(openers[recent["kind"]], recent['filename'])
  7361. action.triggered.connect(o)
  7362. self.ui.recent_projects.addAction(action)
  7363. except KeyError:
  7364. App.log.error("Unsupported file type: %s" % recent["kind"])
  7365. # Last action in Recent Files menu is one that Clear the content
  7366. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  7367. clear_action_proj.triggered.connect(reset_recent_projects)
  7368. self.ui.recent_projects.addSeparator()
  7369. self.ui.recent_projects.addAction(clear_action_proj)
  7370. # Create menu items for files
  7371. for recent in self.recent:
  7372. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7373. if recent['kind'] != 'project':
  7374. try:
  7375. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7376. # Attach callback
  7377. o = make_callback(openers[recent["kind"]], recent['filename'])
  7378. action.triggered.connect(o)
  7379. self.ui.recent.addAction(action)
  7380. except KeyError:
  7381. App.log.error("Unsupported file type: %s" % recent["kind"])
  7382. # Last action in Recent Files menu is one that Clear the content
  7383. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  7384. clear_action.triggered.connect(reset_recent_files)
  7385. self.ui.recent.addSeparator()
  7386. self.ui.recent.addAction(clear_action)
  7387. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7388. # self.ui.menufilerecent.set_submenu(recent_menu)
  7389. # recent_menu.show_all()
  7390. # self.ui.recent.show()
  7391. self.log.debug("Recent items list has been populated.")
  7392. def setup_component_editor(self):
  7393. # label = QtWidgets.QLabel("Choose an item from Project")
  7394. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7395. sel_title = QtWidgets.QTextEdit(
  7396. _('<b>Shortcut Key List</b>'))
  7397. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7398. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7399. settings = QSettings("Open Source", "FlatCAM")
  7400. if settings.contains("notebook_font_size"):
  7401. fsize = settings.value('notebook_font_size', type=int)
  7402. else:
  7403. fsize = 12
  7404. tsize = fsize + int(fsize / 2)
  7405. selected_text = _('''
  7406. <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  7407. <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7408. The normal flow when working in FlatCAM is the following:</span></p>
  7409. <ol>
  7410. <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  7411. <br />
  7412. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  7413. &nbsp;</li>
  7414. <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7415. <br />
  7416. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  7417. <br />
  7418. You can change the parameters in this screen and the flow direction is like this:<br />
  7419. <br />
  7420. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7421. </ol>
  7422. <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  7423. '''.format(fsize=fsize, tsize=tsize))
  7424. sel_title.setText(selected_text)
  7425. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7426. self.ui.selected_scroll_area.setWidget(sel_title)
  7427. def setup_obj_classes(self):
  7428. """
  7429. Sets up application specifics on the FlatCAMObj class.
  7430. :return: None
  7431. """
  7432. FlatCAMObj.app = self
  7433. ObjectCollection.app = self
  7434. Gerber.app = self
  7435. Excellon.app = self
  7436. Geometry.app = self
  7437. CNCjob.app = self
  7438. FCProcess.app = self
  7439. FCProcessContainer.app = self
  7440. def version_check(self):
  7441. """
  7442. Checks for the latest version of the program. Alerts the
  7443. user if theirs is outdated. This method is meant to be run
  7444. in a separate thread.
  7445. :return: None
  7446. """
  7447. self.log.debug("version_check()")
  7448. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7449. full_url = App.version_url + \
  7450. "?s=" + str(self.defaults['global_serial']) + \
  7451. "&v=" + str(self.version) + \
  7452. "&os=" + str(self.os) + \
  7453. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  7454. else:
  7455. # no_stats dict; just so it won't break things on website
  7456. no_ststs_dict = {}
  7457. no_ststs_dict["global_ststs"] = {}
  7458. full_url = App.version_url + \
  7459. "?s=" + str(self.defaults['global_serial']) + \
  7460. "&v=" + str(self.version) + \
  7461. "&os=" + str(self.os) + \
  7462. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7463. App.log.debug("Checking for updates @ %s" % full_url)
  7464. # ## Get the data
  7465. try:
  7466. f = urllib.request.urlopen(full_url)
  7467. except:
  7468. # App.log.warning("Failed checking for latest version. Could not connect.")
  7469. self.log.warning("Failed checking for latest version. Could not connect.")
  7470. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  7471. return
  7472. try:
  7473. data = json.load(f)
  7474. except Exception as e:
  7475. App.log.error("Could not parse information about latest version.")
  7476. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  7477. App.log.debug("json.load(): %s" % str(e))
  7478. f.close()
  7479. return
  7480. f.close()
  7481. # ## Latest version?
  7482. if self.version >= data["version"]:
  7483. App.log.debug("FlatCAM is up to date!")
  7484. self.inform.emit(_("[success] FlatCAM is up to date!"))
  7485. return
  7486. App.log.debug("Newer version available.")
  7487. self.message.emit(
  7488. _("Newer Version Available"),
  7489. _("There is a newer version of FlatCAM available for download:\n\n") +
  7490. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  7491. _("info")
  7492. )
  7493. def on_plotcanvas_setup(self, container=None):
  7494. """
  7495. This is doing the setup for the plot area (VisPy canvas)
  7496. :param container: widget where to install the canvas
  7497. :return: None
  7498. """
  7499. if container:
  7500. plot_container = container
  7501. else:
  7502. plot_container = self.ui.right_layout
  7503. self.plotcanvas = PlotCanvas(plot_container, self)
  7504. # So it can receive key presses
  7505. self.plotcanvas.native.setFocus()
  7506. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  7507. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  7508. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7509. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  7510. # Keys over plot enabled
  7511. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  7512. self.app_cursor = self.plotcanvas.new_cursor()
  7513. self.app_cursor.enabled = False
  7514. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7515. def on_zoom_fit(self, event):
  7516. """
  7517. Callback for zoom-out request. This can be either from the corresponding
  7518. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7519. with axes limits from the geometry bounds of all objects.
  7520. :param event: Ignored.
  7521. :return: None
  7522. """
  7523. self.plotcanvas.fit_view()
  7524. def on_zoom_in(self):
  7525. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7526. def on_zoom_out(self):
  7527. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7528. def disable_all_plots(self):
  7529. self.report_usage("disable_all_plots()")
  7530. self.disable_plots(self.collection.get_list())
  7531. self.inform.emit(_("[success] All plots disabled."))
  7532. def disable_other_plots(self):
  7533. self.report_usage("disable_other_plots()")
  7534. self.disable_plots(self.collection.get_non_selected())
  7535. self.inform.emit(_("[success] All non selected plots disabled."))
  7536. def enable_all_plots(self):
  7537. self.report_usage("enable_all_plots()")
  7538. self.enable_plots(self.collection.get_list())
  7539. self.inform.emit(_("[success] All plots enabled."))
  7540. def on_enable_sel_plots(self):
  7541. log.debug("App.on_enable_sel_plot()")
  7542. object_list = self.collection.get_selected()
  7543. self.enable_plots(objects=object_list)
  7544. self.inform.emit(_("[success] Selected plots enabled..."))
  7545. def on_disable_sel_plots(self):
  7546. log.debug("App.on_disable_sel_plot()")
  7547. # self.inform.emit(_("Disabling plots ..."))
  7548. object_list = self.collection.get_selected()
  7549. self.disable_plots(objects=object_list)
  7550. self.inform.emit(_("[success] Selected plots disabled..."))
  7551. def enable_plots(self, objects):
  7552. """
  7553. Disables plots
  7554. :param objects: list of Objects to be enabled
  7555. :return:
  7556. """
  7557. log.debug("Enabling plots ...")
  7558. self.inform.emit(_("Working ..."))
  7559. for obj in objects:
  7560. if obj.options['plot'] is False:
  7561. obj.options['plot'] = True
  7562. self.plots_updated.emit()
  7563. def disable_plots(self, objects):
  7564. """
  7565. Disables plots
  7566. :param objects: list of Objects to be disabled
  7567. :return:
  7568. """
  7569. # if no objects selected then do nothing
  7570. if not self.collection.get_selected():
  7571. return
  7572. log.debug("Disabling plots ...")
  7573. self.inform.emit(_("Working ..."))
  7574. for obj in objects:
  7575. if obj.options['plot'] is True:
  7576. obj.options['plot'] = False
  7577. self.plots_updated.emit()
  7578. def toggle_plots(self, objects):
  7579. """
  7580. Toggle plots visibility
  7581. :param objects: list of Objects for which to be toggled the visibility
  7582. :return:
  7583. """
  7584. # if no objects selected then do nothing
  7585. if not self.collection.get_selected():
  7586. return
  7587. log.debug("Toggling plots ...")
  7588. self.inform.emit(_("Working ..."))
  7589. for obj in objects:
  7590. if obj.options['plot'] is False:
  7591. obj.options['plot'] = True
  7592. else:
  7593. obj.options['plot'] = False
  7594. self.plots_updated.emit()
  7595. def clear_plots(self):
  7596. objects = self.collection.get_list()
  7597. for obj in objects:
  7598. obj.clear(obj == objects[-1])
  7599. # Clear pool to free memory
  7600. self.clear_pool()
  7601. def generate_cnc_job(self, objects):
  7602. self.report_usage("generate_cnc_job()")
  7603. # for obj in objects:
  7604. # obj.generatecncjob()
  7605. for obj in objects:
  7606. obj.on_generatecnc_button_click()
  7607. def save_project(self, filename, quit_action=False):
  7608. """
  7609. Saves the current project to the specified file.
  7610. :param filename: Name of the file in which to save.
  7611. :type filename: str
  7612. :param quit_action: if the project saving will be followed by an app quit; boolean
  7613. :return: None
  7614. """
  7615. self.log.debug("save_project()")
  7616. self.save_in_progress = True
  7617. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  7618. # Capture the latest changes
  7619. # Current object
  7620. try:
  7621. self.collection.get_active().read_form()
  7622. except:
  7623. self.log.debug("There was no active object")
  7624. pass
  7625. # Project options
  7626. self.options_read_form()
  7627. # Serialize the whole project
  7628. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  7629. "options": self.options,
  7630. "version": self.version}
  7631. if self.defaults["global_save_compressed"] is True:
  7632. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  7633. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  7634. # # Write
  7635. f.write(g)
  7636. self.inform.emit(_("[success] Project saved to: %s") % filename)
  7637. else:
  7638. # Open file
  7639. try:
  7640. f = open(filename, 'w')
  7641. except IOError:
  7642. App.log.error("Failed to open file for saving: %s", filename)
  7643. return
  7644. # Write
  7645. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  7646. f.close()
  7647. # verification of the saved project
  7648. # Open and parse
  7649. try:
  7650. saved_f = open(filename, 'r')
  7651. except IOError:
  7652. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  7653. return
  7654. try:
  7655. saved_d = json.load(saved_f, object_hook=dict2obj)
  7656. except:
  7657. self.inform.emit(
  7658. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  7659. f.close()
  7660. return
  7661. saved_f.close()
  7662. if 'version' in saved_d:
  7663. self.inform.emit(_("[success] Project saved to: %s") % filename)
  7664. else:
  7665. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  7666. settings = QSettings("Open Source", "FlatCAM")
  7667. lock_state = self.ui.lock_action.isChecked()
  7668. settings.setValue('toolbar_lock', lock_state)
  7669. # This will write the setting to the platform specific storage.
  7670. del settings
  7671. # if quit:
  7672. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  7673. # t.start()
  7674. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  7675. def start_delayed_quit(self, delay, filename, should_quit=None):
  7676. """
  7677. :param delay: period of checking if project file size is more than zero; in seconds
  7678. :param filename: the name of the project file to be checked periodically for size more than zero
  7679. :param should_quit: if the task finished will be followed by an app quit; boolean
  7680. :return:
  7681. """
  7682. to_quit = should_quit
  7683. self.save_timer = QtCore.QTimer()
  7684. self.save_timer.setInterval(delay)
  7685. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  7686. self.save_timer.start()
  7687. def check_project_file_size(self, filename, should_quit=None):
  7688. """
  7689. :param filename: the name of the project file to be checked periodically for size more than zero
  7690. :param should_quit: will quit the app if True; boolean
  7691. :return:
  7692. """
  7693. try:
  7694. if os.stat(filename).st_size > 0:
  7695. self.save_in_progress = False
  7696. self.save_timer.stop()
  7697. if should_quit:
  7698. self.app_quit.emit()
  7699. except Exception as e:
  7700. traceback.print_exc()
  7701. def on_options_app2project(self):
  7702. """
  7703. Callback for Options->Transfer Options->App=>Project. Copies options
  7704. from application defaults to project defaults.
  7705. :return: None
  7706. """
  7707. self.report_usage("on_options_app2project")
  7708. self.defaults_read_form()
  7709. self.options.update(self.defaults)
  7710. self.options_write_form()
  7711. def on_options_project2app(self):
  7712. """
  7713. Callback for Options->Transfer Options->Project=>App. Copies options
  7714. from project defaults to application defaults.
  7715. :return: None
  7716. """
  7717. self.report_usage("on_options_project2app")
  7718. self.options_read_form()
  7719. self.defaults.update(self.options)
  7720. self.defaults_write_form()
  7721. def on_options_project2object(self):
  7722. """
  7723. Callback for Options->Transfer Options->Project=>Object. Copies options
  7724. from project defaults to the currently selected object.
  7725. :return: None
  7726. """
  7727. self.report_usage("on_options_project2object")
  7728. self.options_read_form()
  7729. obj = self.collection.get_active()
  7730. if obj is None:
  7731. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7732. return
  7733. for option in self.options:
  7734. if option.find(obj.kind + "_") == 0:
  7735. oname = option[len(obj.kind) + 1:]
  7736. obj.options[oname] = self.options[option]
  7737. obj.to_form() # Update UI
  7738. def on_options_object2project(self):
  7739. """
  7740. Callback for Options->Transfer Options->Object=>Project. Copies options
  7741. from the currently selected object to project defaults.
  7742. :return: None
  7743. """
  7744. self.report_usage("on_options_object2project")
  7745. obj = self.collection.get_active()
  7746. if obj is None:
  7747. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7748. return
  7749. obj.read_form()
  7750. for option in obj.options:
  7751. if option in ['name']: # TODO: Handle this better...
  7752. continue
  7753. self.options[obj.kind + "_" + option] = obj.options[option]
  7754. self.options_write_form()
  7755. def on_options_object2app(self):
  7756. """
  7757. Callback for Options->Transfer Options->Object=>App. Copies options
  7758. from the currently selected object to application defaults.
  7759. :return: None
  7760. """
  7761. self.report_usage("on_options_object2app")
  7762. obj = self.collection.get_active()
  7763. if obj is None:
  7764. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7765. return
  7766. obj.read_form()
  7767. for option in obj.options:
  7768. if option in ['name']: # TODO: Handle this better...
  7769. continue
  7770. self.defaults[obj.kind + "_" + option] = obj.options[option]
  7771. self.defaults_write_form()
  7772. def on_options_app2object(self):
  7773. """
  7774. Callback for Options->Transfer Options->App=>Object. Copies options
  7775. from application defaults to the currently selected object.
  7776. :return: None
  7777. """
  7778. self.report_usage("on_options_app2object")
  7779. self.defaults_read_form()
  7780. obj = self.collection.get_active()
  7781. if obj is None:
  7782. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7783. return
  7784. for option in self.defaults:
  7785. if option.find(obj.kind + "_") == 0:
  7786. oname = option[len(obj.kind) + 1:]
  7787. obj.options[oname] = self.defaults[option]
  7788. obj.to_form() # Update UI
  7789. # end of file