FlatCAMApp.py 483 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from PyQt5.QtCore import pyqtSlot, Qt
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Diverse
  37. from FlatCAMCommon import LoudDict, color_variant, ExclusionAreas
  38. from FlatCAMBookmark import BookmarkManager
  39. from FlatCAMDB import ToolsDB2
  40. from vispy.gloo.util import _screenshot
  41. from vispy.io import write_png
  42. # FlatCAM Objects
  43. from defaults import FlatCAMDefaults
  44. from flatcamGUI.preferences.OptionsGroupUI import OptionsGroupUI
  45. from flatcamGUI.preferences.PreferencesUIManager import PreferencesUIManager
  46. from flatcamObjects.ObjectCollection import *
  47. from flatcamObjects.FlatCAMObj import FlatCAMObj
  48. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  49. from flatcamObjects.FlatCAMDocument import DocumentObject
  50. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  51. from flatcamObjects.FlatCAMGeometry import GeometryObject
  52. from flatcamObjects.FlatCAMGerber import GerberObject
  53. from flatcamObjects.FlatCAMScript import ScriptObject
  54. # FlatCAM Parsing files
  55. from flatcamParsers.ParseExcellon import Excellon
  56. from flatcamParsers.ParseGerber import Gerber
  57. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  58. # FlatCAM GUI
  59. from flatcamGUI.PlotCanvas import *
  60. from flatcamGUI.PlotCanvasLegacy import *
  61. from flatcamGUI.FlatCAMGUI import *
  62. from flatcamGUI.GUIElements import FCFileSaveDialog
  63. # FlatCAM Pre-processors
  64. from FlatCAMPostProc import load_preprocessors
  65. # FlatCAM Editors
  66. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  67. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  68. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  69. from flatcamEditors.FlatCAMTextEditor import TextEditor
  70. from flatcamParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from FlatCAMProcess import *
  73. from FlatCAMWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from flatcamTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import FlatCAMTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = 8.993
  138. version_date = "2020/08/01"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by:
  169. # * App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. plots_updated = QtCore.pyqtSignal()
  188. # Emitted by new_object() and passes the new object as argument, plot flag.
  189. # on_object_created() adds the object to the collection, plots on appropriate flag
  190. # and emits new_object_available.
  191. object_created = QtCore.pyqtSignal(object, bool, bool)
  192. # Emitted when a object has been changed (like scaled, mirrored)
  193. object_changed = QtCore.pyqtSignal(object)
  194. # Emitted after object has been plotted.
  195. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  196. object_plotted = QtCore.pyqtSignal(object)
  197. # Emitted when a new object has been added or deleted from/to the collection
  198. object_status_changed = QtCore.pyqtSignal(object, str, str)
  199. message = QtCore.pyqtSignal(str, str, str)
  200. # Emmited when shell command is finished(one command only)
  201. shell_command_finished = QtCore.pyqtSignal(object)
  202. # Emitted when multiprocess pool has been recreated
  203. pool_recreated = QtCore.pyqtSignal(object)
  204. # Emitted when an unhandled exception happens
  205. # in the worker task.
  206. thread_exception = QtCore.pyqtSignal(object)
  207. # used to signal that there are arguments for the app
  208. args_at_startup = QtCore.pyqtSignal(list)
  209. # a reusable signal to replot a list of objects
  210. # should be disconnected after use so it can be reused
  211. replot_signal = pyqtSignal(list)
  212. # signal emitted when jumping
  213. jump_signal = pyqtSignal(tuple)
  214. # signal emitted when jumping
  215. locate_signal = pyqtSignal(tuple, str)
  216. # close app signal
  217. close_app_signal = pyqtSignal()
  218. # will perform the cleanup operation after a Graceful Exit
  219. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  220. # graphic residues behind
  221. cleanup = pyqtSignal()
  222. def __init__(self, user_defaults=True):
  223. """
  224. Starts the application.
  225. :return: app
  226. :rtype: App
  227. """
  228. super().__init__()
  229. App.log.info("FlatCAM Starting...")
  230. self.main_thread = QtWidgets.QApplication.instance().thread()
  231. # ############################################################################################################
  232. # ################# Setup the listening thread for another instance launching with args ######################
  233. # ############################################################################################################
  234. if sys.platform == 'win32' or sys.platform == 'linux':
  235. # make sure the thread is stored by using a self. otherwise it's garbage collected
  236. self.th = QtCore.QThread()
  237. self.th.start(priority=QtCore.QThread.LowestPriority)
  238. self.new_launch = ArgsThread()
  239. self.new_launch.open_signal[list].connect(self.on_startup_args)
  240. self.new_launch.moveToThread(self.th)
  241. self.new_launch.start.emit()
  242. # ############################################################################################################
  243. # # ######################################## OS-specific #####################################################
  244. # ############################################################################################################
  245. portable = False
  246. # Folder for user settings.
  247. if sys.platform == 'win32':
  248. if platform.architecture()[0] == '32bit':
  249. App.log.debug("Win32!")
  250. else:
  251. App.log.debug("Win64!")
  252. # #######################################################################################################
  253. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  254. # #######################################################################################################
  255. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  256. try:
  257. with open(config_file, 'r'):
  258. pass
  259. except FileNotFoundError:
  260. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  261. try:
  262. with open(config_file, 'r') as f:
  263. try:
  264. for line in f:
  265. param = str(line).replace('\n', '').rpartition('=')
  266. if param[0] == 'portable':
  267. try:
  268. portable = eval(param[2])
  269. except NameError:
  270. portable = False
  271. if param[0] == 'headless':
  272. if param[2].lower() == 'true':
  273. self.cmd_line_headless = 1
  274. else:
  275. self.cmd_line_headless = None
  276. except Exception as e:
  277. log.debug('App.__init__() -->%s' % str(e))
  278. return
  279. except FileNotFoundError as e:
  280. log.debug(str(e))
  281. pass
  282. if portable is False:
  283. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  284. else:
  285. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  286. self.os = 'windows'
  287. else: # Linux/Unix/MacOS
  288. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  289. self.os = 'unix'
  290. # ############################################################################################################
  291. # ################################# Setup folders and files ##################################################
  292. # ############################################################################################################
  293. if not os.path.exists(self.data_path):
  294. os.makedirs(self.data_path)
  295. App.log.debug('Created data folder: ' + self.data_path)
  296. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  297. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  298. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  299. if not os.path.exists(self.preprocessorpaths):
  300. os.makedirs(self.preprocessorpaths)
  301. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  302. # create geo_tools_db.FlatDB file if there is none
  303. try:
  304. f = open(self.data_path + '/geo_tools_db.FlatDB')
  305. f.close()
  306. except IOError:
  307. App.log.debug('Creating empty geo_tool_db.FlatDB')
  308. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  309. json.dump({}, f)
  310. f.close()
  311. # create current_defaults.FlatConfig file if there is none
  312. try:
  313. f = open(self.data_path + '/current_defaults.FlatConfig')
  314. f.close()
  315. except IOError:
  316. App.log.debug('Creating empty current_defaults.FlatConfig')
  317. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  318. json.dump({}, f)
  319. f.close()
  320. # Write factory_defaults.FlatConfig file to disk
  321. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  322. # create a recent files json file if there is none
  323. try:
  324. f = open(self.data_path + '/recent.json')
  325. f.close()
  326. except IOError:
  327. App.log.debug('Creating empty recent.json')
  328. f = open(self.data_path + '/recent.json', 'w')
  329. json.dump([], f)
  330. f.close()
  331. # create a recent projects json file if there is none
  332. try:
  333. fp = open(self.data_path + '/recent_projects.json')
  334. fp.close()
  335. except IOError:
  336. App.log.debug('Creating empty recent_projects.json')
  337. fp = open(self.data_path + '/recent_projects.json', 'w')
  338. json.dump([], fp)
  339. fp.close()
  340. # Application directory. CHDIR to it. Otherwise, trying to load
  341. # GUI icons will fail as their path is relative.
  342. # This will fail under cx_freeze ...
  343. self.app_home = os.path.dirname(os.path.realpath(__file__))
  344. App.log.debug("Application path is " + self.app_home)
  345. App.log.debug("Started in " + os.getcwd())
  346. # cx_freeze workaround
  347. if os.path.isfile(self.app_home):
  348. self.app_home = os.path.dirname(self.app_home)
  349. os.chdir(self.app_home)
  350. # ############################################################################################################
  351. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  352. # ############################################################################################################
  353. self.defaults = FlatCAMDefaults()
  354. self.defaults["root_folder_path"] = self.app_home
  355. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  356. if user_defaults:
  357. self.defaults.load(filename=current_defaults_path)
  358. if self.defaults['units'] == 'MM':
  359. self.decimals = int(self.defaults['decimals_metric'])
  360. else:
  361. self.decimals = int(self.defaults['decimals_inch'])
  362. if self.defaults["global_gray_icons"] is False:
  363. self.resource_location = 'assets/resources'
  364. else:
  365. self.resource_location = 'assets/resources/dark_resources'
  366. self.current_units = self.defaults['units']
  367. # ###########################################################################################################
  368. # #################################### SETUP OBJECT CLASSES #################################################
  369. # ###########################################################################################################
  370. self.setup_obj_classes()
  371. # ###########################################################################################################
  372. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  373. # ###########################################################################################################
  374. self.pool = Pool()
  375. # ###########################################################################################################
  376. # ###################################### Setting the Splash Screen ##########################################
  377. # ###########################################################################################################
  378. splash_settings = QSettings("Open Source", "FlatCAM")
  379. if splash_settings.contains("splash_screen"):
  380. show_splash = splash_settings.value("splash_screen")
  381. else:
  382. splash_settings.setValue('splash_screen', 1)
  383. # This will write the setting to the platform specific storage.
  384. del splash_settings
  385. show_splash = 1
  386. if show_splash and self.cmd_line_headless != 1:
  387. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  388. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  389. # self.splash.setMask(splash_pix.mask())
  390. # move splashscreen to the current monitor
  391. desktop = QtWidgets.QApplication.desktop()
  392. screen = desktop.screenNumber(QtGui.QCursor.pos())
  393. current_screen_center = desktop.availableGeometry(screen).center()
  394. self.splash.move(current_screen_center - self.splash.rect().center())
  395. self.splash.show()
  396. self.splash.showMessage(_("FlatCAM is initializing ..."),
  397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  398. color=QtGui.QColor("gray"))
  399. else:
  400. show_splash = 0
  401. # ###########################################################################################################
  402. # ######################################### Initialize GUI ##################################################
  403. # ###########################################################################################################
  404. # FlatCAM colors used in plotting
  405. self.FC_light_green = '#BBF268BF'
  406. self.FC_dark_green = '#006E20BF'
  407. self.FC_light_blue = '#a5a5ffbf'
  408. self.FC_dark_blue = '#0000ffbf'
  409. self.ui = FlatCAMGUI(self)
  410. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  411. if theme_settings.contains("theme"):
  412. theme = theme_settings.value('theme', type=str)
  413. else:
  414. theme = 'white'
  415. if self.defaults["global_cursor_color_enabled"]:
  416. self.cursor_color_3D = self.defaults["global_cursor_color"]
  417. else:
  418. if theme == 'white':
  419. self.cursor_color_3D = 'black'
  420. else:
  421. self.cursor_color_3D = 'gray'
  422. # update the defaults dict with the setting in QSetting
  423. self.defaults['global_theme'] = theme
  424. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  425. self.ui.final_save.connect(self.final_save)
  426. # restore the toolbar view
  427. self.restore_toolbar_view()
  428. # restore the GUI geometry
  429. self.restore_main_win_geom()
  430. # set FlatCAM units in the Status bar
  431. self.set_screen_units(self.defaults['units'])
  432. # ###########################################################################################################
  433. # ########################################### AUTOSAVE SETUP ################################################
  434. # ###########################################################################################################
  435. self.block_autosave = False
  436. self.autosave_timer = QtCore.QTimer(self)
  437. self.save_project_auto_update()
  438. self.autosave_timer.timeout.connect(self.save_project_auto)
  439. # ###########################################################################################################
  440. # #################################### LOAD PREPROCESSORS ###################################################
  441. # ###########################################################################################################
  442. # ----------------------------------------- WARNING --------------------------------------------------------
  443. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  444. # That's because the number of preprocessors can vary and here the comboboxes are populated
  445. # -----------------------------------------------------------------------------------------------------------
  446. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  447. # the preprocessor file
  448. self.preprocessors = load_preprocessors(self)
  449. # make sure that always the 'default' preprocessor is the first item in the dictionary
  450. if 'default' in self.preprocessors.keys():
  451. new_ppp_dict = {}
  452. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  453. default_pp = self.preprocessors.pop('default')
  454. new_ppp_dict['default'] = default_pp
  455. # then add the rest of the keys
  456. for name, val_class in self.preprocessors.items():
  457. new_ppp_dict[name] = val_class
  458. # and now put back the ordered dict with 'default' key first
  459. self.preprocessors = new_ppp_dict
  460. for name in list(self.preprocessors.keys()):
  461. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  462. if name.partition('_')[0] == 'Paste':
  463. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  464. continue
  465. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  466. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  467. if name == 'hpgl':
  468. continue
  469. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  470. # ###########################################################################################################
  471. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  472. # ###########################################################################################################
  473. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  474. inform=self.inform)
  475. self.preferencesUiManager.defaults_write_form()
  476. # When the self.defaults dictionary changes will update the Preferences GUI forms
  477. self.defaults.set_change_callback(self.on_defaults_dict_change)
  478. # ###########################################################################################################
  479. # ##################################### FIRST RUN SECTION ###################################################
  480. # ################################ It's done only once after install #####################################
  481. # ###########################################################################################################
  482. if self.defaults["first_run"] is True:
  483. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  484. initial_lay = 'minimal'
  485. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  486. # Set the combobox in Preferences to the current layout
  487. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  488. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  489. # after the first run, this object should be False
  490. self.defaults["first_run"] = False
  491. self.preferencesUiManager.save_defaults(silent=True)
  492. # ###########################################################################################################
  493. # ############################################ Data #########################################################
  494. # ###########################################################################################################
  495. self.recent = []
  496. self.recent_projects = []
  497. self.clipboard = QtWidgets.QApplication.clipboard()
  498. self.project_filename = None
  499. self.toggle_units_ignore = False
  500. # ###########################################################################################################
  501. # ########################################## LOAD LANGUAGES ################################################
  502. # ###########################################################################################################
  503. self.languages = fcTranslate.load_languages()
  504. for name in sorted(self.languages.values()):
  505. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  506. # ###########################################################################################################
  507. # ####################################### APPLY APP LANGUAGE ################################################
  508. # ###########################################################################################################
  509. ret_val = fcTranslate.apply_language('strings')
  510. if ret_val == "no language":
  511. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  512. log.debug("Could not find the Language files. The App strings are missing.")
  513. else:
  514. # make the current language the current selection on the language combobox
  515. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  516. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  517. # ###########################################################################################################
  518. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  519. # ###########################################################################################################
  520. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  521. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  522. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  523. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  524. self.defaults.propagate_defaults()
  525. # ###########################################################################################################
  526. # ######################################## UPDATE THE OPTIONS ###############################################
  527. # ###########################################################################################################
  528. self.options = LoudDict()
  529. # -----------------------------------------------------------------------------------------------------------
  530. # Update the self.options from the self.defaults
  531. # The self.defaults holds the application defaults while the self.options holds the object defaults
  532. # -----------------------------------------------------------------------------------------------------------
  533. # Copy app defaults to project options
  534. for def_key, def_val in self.defaults.items():
  535. self.options[def_key] = deepcopy(def_val)
  536. self.preferencesUiManager.show_preferences_gui()
  537. # ### End of Data ####
  538. # ###########################################################################################################
  539. # #################################### SETUP OBJECT COLLECTION ##############################################
  540. # ###########################################################################################################
  541. self.collection = ObjectCollection(self)
  542. self.ui.project_tab_layout.addWidget(self.collection.view)
  543. # ### Adjust tabs width ## ##
  544. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  545. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  546. self.collection.view.setMinimumWidth(290)
  547. self.log.debug("Finished creating Object Collection.")
  548. # ###########################################################################################################
  549. # ######################################## SETUP Plot Area ##################################################
  550. # ###########################################################################################################
  551. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  552. if self.defaults["global_graphic_engine"] == '3D':
  553. self.is_legacy = False
  554. else:
  555. self.is_legacy = True
  556. # Event signals disconnect id holders
  557. self.mp = None
  558. self.mm = None
  559. self.mr = None
  560. self.mdc = None
  561. self.mp_zc = None
  562. self.kp = None
  563. # Matplotlib axis
  564. self.axes = None
  565. if show_splash:
  566. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  567. "Canvas initialization started."),
  568. alignment=Qt.AlignBottom | Qt.AlignLeft,
  569. color=QtGui.QColor("gray"))
  570. start_plot_time = time.time() # debug
  571. self.plotcanvas = None
  572. self.app_cursor = None
  573. self.hover_shapes = None
  574. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  575. # setup the PlotCanvas
  576. self.on_plotcanvas_setup()
  577. end_plot_time = time.time()
  578. self.used_time = end_plot_time - start_plot_time
  579. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  580. if show_splash:
  581. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  582. "Canvas initialization started.\n"
  583. "Canvas initialization finished in"), '%.2f' % self.used_time),
  584. alignment=Qt.AlignBottom | Qt.AlignLeft,
  585. color=QtGui.QColor("gray"))
  586. self.ui.splitter.setStretchFactor(1, 2)
  587. # ###########################################################################################################
  588. # ############################################### SYS TRAY ##################################################
  589. # ###########################################################################################################
  590. if self.defaults["global_systray_icon"]:
  591. self.parent_w = QtWidgets.QWidget()
  592. if self.cmd_line_headless == 1:
  593. self.trayIcon = FlatCAMSystemTray(app=self,
  594. icon=QtGui.QIcon(self.resource_location +
  595. '/flatcam_icon32_green.png'),
  596. headless=True,
  597. parent=self.parent_w)
  598. else:
  599. self.trayIcon = FlatCAMSystemTray(app=self,
  600. icon=QtGui.QIcon(self.resource_location +
  601. '/flatcam_icon32_green.png'),
  602. parent=self.parent_w)
  603. # ###########################################################################################################
  604. # ############################################### Worker SETUP ##############################################
  605. # ###########################################################################################################
  606. if self.defaults["global_worker_number"]:
  607. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  608. else:
  609. self.workers = WorkerStack(workers_number=2)
  610. self.worker_task.connect(self.workers.add_task)
  611. self.log.debug("Finished creating Workers crew.")
  612. # ###########################################################################################################
  613. # ############################################# Activity Monitor ###########################################
  614. # ###########################################################################################################
  615. self.activity_view = FlatCAMActivityView(app=self)
  616. self.ui.infobar.addWidget(self.activity_view)
  617. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  618. # ###########################################################################################################
  619. # ############################################# Signal handling #############################################
  620. # ###########################################################################################################
  621. # ########################################## Custom signals ################################################
  622. # signal for displaying messages in status bar
  623. self.inform.connect(self.info)
  624. # signal to be called when the app is quiting
  625. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  626. self.message.connect(self.message_dialog)
  627. # self.progress.connect(self.set_progress_bar)
  628. # signals that are emitted when object state changes
  629. self.object_created.connect(self.on_object_created)
  630. self.object_changed.connect(self.on_object_changed)
  631. self.object_plotted.connect(self.on_object_plotted)
  632. self.plots_updated.connect(self.on_plots_updated)
  633. # signals emitted when file state change
  634. self.file_opened.connect(self.register_recent)
  635. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  636. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  637. # ########################################## Standard signals ###############################################
  638. # ### Menu
  639. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  640. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  641. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  642. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  643. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  644. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  645. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  646. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  647. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  648. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  649. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  650. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  651. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  652. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  653. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  654. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  655. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  656. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  657. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  658. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  659. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  660. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  661. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  662. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  663. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  664. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  665. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  666. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  667. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  668. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  669. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  670. self.ui.menufile_exit.triggered.connect(self.final_save)
  671. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  672. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  673. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  674. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  675. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  676. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  677. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  678. self.ui.menueditdelete.triggered.connect(self.on_delete)
  679. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  680. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  681. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  682. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  683. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  684. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  685. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  686. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  687. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  688. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  689. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  690. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  691. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  692. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  693. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  694. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  695. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  696. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  697. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  698. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  699. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  700. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  701. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  702. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  703. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  704. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  705. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  706. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  707. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  708. self.ui.menuview_replot.triggered.connect(self.plot_all)
  709. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  710. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  711. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  712. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  713. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  714. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  715. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  716. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  717. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  718. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  719. self.ui.menuhelp_about.triggered.connect(self.on_about)
  720. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  721. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  722. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  723. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  724. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  725. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  726. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  727. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  728. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  729. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  730. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  731. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  732. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  733. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  734. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  735. # ToolBar signals
  736. self.connect_toolbar_signals()
  737. # Notebook and Plot Tab Area signals
  738. # make the right click on the notebook tab and plot tab area tab raise a menu
  739. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  740. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  741. self.on_tab_setup_context_menu()
  742. # activate initial state
  743. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  744. # Context Menu
  745. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  746. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  747. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  748. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  749. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  750. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  751. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  752. self.ui.clearplot.triggered.connect(self.clear_plots)
  753. self.ui.replot.triggered.connect(self.plot_all)
  754. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  755. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  756. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  757. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  758. self.ui.popmenu_move.triggered.connect(self.obj_move)
  759. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  760. # Project Context Menu -> Color Setting
  761. for act in self.ui.menuprojectcolor.actions():
  762. act.triggered.connect(self.on_set_color_action_triggered)
  763. # ###########################################################################################################
  764. # #################################### GUI PREFERENCES SIGNALS ##############################################
  765. # ###########################################################################################################
  766. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  767. lambda: self.on_toggle_units(no_pref=False))
  768. # ##################################### Workspace Setting Signals ###########################################
  769. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  770. self.on_workspace_modified)
  771. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  772. self.on_workspace_modified
  773. )
  774. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  775. # ###########################################################################################################
  776. # ######################################## GUI SETTINGS SIGNALS #############################################
  777. # ###########################################################################################################
  778. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  779. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  780. # ######################################## Tools related signals ############################################
  781. # Film Tool
  782. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  783. self.on_film_color_entry)
  784. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  785. self.on_film_color_button)
  786. # QRCode Tool
  787. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  788. self.on_qrcode_fill_color_entry)
  789. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  790. self.on_qrcode_fill_color_button)
  791. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  792. self.on_qrcode_back_color_entry)
  793. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  794. self.on_qrcode_back_color_button)
  795. # portability changed signal
  796. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  797. # Object list
  798. self.collection.view.activated.connect(self.on_row_activated)
  799. self.collection.item_selected.connect(self.on_row_selected)
  800. self.object_status_changed.connect(self.on_collection_updated)
  801. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  802. # Export Excellon parameters.
  803. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  804. self.on_update_exc_export
  805. )
  806. # call it once to make sure it is updated at startup
  807. self.on_update_exc_export(state=self.defaults["excellon_update"])
  808. # when there are arguments at application startup this get launched
  809. self.args_at_startup[list].connect(self.on_startup_args)
  810. # ###########################################################################################################
  811. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  812. # ###########################################################################################################
  813. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  814. lambda: self.restore_extensions(ext_type='excellon'))
  815. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  816. lambda: self.restore_extensions(ext_type='gcode'))
  817. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  818. lambda: self.restore_extensions(ext_type='gerber'))
  819. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  820. lambda: self.delete_all_extensions(ext_type='excellon'))
  821. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  822. lambda: self.delete_all_extensions(ext_type='gcode'))
  823. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  824. lambda: self.delete_all_extensions(ext_type='gerber'))
  825. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  826. lambda: self.add_extension(ext_type='excellon'))
  827. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  828. lambda: self.add_extension(ext_type='gcode'))
  829. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  830. lambda: self.add_extension(ext_type='gerber'))
  831. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  832. lambda: self.del_extension(ext_type='excellon'))
  833. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  834. lambda: self.del_extension(ext_type='gcode'))
  835. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  836. lambda: self.del_extension(ext_type='gerber'))
  837. # connect the 'Apply' buttons from the Preferences/File Associations
  838. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  839. lambda: self.on_register_files(obj_type='excellon'))
  840. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  841. lambda: self.on_register_files(obj_type='gcode'))
  842. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  843. lambda: self.on_register_files(obj_type='gerber'))
  844. # ###########################################################################################################
  845. # ########################################### KEYWORDS SIGNALS ##############################################
  846. # ###########################################################################################################
  847. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  848. lambda: self.restore_extensions(ext_type='keyword'))
  849. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  850. lambda: self.delete_all_extensions(ext_type='keyword'))
  851. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  852. lambda: self.add_extension(ext_type='keyword'))
  853. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  854. lambda: self.del_extension(ext_type='keyword'))
  855. # connect the abort_all_tasks related slots to the related signals
  856. self.proc_container.idle_flag.connect(self.app_is_idle)
  857. # signal emitted when a tab is closed in the Plot Area
  858. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  859. # signal to close the application
  860. self.close_app_signal.connect(self.kill_app)
  861. # ################################# FINISHED CONNECTING SIGNALS #############################################
  862. # ###########################################################################################################
  863. # ###########################################################################################################
  864. # ###########################################################################################################
  865. self.log.debug("Finished connecting Signals.")
  866. # ###########################################################################################################
  867. # ########################################## Other setups ###################################################
  868. # ###########################################################################################################
  869. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  870. # depending on from where those tools are called different actions can be done
  871. self.call_source = 'app'
  872. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  873. self.tool_tab_locked = False
  874. # decide if to show or hide the Notebook side of the screen at startup
  875. if self.defaults["global_project_at_startup"] is True:
  876. self.ui.splitter.setSizes([1, 1])
  877. else:
  878. self.ui.splitter.setSizes([0, 1])
  879. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  880. self.setup_component_editor()
  881. # ###########################################################################################################
  882. # ####################################### Auto-complete KEYWORDS ############################################
  883. # ###########################################################################################################
  884. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  885. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  886. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  887. 'export_exc',
  888. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  889. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  890. 'interiors', 'isolate', 'join_excellon',
  891. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  892. 'mirror', 'ncc',
  893. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  894. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  895. 'options', 'origin',
  896. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  897. 'save', 'save_project',
  898. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  899. 'skew', 'subtract_poly', 'subtract_rectangle',
  900. 'version', 'write_gcode'
  901. ]
  902. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  903. 'Paste_1',
  904. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  905. 'Toolchange_manual', 'True', 'Users',
  906. 'all', 'auto', 'axis',
  907. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  908. 'contour', 'default',
  909. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  910. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  911. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  912. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  913. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  914. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  915. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  916. 'spacing_columns',
  917. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  918. 'toolchange_xy', 'toolchangez', 'travelz',
  919. 'tooldia', 'use_threads', 'value',
  920. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  921. ]
  922. self.tcl_keywords = [
  923. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  924. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  925. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  926. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  927. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  928. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  929. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  930. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  931. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  932. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  933. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  934. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  935. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  936. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  937. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  938. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  939. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  940. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  941. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  942. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  943. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  944. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  945. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  946. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  947. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  948. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  949. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  950. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  951. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  952. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  953. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  954. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  955. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  956. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  957. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  958. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  959. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  960. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  961. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  962. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  963. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  964. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  965. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  966. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  967. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  968. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  969. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  970. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  971. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  972. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  973. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  974. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  975. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  976. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  977. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  978. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  979. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  980. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  981. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  982. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  983. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  984. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  985. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  986. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  987. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  988. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  989. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  990. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  991. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  992. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  993. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  994. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  995. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  996. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  997. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  998. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  999. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1000. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1001. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1002. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1003. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1004. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1005. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1006. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1007. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1008. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1009. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1010. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1011. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1012. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1013. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1014. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1015. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1016. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1017. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1018. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1019. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1020. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1021. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1022. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1023. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1024. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1025. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1026. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1027. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1028. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1029. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1030. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1031. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1032. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1033. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1034. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1035. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1036. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1037. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1038. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1039. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1040. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1041. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1042. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1043. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1044. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1045. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1046. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1047. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1048. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1049. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1050. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1051. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1052. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1053. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1054. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1055. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1056. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1057. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1058. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1059. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1060. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1061. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1062. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1063. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1064. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1065. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1066. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1067. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1068. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1069. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1070. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1071. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1072. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1073. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1074. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1075. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1076. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1077. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1078. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1079. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1080. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1081. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1082. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1083. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1084. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1085. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1086. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1087. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1088. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1089. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1090. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1091. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1092. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1093. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1094. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1095. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1096. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1097. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1098. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1099. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1100. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1101. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1102. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1103. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1104. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1105. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1106. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1107. ]
  1108. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1109. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1110. # ###########################################################################################################
  1111. # ############################################## Shell SETUP ################################################
  1112. # ###########################################################################################################
  1113. self.shell = FCShell(app=self, version=self.version)
  1114. self.ui.shell_dock.setWidget(self.shell)
  1115. self.log.debug("TCL Shell has been initialized.")
  1116. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1117. if self.defaults["global_shell_at_startup"]:
  1118. self.ui.shell_dock.show()
  1119. else:
  1120. self.ui.shell_dock.hide()
  1121. # ###########################################################################################################
  1122. # ########################################## Tools and Plugins ##############################################
  1123. # ###########################################################################################################
  1124. self.dblsidedtool = None
  1125. self.distance_tool = None
  1126. self.distance_min_tool = None
  1127. self.panelize_tool = None
  1128. self.film_tool = None
  1129. self.paste_tool = None
  1130. self.calculator_tool = None
  1131. self.rules_tool = None
  1132. self.sub_tool = None
  1133. self.move_tool = None
  1134. self.cutout_tool = None
  1135. self.ncclear_tool = None
  1136. self.optimal_tool = None
  1137. self.paint_tool = None
  1138. self.transform_tool = None
  1139. self.properties_tool = None
  1140. self.pdf_tool = None
  1141. self.image_tool = None
  1142. self.pcb_wizard_tool = None
  1143. self.cal_exc_tool = None
  1144. self.qrcode_tool = None
  1145. self.copper_thieving_tool = None
  1146. self.fiducial_tool = None
  1147. self.edrills_tool = None
  1148. self.align_objects_tool = None
  1149. self.punch_tool = None
  1150. self.invert_tool = None
  1151. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1152. try:
  1153. self.install_tools()
  1154. except AttributeError as e:
  1155. log.debug("App.__init__() install tools() --> %s" % str(e))
  1156. # ###########################################################################################################
  1157. # ############################################ SETUP RECENT ITEMS ###########################################
  1158. # ###########################################################################################################
  1159. self.setup_recent_items()
  1160. # ###########################################################################################################
  1161. # ######################################### BookMarks Manager ###############################################
  1162. # ###########################################################################################################
  1163. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1164. self.install_bookmarks()
  1165. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1166. # ###########################################################################################################
  1167. # ########################################### Tools Database ################################################
  1168. # ###########################################################################################################
  1169. self.tools_db_tab = None
  1170. # ### System Font Parsing ###
  1171. # self.f_parse = ParseFont(self)
  1172. # self.parse_system_fonts()
  1173. # ###########################################################################################################
  1174. # ######################################### Check for updates ###############################################
  1175. # ###########################################################################################################
  1176. # Separate thread (Not worker)
  1177. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1178. if (self.beta is False or self.beta is None) and \
  1179. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1180. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1181. # self.thr2 = QtCore.QThread()
  1182. self.worker_task.emit({'fcn': self.version_check,
  1183. 'params': []})
  1184. # self.thr2.start(QtCore.QThread.LowPriority)
  1185. # ###########################################################################################################
  1186. # ##################################### Register files with FlatCAM; #######################################
  1187. # ################################### It works only for Windows for now ####################################
  1188. # ###########################################################################################################
  1189. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1190. self.on_register_files()
  1191. # ###########################################################################################################
  1192. # ######################################## Variables for global usage #######################################
  1193. # ###########################################################################################################
  1194. # hold the App units
  1195. self.units = 'MM'
  1196. # coordinates for relative position display
  1197. self.rel_point1 = (0, 0)
  1198. self.rel_point2 = (0, 0)
  1199. # variable to store coordinates
  1200. self.pos = (0, 0)
  1201. self.pos_canvas = (0, 0)
  1202. self.pos_jump = (0, 0)
  1203. # variable to store mouse coordinates
  1204. self.mouse = [0, 0]
  1205. # variable to store the delta positions on cavnas
  1206. self.dx = 0
  1207. self.dy = 0
  1208. # decide if we have a double click or single click
  1209. self.doubleclick = False
  1210. # store here the is_dragging value
  1211. self.event_is_dragging = False
  1212. # variable to store if a command is active (then the var is not None) and which one it is
  1213. self.command_active = None
  1214. # variable to store the status of moving selection action
  1215. # None value means that it's not an selection action
  1216. # True value = a selection from left to right
  1217. # False value = a selection from right to left
  1218. self.selection_type = None
  1219. # List to store the objects that are currently loaded in FlatCAM
  1220. # This list is updated on each object creation or object delete
  1221. self.all_objects_list = []
  1222. self.objects_under_the_click_list = []
  1223. # List to store the objects that are selected
  1224. self.sel_objects_list = []
  1225. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1226. self.key_modifiers = None
  1227. # Variable to hold the status of the axis
  1228. self.toggle_axis = True
  1229. # Variable to hold the status of the grid lines
  1230. self.toggle_grid_lines = True
  1231. # Variable to store the status of the fullscreen event
  1232. self.toggle_fscreen = False
  1233. # Variable to store the status of the code editor
  1234. self.toggle_codeeditor = False
  1235. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1236. self.click_noproject = False
  1237. self.cursor = None
  1238. # Variable to store the GCODE that was edited
  1239. self.gcode_edited = ""
  1240. self.text_editor_tab = None
  1241. # reference for the self.ui.code_editor
  1242. self.reference_code_editor = None
  1243. self.script_code = ''
  1244. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1245. self.tools_db_changed_flag = False
  1246. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1247. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1248. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1249. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1250. 'tsm']
  1251. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1252. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1253. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1254. 'sbp', 'tap', 'xpi']
  1255. self.svg_list = ['svg']
  1256. self.dxf_list = ['dxf']
  1257. self.pdf_list = ['pdf']
  1258. self.prj_list = ['flatprj']
  1259. self.conf_list = ['flatconfig']
  1260. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1261. # flag for polygons not cleared
  1262. self.poly_not_cleared = False
  1263. # VisPy visuals
  1264. self.isHovering = False
  1265. self.notHovering = True
  1266. # Window geometry
  1267. self.x_pos = None
  1268. self.y_pos = None
  1269. self.width = None
  1270. self.height = None
  1271. # when True, the app has to return from any thread
  1272. self.abort_flag = False
  1273. # set the value used in the Windows Title
  1274. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1275. # this holds a widget that is installed in the Plot Area when View Source option is used
  1276. self.source_editor_tab = None
  1277. self.pagesize = {}
  1278. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1279. # VisPy visuals
  1280. if self.is_legacy is False:
  1281. try:
  1282. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1283. except AttributeError:
  1284. self.tool_shapes = None
  1285. else:
  1286. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1287. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1288. # used in the delayed shutdown self.start_delayed_quit() method
  1289. self.save_timer = None
  1290. # ###########################################################################################################
  1291. # ################################## ADDING FlatCAM EDITORS section #########################################
  1292. # ###########################################################################################################
  1293. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1294. # at the first launch of the App , the editors will not be functional.
  1295. try:
  1296. self.geo_editor = FlatCAMGeoEditor(self)
  1297. except AttributeError:
  1298. pass
  1299. try:
  1300. self.exc_editor = FlatCAMExcEditor(self)
  1301. except AttributeError:
  1302. pass
  1303. try:
  1304. self.grb_editor = FlatCAMGrbEditor(self)
  1305. except AttributeError:
  1306. pass
  1307. self.log.debug("Finished adding FlatCAM Editor's.")
  1308. self.set_ui_title(name=_("New Project - Not saved"))
  1309. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1310. current_platform = platform.architecture()[0]
  1311. if current_platform != '64bit':
  1312. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1313. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1314. # ###########################################################################################################
  1315. # ########################################### EXCLUSION AREAS ###############################################
  1316. # ###########################################################################################################
  1317. self.exc_areas = ExclusionAreas(app=self)
  1318. # ###########################################################################################################
  1319. # ##################################### Finished the CONSTRUCTOR ############################################
  1320. # ###########################################################################################################
  1321. App.log.debug("END of constructor. Releasing control.")
  1322. # ###########################################################################################################
  1323. # ########################################## SHOW GUI #######################################################
  1324. # ###########################################################################################################
  1325. # if the app is not started as headless, show it
  1326. if self.cmd_line_headless != 1:
  1327. if show_splash:
  1328. # finish the splash
  1329. self.splash.finish(self.ui)
  1330. mgui_settings = QSettings("Open Source", "FlatCAM")
  1331. if mgui_settings.contains("maximized_gui"):
  1332. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1333. if maximized_ui is True:
  1334. self.ui.showMaximized()
  1335. else:
  1336. self.ui.show()
  1337. else:
  1338. self.ui.show()
  1339. if self.defaults["global_systray_icon"]:
  1340. self.trayIcon.show()
  1341. else:
  1342. log.warning("******************* RUNNING HEADLESS *******************")
  1343. # ###########################################################################################################
  1344. # ######################################## START-UP ARGUMENTS ###############################################
  1345. # ###########################################################################################################
  1346. # test if the program was started with a script as parameter
  1347. if self.cmd_line_shellvar:
  1348. try:
  1349. cnt = 0
  1350. command_tcl = 0
  1351. for i in self.cmd_line_shellvar.split(','):
  1352. if i is not None:
  1353. # noinspection PyBroadException
  1354. try:
  1355. command_tcl = eval(i)
  1356. except Exception:
  1357. command_tcl = i
  1358. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1359. cnt += 1
  1360. # if there are Windows paths then replace the path separator with a Unix like one
  1361. if sys.platform == 'win32':
  1362. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1363. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1364. except Exception as ext:
  1365. print("ERROR: ", ext)
  1366. sys.exit(2)
  1367. if self.cmd_line_shellfile:
  1368. if self.cmd_line_headless != 1:
  1369. if self.ui.shell_dock.isHidden():
  1370. self.ui.shell_dock.show()
  1371. try:
  1372. with open(self.cmd_line_shellfile, "r") as myfile:
  1373. # if show_splash:
  1374. # self.splash.showMessage('%s: %ssec\n%s' % (
  1375. # _("Canvas initialization started.\n"
  1376. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1377. # _("Executing Tcl Script ...")),
  1378. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1379. # color=QtGui.QColor("gray"))
  1380. cmd_line_shellfile_text = myfile.read()
  1381. if self.cmd_line_headless != 1:
  1382. self.shell.exec_command(cmd_line_shellfile_text)
  1383. else:
  1384. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1385. except Exception as ext:
  1386. print("ERROR: ", ext)
  1387. sys.exit(2)
  1388. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1389. # the path/file_name must be enclosed in quotes if it contain spaces
  1390. if App.args:
  1391. self.args_at_startup.emit(App.args)
  1392. if self.defaults.old_defaults_found is True:
  1393. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1394. "Please reboot the application to update."))
  1395. self.defaults.old_defaults_found = False
  1396. # ######################################### INIT FINISHED #######################################################
  1397. # #################################################################################################################
  1398. # #################################################################################################################
  1399. # #################################################################################################################
  1400. # #################################################################################################################
  1401. # #################################################################################################################
  1402. @staticmethod
  1403. def copy_and_overwrite(from_path, to_path):
  1404. """
  1405. From here:
  1406. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1407. :param from_path: source path
  1408. :param to_path: destination path
  1409. :return: None
  1410. """
  1411. if os.path.exists(to_path):
  1412. shutil.rmtree(to_path)
  1413. try:
  1414. shutil.copytree(from_path, to_path)
  1415. except FileNotFoundError:
  1416. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1417. shutil.copytree(from_new_path, to_path)
  1418. def on_startup_args(self, args, silent=False):
  1419. """
  1420. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1421. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1422. :param args: a list containing the application args at startup
  1423. :return: None
  1424. """
  1425. if args is not None:
  1426. args_to_process = args
  1427. else:
  1428. args_to_process = App.args
  1429. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1430. for argument in args_to_process:
  1431. if '.FlatPrj'.lower() in argument.lower():
  1432. try:
  1433. project_name = str(argument)
  1434. if project_name == "":
  1435. if silent is False:
  1436. self.inform.emit(_("Cancelled."))
  1437. else:
  1438. # self.open_project(project_name)
  1439. run_from_arg = True
  1440. # self.worker_task.emit({'fcn': self.open_project,
  1441. # 'params': [project_name, run_from_arg]})
  1442. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1443. except Exception as e:
  1444. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1445. elif '.FlatConfig'.lower() in argument.lower():
  1446. try:
  1447. file_name = str(argument)
  1448. if file_name == "":
  1449. if silent is False:
  1450. self.inform.emit(_("Open Config file failed."))
  1451. else:
  1452. run_from_arg = True
  1453. # self.worker_task.emit({'fcn': self.open_config_file,
  1454. # 'params': [file_name, run_from_arg]})
  1455. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1456. except Exception as e:
  1457. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1458. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1459. try:
  1460. file_name = str(argument)
  1461. if file_name == "":
  1462. if silent is False:
  1463. self.inform.emit(_("Open Script file failed."))
  1464. else:
  1465. if silent is False:
  1466. self.on_fileopenscript(name=file_name)
  1467. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1468. self.on_filerunscript(name=file_name)
  1469. except Exception as e:
  1470. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1471. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1472. log.debug("App.on_startup_args() --> Quit event.")
  1473. sys.exit()
  1474. elif 'save'.lower() in argument.lower():
  1475. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1476. self.preferencesUiManager.save_defaults()
  1477. else:
  1478. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1479. proc_arg = argument.lower()
  1480. for ext in exc_list:
  1481. proc_ext = ext.replace(' ', '')
  1482. proc_ext = '.%s' % proc_ext
  1483. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1484. file_name = str(argument)
  1485. if file_name == "":
  1486. if silent is False:
  1487. self.inform.emit(_("Open Excellon file failed."))
  1488. else:
  1489. self.on_fileopenexcellon(name=file_name, signal=None)
  1490. return
  1491. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1492. for ext in gco_list:
  1493. proc_ext = ext.replace(' ', '')
  1494. proc_ext = '.%s' % proc_ext
  1495. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1496. file_name = str(argument)
  1497. if file_name == "":
  1498. if silent is False:
  1499. self.inform.emit(_("Open GCode file failed."))
  1500. else:
  1501. self.on_fileopengcode(name=file_name, signal=None)
  1502. return
  1503. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1504. for ext in grb_list:
  1505. proc_ext = ext.replace(' ', '')
  1506. proc_ext = '.%s' % proc_ext
  1507. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1508. file_name = str(argument)
  1509. if file_name == "":
  1510. if silent is False:
  1511. self.inform.emit(_("Open Gerber file failed."))
  1512. else:
  1513. self.on_fileopengerber(name=file_name, signal=None)
  1514. return
  1515. # if it reached here without already returning then the app was registered with a file that it does not
  1516. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1517. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1518. # for arg in args_to_process:
  1519. # if 'FlatCAM.exe' in arg:
  1520. # continue
  1521. # else:
  1522. # sys.exit(2)
  1523. def set_ui_title(self, name):
  1524. """
  1525. Sets the title of the main window.
  1526. :param name: String that store the project path and project name
  1527. :return: None
  1528. """
  1529. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1530. (self.version,
  1531. ('BETA' if self.beta else ''),
  1532. platform.architecture()[0],
  1533. self.engine,
  1534. name)
  1535. )
  1536. def on_app_restart(self):
  1537. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1538. # be left in the SySTray
  1539. try:
  1540. self.trayIcon.hide()
  1541. except Exception:
  1542. pass
  1543. fcTranslate.restart_program(app=self)
  1544. def clear_pool(self):
  1545. """
  1546. Clear the multiprocessing pool and calls garbage collector.
  1547. :return: None
  1548. """
  1549. self.pool.close()
  1550. self.pool = Pool()
  1551. self.pool_recreated.emit(self.pool)
  1552. gc.collect()
  1553. def install_tools(self):
  1554. """
  1555. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1556. Instantiation of the Tools classes.
  1557. The order that the tools are installed is important as they can depend on each other install position.
  1558. :return: None
  1559. """
  1560. self.distance_tool = Distance(self)
  1561. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1562. before=self.ui.menueditorigin,
  1563. separator=False)
  1564. self.distance_min_tool = DistanceMin(self)
  1565. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1566. pos=self.ui.menuedit,
  1567. before=self.ui.menueditorigin,
  1568. separator=True)
  1569. self.dblsidedtool = DblSidedTool(self)
  1570. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1571. self.cal_exc_tool = ToolCalibration(self)
  1572. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1573. before=self.dblsidedtool.menuAction,
  1574. separator=False)
  1575. self.align_objects_tool = AlignObjects(self)
  1576. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1577. self.edrills_tool = ToolExtractDrills(self)
  1578. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1579. self.panelize_tool = Panelize(self)
  1580. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1581. self.film_tool = Film(self)
  1582. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1583. self.paste_tool = SolderPaste(self)
  1584. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1585. self.calculator_tool = ToolCalculator(self)
  1586. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1587. self.sub_tool = ToolSub(self)
  1588. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1589. pos=self.ui.menutool, separator=True)
  1590. self.rules_tool = RulesCheck(self)
  1591. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1592. pos=self.ui.menutool, separator=False)
  1593. self.optimal_tool = ToolOptimal(self)
  1594. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1595. pos=self.ui.menutool, separator=True)
  1596. self.move_tool = ToolMove(self)
  1597. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1598. before=self.ui.menueditorigin, separator=True)
  1599. self.cutout_tool = CutOut(self)
  1600. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1601. before=self.sub_tool.menuAction)
  1602. self.ncclear_tool = NonCopperClear(self)
  1603. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1604. before=self.sub_tool.menuAction, separator=True)
  1605. self.paint_tool = ToolPaint(self)
  1606. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1607. before=self.sub_tool.menuAction, separator=True)
  1608. self.copper_thieving_tool = ToolCopperThieving(self)
  1609. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1610. pos=self.ui.menutool)
  1611. self.fiducial_tool = ToolFiducials(self)
  1612. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1613. pos=self.ui.menutool)
  1614. self.qrcode_tool = QRCode(self)
  1615. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1616. pos=self.ui.menutool)
  1617. self.punch_tool = ToolPunchGerber(self)
  1618. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1619. self.invert_tool = ToolInvertGerber(self)
  1620. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1621. self.transform_tool = ToolTransform(self)
  1622. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1623. pos=self.ui.menuoptions, separator=True)
  1624. self.properties_tool = Properties(self)
  1625. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1626. pos=self.ui.menuoptions)
  1627. self.pdf_tool = ToolPDF(self)
  1628. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1629. pos=self.ui.menufileimport,
  1630. separator=True)
  1631. self.image_tool = ToolImage(self)
  1632. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1633. pos=self.ui.menufileimport,
  1634. separator=True)
  1635. self.pcb_wizard_tool = PcbWizard(self)
  1636. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1637. pos=self.ui.menufileimport)
  1638. self.log.debug("Tools are installed.")
  1639. def remove_tools(self):
  1640. """
  1641. Will remove all the actions in the Tool menu.
  1642. :return: None
  1643. """
  1644. for act in self.ui.menutool.actions():
  1645. self.ui.menutool.removeAction(act)
  1646. def init_tools(self):
  1647. """
  1648. Initialize the Tool tab in the notebook side of the central widget.
  1649. Remove the actions in the Tools menu.
  1650. Instantiate again the FlatCAM tools (plugins).
  1651. All this is required when changing the layout: standard, compact etc.
  1652. :return: None
  1653. """
  1654. log.debug("init_tools()")
  1655. # delete the data currently in the Tools Tab and the Tab itself
  1656. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1657. if widget is not None:
  1658. widget.deleteLater()
  1659. self.ui.notebook.removeTab(2)
  1660. # rebuild the Tools Tab
  1661. self.ui.tool_tab = QtWidgets.QWidget()
  1662. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1663. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1664. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1665. self.ui.tool_scroll_area = VerticalScrollArea()
  1666. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1667. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1668. # first remove all of them
  1669. self.remove_tools()
  1670. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1671. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1672. '&Command Line\tS')
  1673. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1674. # third install all of them
  1675. try:
  1676. self.install_tools()
  1677. except AttributeError:
  1678. pass
  1679. self.log.debug("Tools are initialized.")
  1680. # def parse_system_fonts(self):
  1681. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1682. # 'params': []})
  1683. def connect_toolbar_signals(self):
  1684. """
  1685. Reconnect the signals to the actions in the toolbar.
  1686. This has to be done each time after the FlatCAM tools are removed/installed.
  1687. :return: None
  1688. """
  1689. # Toolbar
  1690. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1691. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1692. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1693. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1694. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1695. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1696. self.ui.replot_btn.triggered.connect(self.plot_all)
  1697. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1698. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1699. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1700. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1701. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1702. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1703. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1704. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1705. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1706. self.ui.delete_btn.triggered.connect(self.on_delete)
  1707. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1708. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1709. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1710. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1711. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1712. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1713. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1714. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1715. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1716. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1717. # Tools Toolbar Signals
  1718. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1719. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1720. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1721. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1722. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1723. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1724. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1725. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1726. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1727. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1728. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1729. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1730. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1731. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1732. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1733. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1734. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1735. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1736. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1737. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1738. def object2editor(self):
  1739. """
  1740. Send the current Geometry or Excellon object (if any) into the it's editor.
  1741. :return: None
  1742. """
  1743. self.defaults.report_usage("object2editor()")
  1744. # disable the objects menu as it may interfere with the Editors
  1745. self.ui.menuobjects.setDisabled(True)
  1746. edited_object = self.collection.get_active()
  1747. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1748. isinstance(edited_object, ExcellonObject):
  1749. pass
  1750. else:
  1751. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1752. return
  1753. if isinstance(edited_object, GeometryObject):
  1754. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1755. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1756. # we set the notebook to hidden
  1757. # self.ui.splitter.setSizes([0, 1])
  1758. if edited_object.multigeo is True:
  1759. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1760. if len(sel_rows) > 1:
  1761. self.inform.emit('[WARNING_NOTCL] %s' %
  1762. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1763. "is not possible.\n"
  1764. "Edit only one geometry at a time."))
  1765. # determine the tool dia of the selected tool
  1766. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1767. # now find the key in the edited_object.tools that has this tooldia
  1768. multi_tool = 1
  1769. for tool in edited_object.tools:
  1770. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1771. multi_tool = tool
  1772. break
  1773. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1774. else:
  1775. self.geo_editor.edit_fcgeometry(edited_object)
  1776. # set call source to the Editor we go into
  1777. self.call_source = 'geo_editor'
  1778. elif isinstance(edited_object, ExcellonObject):
  1779. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1780. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1781. if self.ui.splitter.sizes()[0] == 0:
  1782. self.ui.splitter.setSizes([1, 1])
  1783. self.exc_editor.edit_fcexcellon(edited_object)
  1784. # set call source to the Editor we go into
  1785. self.call_source = 'exc_editor'
  1786. elif isinstance(edited_object, GerberObject):
  1787. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1788. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1789. if self.ui.splitter.sizes()[0] == 0:
  1790. self.ui.splitter.setSizes([1, 1])
  1791. self.grb_editor.edit_fcgerber(edited_object)
  1792. # set call source to the Editor we go into
  1793. self.call_source = 'grb_editor'
  1794. # reset the following variables so the UI is built again after edit
  1795. edited_object.ui_build = False
  1796. edited_object.build_aperture_storage = False
  1797. # make sure that we can't select another object while in Editor Mode:
  1798. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1799. self.ui.project_frame.setDisabled(True)
  1800. # delete any selection shape that might be active as they are not relevant in Editor
  1801. self.delete_selection_shape()
  1802. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1803. self.ui.plot_tab_area.protectTab(0)
  1804. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1805. self.should_we_save = True
  1806. def editor2object(self, cleanup=None):
  1807. """
  1808. Transfers the Geometry or Excellon from it's editor to the current object.
  1809. :return: None
  1810. """
  1811. self.defaults.report_usage("editor2object()")
  1812. # re-enable the objects menu that was disabled on entry in Editor mode
  1813. self.ui.menuobjects.setDisabled(False)
  1814. # do not update a geometry or excellon object unless it comes out of an editor
  1815. if self.call_source != 'app':
  1816. edited_obj = self.collection.get_active()
  1817. if cleanup is None:
  1818. msgbox = QtWidgets.QMessageBox()
  1819. msgbox.setText(_("Do you want to save the edited object?"))
  1820. msgbox.setWindowTitle(_("Close Editor"))
  1821. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1822. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1823. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1824. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1825. msgbox.setDefaultButton(bt_yes)
  1826. msgbox.exec_()
  1827. response = msgbox.clickedButton()
  1828. if response == bt_yes:
  1829. # clean the Tools Tab
  1830. self.ui.tool_scroll_area.takeWidget()
  1831. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1832. self.ui.notebook.setTabText(2, "Tool")
  1833. if isinstance(edited_obj, GeometryObject):
  1834. obj_type = "Geometry"
  1835. if cleanup is None:
  1836. self.geo_editor.update_fcgeometry(edited_obj)
  1837. # self.geo_editor.update_options(edited_obj)
  1838. self.geo_editor.deactivate()
  1839. # restore GUI to the Selected TAB
  1840. # Remove anything else in the GUI
  1841. self.ui.tool_scroll_area.takeWidget()
  1842. # update the geo object options so it is including the bounding box values
  1843. try:
  1844. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1845. edited_obj.options['xmin'] = xmin
  1846. edited_obj.options['ymin'] = ymin
  1847. edited_obj.options['xmax'] = xmax
  1848. edited_obj.options['ymax'] = ymax
  1849. except AttributeError as e:
  1850. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1851. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1852. edited_obj.build_ui()
  1853. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1854. elif isinstance(edited_obj, GerberObject):
  1855. obj_type = "Gerber"
  1856. if cleanup is None:
  1857. self.grb_editor.update_fcgerber()
  1858. self.grb_editor.update_options(edited_obj)
  1859. self.grb_editor.deactivate_grb_editor()
  1860. # delete the old object (the source object) if it was an empty one
  1861. try:
  1862. if len(edited_obj.solid_geometry) == 0:
  1863. old_name = edited_obj.options['name']
  1864. self.collection.set_active(old_name)
  1865. self.collection.delete_active()
  1866. except TypeError:
  1867. # if the solid_geometry is a single Polygon the len() will not work
  1868. # in any case, falling here means that we have something in the solid_geometry, even if only
  1869. # a single Polygon, therefore we pass this
  1870. pass
  1871. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1872. # restore GUI to the Selected TAB
  1873. # Remove anything else in the GUI
  1874. self.ui.selected_scroll_area.takeWidget()
  1875. elif isinstance(edited_obj, ExcellonObject):
  1876. obj_type = "Excellon"
  1877. if cleanup is None:
  1878. self.exc_editor.update_fcexcellon(edited_obj)
  1879. # self.exc_editor.update_options(edited_obj)
  1880. self.exc_editor.deactivate()
  1881. # restore GUI to the Selected TAB
  1882. # Remove anything else in the GUI
  1883. self.ui.tool_scroll_area.takeWidget()
  1884. # delete the old object (the source object) if it was an empty one
  1885. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1886. old_name = edited_obj.options['name']
  1887. self.collection.delete_by_name(name=old_name)
  1888. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1889. else:
  1890. self.inform.emit('[WARNING_NOTCL] %s' %
  1891. _("Select a Gerber, Geometry or Excellon Object to update."))
  1892. return
  1893. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1894. elif response == bt_no:
  1895. # clean the Tools Tab
  1896. self.ui.tool_scroll_area.takeWidget()
  1897. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1898. self.ui.notebook.setTabText(2, "Tool")
  1899. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1900. if isinstance(edited_obj, GeometryObject):
  1901. self.geo_editor.deactivate()
  1902. edited_obj.build_ui()
  1903. elif isinstance(edited_obj, GerberObject):
  1904. self.grb_editor.deactivate_grb_editor()
  1905. edited_obj.build_ui()
  1906. elif isinstance(edited_obj, ExcellonObject):
  1907. self.exc_editor.deactivate()
  1908. edited_obj.build_ui()
  1909. else:
  1910. self.inform.emit('[WARNING_NOTCL] %s' %
  1911. _("Select a Gerber, Geometry or Excellon Object to update."))
  1912. return
  1913. elif response == bt_cancel:
  1914. return
  1915. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1916. # edited_obj.build_ui()
  1917. # Switch notebook to Selected page
  1918. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1919. else:
  1920. if isinstance(edited_obj, GeometryObject):
  1921. self.geo_editor.deactivate()
  1922. elif isinstance(edited_obj, GerberObject):
  1923. self.grb_editor.deactivate_grb_editor()
  1924. elif isinstance(edited_obj, ExcellonObject):
  1925. self.exc_editor.deactivate()
  1926. else:
  1927. self.inform.emit('[WARNING_NOTCL] %s' %
  1928. _("Select a Gerber, Geometry or Excellon Object to update."))
  1929. return
  1930. # if notebook is hidden we show it
  1931. if self.ui.splitter.sizes()[0] == 0:
  1932. self.ui.splitter.setSizes([1, 1])
  1933. # restore the call_source to app
  1934. self.call_source = 'app'
  1935. edited_obj.plot()
  1936. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1937. self.ui.plot_tab_area.protectTab(0)
  1938. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1939. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1940. self.ui.project_frame.setDisabled(False)
  1941. def get_last_folder(self):
  1942. """
  1943. Get the folder path from where the last file was opened.
  1944. :return: String, last opened folder path
  1945. """
  1946. return self.defaults["global_last_folder"]
  1947. def get_last_save_folder(self):
  1948. """
  1949. Get the folder path from where the last file was saved.
  1950. :return: String, last saved folder path
  1951. """
  1952. loc = self.defaults["global_last_save_folder"]
  1953. if loc is None:
  1954. loc = self.defaults["global_last_folder"]
  1955. if loc is None:
  1956. loc = os.path.dirname(__file__)
  1957. return loc
  1958. def info(self, msg):
  1959. """
  1960. Informs the user. Normally on the status bar, optionally
  1961. also on the shell.
  1962. :param msg: Text to write.
  1963. :return: None
  1964. """
  1965. # Type of message in brackets at the beginning of the message.
  1966. match = re.search(r"\[(.*)\](.*)", msg)
  1967. if match:
  1968. level = match.group(1)
  1969. msg_ = match.group(2)
  1970. self.ui.fcinfo.set_status(str(msg_), level=level)
  1971. if level.lower() == "error":
  1972. self.shell_message(msg, error=True, show=True)
  1973. elif level.lower() == "warning":
  1974. self.shell_message(msg, warning=True, show=True)
  1975. elif level.lower() == "error_notcl":
  1976. self.shell_message(msg, error=True, show=False)
  1977. elif level.lower() == "warning_notcl":
  1978. self.shell_message(msg, warning=True, show=False)
  1979. elif level.lower() == "success":
  1980. self.shell_message(msg, success=True, show=False)
  1981. elif level.lower() == "selected":
  1982. self.shell_message(msg, selected=True, show=False)
  1983. else:
  1984. self.shell_message(msg, show=False)
  1985. else:
  1986. self.ui.fcinfo.set_status(str(msg), level="info")
  1987. # make sure that if the message is to clear the infobar with a space
  1988. # is not printed over and over on the shell
  1989. if msg != '':
  1990. self.shell_message(msg)
  1991. def restore_toolbar_view(self):
  1992. """
  1993. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1994. was saved in the defaults dictionary.
  1995. :return: None
  1996. """
  1997. tb = self.defaults["global_toolbar_view"]
  1998. if tb & 1:
  1999. self.ui.toolbarfile.setVisible(True)
  2000. else:
  2001. self.ui.toolbarfile.setVisible(False)
  2002. if tb & 2:
  2003. self.ui.toolbargeo.setVisible(True)
  2004. else:
  2005. self.ui.toolbargeo.setVisible(False)
  2006. if tb & 4:
  2007. self.ui.toolbarview.setVisible(True)
  2008. else:
  2009. self.ui.toolbarview.setVisible(False)
  2010. if tb & 8:
  2011. self.ui.toolbartools.setVisible(True)
  2012. else:
  2013. self.ui.toolbartools.setVisible(False)
  2014. if tb & 16:
  2015. self.ui.exc_edit_toolbar.setVisible(True)
  2016. else:
  2017. self.ui.exc_edit_toolbar.setVisible(False)
  2018. if tb & 32:
  2019. self.ui.geo_edit_toolbar.setVisible(True)
  2020. else:
  2021. self.ui.geo_edit_toolbar.setVisible(False)
  2022. if tb & 64:
  2023. self.ui.grb_edit_toolbar.setVisible(True)
  2024. else:
  2025. self.ui.grb_edit_toolbar.setVisible(False)
  2026. if tb & 128:
  2027. self.ui.snap_toolbar.setVisible(True)
  2028. else:
  2029. self.ui.snap_toolbar.setVisible(False)
  2030. if tb & 256:
  2031. self.ui.toolbarshell.setVisible(True)
  2032. else:
  2033. self.ui.toolbarshell.setVisible(False)
  2034. def on_import_preferences(self):
  2035. """
  2036. Loads the application default settings from a saved file into
  2037. ``self.defaults`` dictionary.
  2038. :return: None
  2039. """
  2040. self.defaults.report_usage("on_import_preferences")
  2041. App.log.debug("App.on_import_preferences()")
  2042. # Show file chooser
  2043. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2044. try:
  2045. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2046. directory=self.data_path,
  2047. filter=filter_)
  2048. except TypeError:
  2049. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2050. filter=filter_)
  2051. filename = str(filename)
  2052. if filename == "":
  2053. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2054. return
  2055. # Load in the defaults from the chosen file
  2056. self.defaults.load(filename=filename)
  2057. self.preferencesUiManager.on_preferences_edited()
  2058. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2059. def on_export_preferences(self):
  2060. """
  2061. Save the defaults dictionary to a file.
  2062. :return: None
  2063. """
  2064. self.defaults.report_usage("on_export_preferences")
  2065. App.log.debug("on_export_preferences()")
  2066. # defaults_file_content = None
  2067. # Show file chooser
  2068. date = str(datetime.today()).rpartition('.')[0]
  2069. date = ''.join(c for c in date if c not in ':-')
  2070. date = date.replace(' ', '_')
  2071. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2072. try:
  2073. filename, _f = FCFileSaveDialog.get_saved_filename(
  2074. caption=_("Export FlatCAM Preferences"),
  2075. directory=self.data_path + '/preferences_' + date,
  2076. filter=filter__
  2077. )
  2078. except TypeError:
  2079. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2080. filename = str(filename)
  2081. if filename == "":
  2082. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2083. return
  2084. # Update options
  2085. self.preferencesUiManager.defaults_read_form()
  2086. self.defaults.propagate_defaults()
  2087. # Save update options
  2088. try:
  2089. self.defaults.write(filename=filename)
  2090. except Exception:
  2091. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2092. return
  2093. if self.defaults["global_open_style"] is False:
  2094. self.file_opened.emit("preferences", filename)
  2095. self.file_saved.emit("preferences", filename)
  2096. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2097. def save_to_file(self, content_to_save, txt_content):
  2098. """
  2099. Save something to a file.
  2100. :return: None
  2101. """
  2102. self.defaults.report_usage("save_to_file")
  2103. App.log.debug("save_to_file()")
  2104. self.date = str(datetime.today()).rpartition('.')[0]
  2105. self.date = ''.join(c for c in self.date if c not in ':-')
  2106. self.date = self.date.replace(' ', '_')
  2107. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2108. path_to_save = self.defaults["global_last_save_folder"] if \
  2109. self.defaults["global_last_save_folder"] is not None else self.data_path
  2110. try:
  2111. filename, _f = FCFileSaveDialog.get_saved_filename(
  2112. caption=_("Save to file"),
  2113. directory=path_to_save + '/file_' + self.date,
  2114. filter=filter__
  2115. )
  2116. except TypeError:
  2117. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2118. filename = str(filename)
  2119. if filename == "":
  2120. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2121. return
  2122. else:
  2123. try:
  2124. with open(filename, 'w') as f:
  2125. ___ = f.read()
  2126. except PermissionError:
  2127. self.inform.emit('[WARNING] %s' %
  2128. _("Permission denied, saving not possible.\n"
  2129. "Most likely another app is holding the file open and not accessible."))
  2130. return
  2131. except IOError:
  2132. App.log.debug('Creating a new file ...')
  2133. f = open(filename, 'w')
  2134. f.close()
  2135. except Exception:
  2136. e = sys.exc_info()[0]
  2137. App.log.error("Could not load the file.")
  2138. App.log.error(str(e))
  2139. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2140. return
  2141. # Save content
  2142. if filename.rpartition('.')[2].lower() == 'html':
  2143. file_content = content_to_save
  2144. else:
  2145. file_content = txt_content
  2146. try:
  2147. with open(filename, "w") as f:
  2148. f.write(file_content)
  2149. except Exception:
  2150. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2151. return
  2152. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2153. def save_geometry(self, x, y, width, height, notebook_width):
  2154. """
  2155. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2156. launch of the application.
  2157. :param x: X position of the main window
  2158. :param y: Y position of the main window
  2159. :param width: width of the main window
  2160. :param height: height of the main window
  2161. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2162. :return: None
  2163. """
  2164. self.defaults["global_def_win_x"] = x
  2165. self.defaults["global_def_win_y"] = y
  2166. self.defaults["global_def_win_w"] = width
  2167. self.defaults["global_def_win_h"] = height
  2168. self.defaults["global_def_notebook_width"] = notebook_width
  2169. self.preferencesUiManager.save_defaults()
  2170. def restore_main_win_geom(self):
  2171. try:
  2172. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2173. self.defaults["global_def_win_y"],
  2174. self.defaults["global_def_win_w"],
  2175. self.defaults["global_def_win_h"])
  2176. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2177. except KeyError as e:
  2178. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2179. def message_dialog(self, title, message, kind="info"):
  2180. """
  2181. Builds and show a custom QMessageBox to be used in FlatCAM.
  2182. :param title: title of the QMessageBox
  2183. :param message: message to be displayed
  2184. :param kind: type of QMessageBox; will display a specific icon.
  2185. :return:
  2186. """
  2187. icon = {"info": QtWidgets.QMessageBox.Information,
  2188. "warning": QtWidgets.QMessageBox.Warning,
  2189. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2190. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2191. dlg.setText(message)
  2192. dlg.exec_()
  2193. def register_recent(self, kind, filename):
  2194. """
  2195. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2196. dictionary.
  2197. :param kind: type of file that was opened
  2198. :param filename: the path and file name for the file that was opened
  2199. :return:
  2200. """
  2201. self.log.debug("register_recent()")
  2202. self.log.debug(" %s" % kind)
  2203. self.log.debug(" %s" % filename)
  2204. record = {'kind': str(kind), 'filename': str(filename)}
  2205. if record in self.recent:
  2206. return
  2207. if record in self.recent_projects:
  2208. return
  2209. if record['kind'] == 'project':
  2210. self.recent_projects.insert(0, record)
  2211. else:
  2212. self.recent.insert(0, record)
  2213. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2214. self.recent.pop()
  2215. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2216. self.recent_projects.pop()
  2217. try:
  2218. f = open(self.data_path + '/recent.json', 'w')
  2219. except IOError:
  2220. App.log.error("Failed to open recent items file for writing.")
  2221. self.inform.emit('[ERROR_NOTCL] %s' %
  2222. _('Failed to open recent files file for writing.'))
  2223. return
  2224. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2225. f.close()
  2226. try:
  2227. fp = open(self.data_path + '/recent_projects.json', 'w')
  2228. except IOError:
  2229. App.log.error("Failed to open recent items file for writing.")
  2230. self.inform.emit('[ERROR_NOTCL] %s' %
  2231. _('Failed to open recent projects file for writing.'))
  2232. return
  2233. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2234. fp.close()
  2235. # Re-build the recent items menu
  2236. self.setup_recent_items()
  2237. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2238. """
  2239. Creates a new specialized FlatCAMObj and attaches it to the application,
  2240. this is, updates the GUI accordingly, any other records and plots it.
  2241. This method is thread-safe.
  2242. Notes:
  2243. * If the name is in use, the self.collection will modify it
  2244. when appending it to the collection. There is no need to handle
  2245. name conflicts here.
  2246. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2247. :type kind: str
  2248. :param name: Name for the object.
  2249. :type name: str
  2250. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2251. The function is called with 2 parameters: the new object and the App instance.
  2252. :type initialize: function
  2253. :param plot: If to plot the resulting object
  2254. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2255. self.collection
  2256. :return: None
  2257. :rtype: None
  2258. """
  2259. App.log.debug("new_object()")
  2260. obj_plot = plot
  2261. obj_autoselected = autoselected
  2262. t0 = time.time() # Debug
  2263. # ## Create object
  2264. classdict = {
  2265. "gerber": GerberObject,
  2266. "excellon": ExcellonObject,
  2267. "cncjob": CNCJobObject,
  2268. "geometry": GeometryObject,
  2269. "script": ScriptObject,
  2270. "document": DocumentObject
  2271. }
  2272. App.log.debug("Calling object constructor...")
  2273. # Object creation/instantiation
  2274. obj = classdict[kind](name)
  2275. obj.units = self.options["units"]
  2276. # IMPORTANT
  2277. # The key names in defaults and options dictionary's are not random:
  2278. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2279. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2280. # copied to self.options. After that, below, depending on the type of
  2281. # object that is created, it will strip the name of the object and the underline (if the original key was
  2282. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2283. # "toolchange"
  2284. for option in self.options:
  2285. if option.find(kind + "_") == 0:
  2286. oname = option[len(kind) + 1:]
  2287. obj.options[oname] = self.options[option]
  2288. obj.isHovering = False
  2289. obj.notHovering = True
  2290. # Initialize as per user request
  2291. # User must take care to implement initialize
  2292. # in a thread-safe way as is is likely that we
  2293. # have been invoked in a separate thread.
  2294. t1 = time.time()
  2295. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2296. try:
  2297. return_value = initialize(obj, self)
  2298. except Exception as e:
  2299. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2300. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2301. msg += traceback.format_exc()
  2302. self.inform.emit(msg)
  2303. return "fail"
  2304. t2 = time.time()
  2305. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2306. if return_value == 'fail':
  2307. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2308. return "fail"
  2309. # Check units and convert if necessary
  2310. # This condition CAN be true because initialize() can change obj.units
  2311. if self.options["units"].upper() != obj.units.upper():
  2312. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2313. obj.convert_units(self.options["units"])
  2314. t3 = time.time()
  2315. self.log.debug("%f seconds converting units." % (t3 - t2))
  2316. # Create the bounding box for the object and then add the results to the obj.options
  2317. # But not for Scripts or for Documents
  2318. if kind != 'document' and kind != 'script':
  2319. try:
  2320. xmin, ymin, xmax, ymax = obj.bounds()
  2321. obj.options['xmin'] = xmin
  2322. obj.options['ymin'] = ymin
  2323. obj.options['xmax'] = xmax
  2324. obj.options['ymax'] = ymax
  2325. except Exception as e:
  2326. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2327. return "fail"
  2328. try:
  2329. if kind == 'excellon':
  2330. obj.fill_color = self.defaults["excellon_plot_fill"]
  2331. obj.outline_color = self.defaults["excellon_plot_line"]
  2332. if kind == 'gerber':
  2333. obj.fill_color = self.defaults["gerber_plot_fill"]
  2334. obj.outline_color = self.defaults["gerber_plot_line"]
  2335. except Exception as e:
  2336. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2337. # update the KeyWords list with the name of the file
  2338. self.myKeywords.append(obj.options['name'])
  2339. log.debug("Moving new object back to main thread.")
  2340. # Move the object to the main thread and let the app know that it is available.
  2341. obj.moveToThread(self.main_thread)
  2342. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2343. return obj
  2344. def new_excellon_object(self):
  2345. """
  2346. Creates a new, blank Excellon object.
  2347. :return: None
  2348. """
  2349. self.defaults.report_usage("new_excellon_object()")
  2350. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2351. def new_geometry_object(self):
  2352. """
  2353. Creates a new, blank and single-tool Geometry object.
  2354. :return: None
  2355. """
  2356. self.defaults.report_usage("new_geometry_object()")
  2357. def initialize(obj, app):
  2358. obj.multitool = False
  2359. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2360. def new_gerber_object(self):
  2361. """
  2362. Creates a new, blank Gerber object.
  2363. :return: None
  2364. """
  2365. self.defaults.report_usage("new_gerber_object()")
  2366. def initialize(grb_obj, app):
  2367. grb_obj.multitool = False
  2368. grb_obj.source_file = []
  2369. grb_obj.multigeo = False
  2370. grb_obj.follow = False
  2371. grb_obj.apertures = {}
  2372. grb_obj.solid_geometry = []
  2373. try:
  2374. grb_obj.options['xmin'] = 0
  2375. grb_obj.options['ymin'] = 0
  2376. grb_obj.options['xmax'] = 0
  2377. grb_obj.options['ymax'] = 0
  2378. except KeyError:
  2379. pass
  2380. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2381. def new_script_object(self):
  2382. """
  2383. Creates a new, blank TCL Script object.
  2384. :return: None
  2385. """
  2386. self.defaults.report_usage("new_script_object()")
  2387. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2388. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2389. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2390. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2391. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2392. # "ListSys, MillDrills,\n" \
  2393. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2394. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2395. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2396. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2397. # "# SubtractRectangle, Version, WriteGCode\n"
  2398. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2399. '# %s:\n' % _('TCL Tutorial is here') + \
  2400. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2401. '# %s:\n' % _("FlatCAM commands list")
  2402. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2403. "(displayed in Tcl Shell).")
  2404. def initialize(obj, app):
  2405. obj.source_file = deepcopy(new_source_file)
  2406. outname = 'new_script'
  2407. self.new_object('script', outname, initialize, plot=False)
  2408. def new_document_object(self):
  2409. """
  2410. Creates a new, blank Document object.
  2411. :return: None
  2412. """
  2413. self.defaults.report_usage("new_document_object()")
  2414. def initialize(obj, app):
  2415. obj.source_file = ""
  2416. self.new_object('document', 'new_document', initialize, plot=False)
  2417. def on_object_created(self, obj, plot, auto_select):
  2418. """
  2419. Event callback for object creation.
  2420. It will add the new object to the collection. After that it will plot the object in a threaded way
  2421. :param obj: The newly created FlatCAM object.
  2422. :param plot: if the newly create object t obe plotted
  2423. :param auto_select: if the newly created object to be autoselected after creation
  2424. :return: None
  2425. """
  2426. t0 = time.time() # DEBUG
  2427. self.log.debug("on_object_created()")
  2428. # The Collection might change the name if there is a collision
  2429. self.collection.append(obj)
  2430. # after adding the object to the collection always update the list of objects that are in the collection
  2431. self.all_objects_list = self.collection.get_list()
  2432. # self.inform.emit('[selected] %s created & selected: %s' %
  2433. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2434. if obj.kind == 'gerber':
  2435. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2436. kind=obj.kind.capitalize(),
  2437. color='green',
  2438. name=str(obj.options['name']), tx=_("created/selected"))
  2439. )
  2440. elif obj.kind == 'excellon':
  2441. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2442. kind=obj.kind.capitalize(),
  2443. color='brown',
  2444. name=str(obj.options['name']), tx=_("created/selected"))
  2445. )
  2446. elif obj.kind == 'cncjob':
  2447. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2448. kind=obj.kind.capitalize(),
  2449. color='blue',
  2450. name=str(obj.options['name']), tx=_("created/selected"))
  2451. )
  2452. elif obj.kind == 'geometry':
  2453. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2454. kind=obj.kind.capitalize(),
  2455. color='red',
  2456. name=str(obj.options['name']), tx=_("created/selected"))
  2457. )
  2458. elif obj.kind == 'script':
  2459. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2460. kind=obj.kind.capitalize(),
  2461. color='orange',
  2462. name=str(obj.options['name']), tx=_("created/selected"))
  2463. )
  2464. elif obj.kind == 'document':
  2465. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2466. kind=obj.kind.capitalize(),
  2467. color='darkCyan',
  2468. name=str(obj.options['name']), tx=_("created/selected"))
  2469. )
  2470. # update the SHELL auto-completer model with the name of the new object
  2471. self.shell._edit.set_model_data(self.myKeywords)
  2472. if auto_select:
  2473. # select the just opened object but deselect the previous ones
  2474. self.collection.set_all_inactive()
  2475. self.collection.set_active(obj.options["name"])
  2476. else:
  2477. self.collection.set_all_inactive()
  2478. # here it is done the object plotting
  2479. def worker_task(t_obj):
  2480. with self.proc_container.new(_("Plotting")):
  2481. if isinstance(t_obj, CNCJobObject):
  2482. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2483. else:
  2484. t_obj.plot()
  2485. t1 = time.time() # DEBUG
  2486. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2487. self.object_plotted.emit(t_obj)
  2488. # Send to worker
  2489. # self.worker.add_task(worker_task, [self])
  2490. if plot is True:
  2491. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2492. def on_object_changed(self, obj):
  2493. """
  2494. Called whenever the geometry of the object was changed in some way.
  2495. This require the update of it's bounding values so it can be the selected on canvas.
  2496. Update the bounding box data from obj.options
  2497. :param obj: the object that was changed
  2498. :return: None
  2499. """
  2500. xmin, ymin, xmax, ymax = obj.bounds()
  2501. obj.options['xmin'] = xmin
  2502. obj.options['ymin'] = ymin
  2503. obj.options['xmax'] = xmax
  2504. obj.options['ymax'] = ymax
  2505. log.debug("Object changed, updating the bounding box data on self.options")
  2506. # delete the old selection shape
  2507. self.delete_selection_shape()
  2508. self.should_we_save = True
  2509. def on_object_plotted(self):
  2510. """
  2511. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2512. :return: None
  2513. """
  2514. self.on_zoom_fit(None)
  2515. def on_about(self):
  2516. """
  2517. Displays the "about" dialog found in the Menu --> Help.
  2518. :return: None
  2519. """
  2520. self.defaults.report_usage("on_about")
  2521. version = self.version
  2522. version_date = self.version_date
  2523. beta = self.beta
  2524. class AboutDialog(QtWidgets.QDialog):
  2525. def __init__(self, app, parent=None):
  2526. QtWidgets.QDialog.__init__(self, parent)
  2527. self.app = app
  2528. # Icon and title
  2529. self.setWindowIcon(parent.app_icon)
  2530. self.setWindowTitle(_("About FlatCAM"))
  2531. self.resize(600, 200)
  2532. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2533. # self.setStyleSheet(
  2534. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2535. # "background-attachment: fixed"
  2536. # )
  2537. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2538. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2539. # palette = QtGui.QPalette()
  2540. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2541. # self.setPalette(palette)
  2542. logo = QtWidgets.QLabel()
  2543. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2544. title = QtWidgets.QLabel(
  2545. "<font size=8><B>FlatCAM</B></font><BR>"
  2546. "{title}<BR>"
  2547. "<BR>"
  2548. "<BR>"
  2549. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2550. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2551. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2552. "<B>{issue}</B></a><BR>".format(
  2553. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2554. devel=_("Development"),
  2555. down=_("DOWNLOAD"),
  2556. issue=_("Issue tracker"))
  2557. )
  2558. title.setOpenExternalLinks(True)
  2559. closebtn = QtWidgets.QPushButton(_("Close"))
  2560. tab_widget = QtWidgets.QTabWidget()
  2561. description_label = QtWidgets.QLabel(
  2562. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2563. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2564. version=version,
  2565. beta=('BETA' if beta else ''),
  2566. date=version_date,
  2567. arch=platform.architecture()[0])
  2568. )
  2569. description_label.setOpenExternalLinks(True)
  2570. lic_lbl_header = QtWidgets.QLabel(
  2571. '%s:<br>%s<br>' % (
  2572. _('Licensed under the MIT license'),
  2573. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2574. "http://www.opensource.org/licenses/mit-license.php</a>"
  2575. )
  2576. )
  2577. lic_lbl_header.setOpenExternalLinks(True)
  2578. lic_lbl_body = QtWidgets.QLabel(
  2579. _(
  2580. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2581. 'of this software and associated documentation files (the "Software"), to deal\n'
  2582. 'in the Software without restriction, including without limitation the rights\n'
  2583. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2584. 'copies of the Software, and to permit persons to whom the Software is\n'
  2585. 'furnished to do so, subject to the following conditions:\n\n'
  2586. 'The above copyright notice and this permission notice shall be included in\n'
  2587. 'all copies or substantial portions of the Software.\n\n'
  2588. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2589. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2590. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2591. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2592. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2593. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2594. 'THE SOFTWARE.'
  2595. )
  2596. )
  2597. attributions_label = QtWidgets.QLabel(
  2598. _(
  2599. 'Some of the icons used are from the following sources:<br>'
  2600. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2601. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2602. 'title="Flaticon">www.flaticon.com</a></div>'
  2603. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2604. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2605. )
  2606. )
  2607. attributions_label.setOpenExternalLinks(True)
  2608. # layouts
  2609. layout1 = QtWidgets.QVBoxLayout()
  2610. layout1_1 = QtWidgets.QHBoxLayout()
  2611. layout1_2 = QtWidgets.QHBoxLayout()
  2612. layout2 = QtWidgets.QHBoxLayout()
  2613. layout3 = QtWidgets.QHBoxLayout()
  2614. self.setLayout(layout1)
  2615. layout1.addLayout(layout1_1)
  2616. layout1.addLayout(layout1_2)
  2617. layout1.addLayout(layout2)
  2618. layout1.addLayout(layout3)
  2619. layout1_1.addStretch()
  2620. layout1_1.addWidget(description_label)
  2621. layout1_2.addWidget(tab_widget)
  2622. self.splash_tab = QtWidgets.QWidget()
  2623. self.splash_tab.setObjectName("splash_about")
  2624. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2625. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2626. tab_widget.addTab(self.splash_tab, _("Splash"))
  2627. self.programmmers_tab = QtWidgets.QWidget()
  2628. self.programmmers_tab.setObjectName("programmers_about")
  2629. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2630. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2631. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2632. self.translators_tab = QtWidgets.QWidget()
  2633. self.translators_tab.setObjectName("translators_about")
  2634. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2635. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2636. tab_widget.addTab(self.translators_tab, _("Translators"))
  2637. self.license_tab = QtWidgets.QWidget()
  2638. self.license_tab.setObjectName("license_about")
  2639. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2640. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2641. tab_widget.addTab(self.license_tab, _("License"))
  2642. self.attributions_tab = QtWidgets.QWidget()
  2643. self.attributions_tab.setObjectName("attributions_about")
  2644. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2645. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2646. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2647. self.splash_tab_layout.addWidget(logo, stretch=0)
  2648. self.splash_tab_layout.addWidget(title, stretch=1)
  2649. pal = QtGui.QPalette()
  2650. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2651. self.prog_grid_lay = QtWidgets.QGridLayout()
  2652. self.prog_grid_lay.setHorizontalSpacing(20)
  2653. self.prog_grid_lay.setColumnStretch(0, 0)
  2654. self.prog_grid_lay.setColumnStretch(2, 1)
  2655. prog_widget = QtWidgets.QWidget()
  2656. prog_widget.setLayout(self.prog_grid_lay)
  2657. prog_scroll = QtWidgets.QScrollArea()
  2658. prog_scroll.setWidget(prog_widget)
  2659. prog_scroll.setWidgetResizable(True)
  2660. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2661. prog_scroll.setPalette(pal)
  2662. self.programmmers_tab_layout.addWidget(prog_scroll)
  2663. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2664. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2665. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2704. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2705. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2706. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2707. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2708. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2709. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2710. self.translator_grid_lay = QtWidgets.QGridLayout()
  2711. self.translator_grid_lay.setColumnStretch(0, 0)
  2712. self.translator_grid_lay.setColumnStretch(1, 0)
  2713. self.translator_grid_lay.setColumnStretch(2, 1)
  2714. self.translator_grid_lay.setColumnStretch(3, 0)
  2715. # trans_widget = QtWidgets.QWidget()
  2716. # trans_widget.setLayout(self.translator_grid_lay)
  2717. # self.translators_tab_layout.addWidget(trans_widget)
  2718. # self.translators_tab_layout.addStretch()
  2719. trans_widget = QtWidgets.QWidget()
  2720. trans_widget.setLayout(self.translator_grid_lay)
  2721. trans_scroll = QtWidgets.QScrollArea()
  2722. trans_scroll.setWidget(trans_widget)
  2723. trans_scroll.setWidgetResizable(True)
  2724. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2725. trans_scroll.setPalette(pal)
  2726. self.translators_tab_layout.addWidget(trans_scroll)
  2727. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2728. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2750. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2751. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2752. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2753. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2754. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2755. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2756. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2757. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2758. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2759. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2760. self.translator_grid_lay.setColumnStretch(0, 0)
  2761. self.translators_tab_layout.addStretch()
  2762. self.license_tab_layout.addWidget(lic_lbl_header)
  2763. self.license_tab_layout.addWidget(lic_lbl_body)
  2764. self.license_tab_layout.addStretch()
  2765. self.attributions_tab_layout.addWidget(attributions_label)
  2766. self.attributions_tab_layout.addStretch()
  2767. layout3.addStretch()
  2768. layout3.addWidget(closebtn)
  2769. closebtn.clicked.connect(self.accept)
  2770. AboutDialog(app=self, parent=self.ui).exec_()
  2771. def install_bookmarks(self, book_dict=None):
  2772. """
  2773. Install the bookmarks actions in the Help menu -> Bookmarks
  2774. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2775. :return: None
  2776. """
  2777. if book_dict is None:
  2778. self.defaults["global_bookmarks"].update(
  2779. {
  2780. '1': ['FlatCAM', "http://flatcam.org"],
  2781. '2': ['Backup Site', ""]
  2782. }
  2783. )
  2784. else:
  2785. self.defaults["global_bookmarks"].clear()
  2786. self.defaults["global_bookmarks"].update(book_dict)
  2787. # first try to disconnect if somehow they get connected from elsewhere
  2788. for act in self.ui.menuhelp_bookmarks.actions():
  2789. try:
  2790. act.triggered.disconnect()
  2791. except TypeError:
  2792. pass
  2793. # clear all actions except the last one who is the Bookmark manager
  2794. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2795. pass
  2796. else:
  2797. self.ui.menuhelp_bookmarks.removeAction(act)
  2798. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2799. if self.defaults["global_bookmarks"]:
  2800. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2801. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2802. # the JSON is first making the keys as strings (therefore I have to use strings too
  2803. # or do the conversion :(
  2804. # )
  2805. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2806. # the '10' entry jsut after '1' therefore ordering as strings
  2807. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2808. key=lambda x: int(x[0]))
  2809. for entry, bookmark in sorted_bookmarks:
  2810. title = bookmark[0]
  2811. weblink = bookmark[1]
  2812. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2813. act.setText(title)
  2814. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2815. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2816. if title == 'Backup Site' and weblink == "":
  2817. act.triggered.connect(self.on_backup_site)
  2818. else:
  2819. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2820. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2821. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2822. def on_bookmarks_manager(self):
  2823. """
  2824. Adds the bookmark manager in a Tab in Plot Area
  2825. :return:
  2826. """
  2827. for idx in range(self.ui.plot_tab_area.count()):
  2828. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2829. # there can be only one instance of Bookmark Manager at one time
  2830. return
  2831. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2832. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2833. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2834. # add the tab if it was closed
  2835. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2836. # delete the absolute and relative position and messages in the infobar
  2837. self.ui.position_label.setText("")
  2838. self.ui.rel_position_label.setText("")
  2839. # Switch plot_area to preferences page
  2840. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2841. def on_backup_site(self):
  2842. msgbox = QtWidgets.QMessageBox()
  2843. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2844. "1. FlatCAM.org website is down\n"
  2845. "2. Someone forked FlatCAM project and wants to point\n"
  2846. "to his own website\n\n"
  2847. "If you can't get any informations about FlatCAM beta\n"
  2848. "use the YouTube channel link from the Help menu."))
  2849. msgbox.setWindowTitle(_("Alternative website"))
  2850. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2851. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2852. msgbox.setDefaultButton(bt_yes)
  2853. msgbox.exec_()
  2854. # response = msgbox.clickedButton()
  2855. def on_file_savedefaults(self):
  2856. """
  2857. Callback for menu item File->Save Defaults. Saves application default options
  2858. ``self.defaults`` to current_defaults.FlatConfig.
  2859. :return: None
  2860. """
  2861. self.preferencesUiManager.save_defaults()
  2862. def final_save(self):
  2863. """
  2864. Callback for doing a preferences save to file whenever the application is about to quit.
  2865. If the project has changes, it will ask the user to save the project.
  2866. :return: None
  2867. """
  2868. if self.save_in_progress:
  2869. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2870. return
  2871. if self.should_we_save and self.collection.get_list():
  2872. msgbox = QtWidgets.QMessageBox()
  2873. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2874. "\n"
  2875. "Do you want to Save the project?"))
  2876. msgbox.setWindowTitle(_("Save changes"))
  2877. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2878. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2879. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2880. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2881. msgbox.setDefaultButton(bt_yes)
  2882. msgbox.exec_()
  2883. response = msgbox.clickedButton()
  2884. if response == bt_yes:
  2885. try:
  2886. self.trayIcon.hide()
  2887. except Exception:
  2888. pass
  2889. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2890. elif response == bt_no:
  2891. try:
  2892. self.trayIcon.hide()
  2893. except Exception:
  2894. pass
  2895. self.quit_application()
  2896. elif response == bt_cancel:
  2897. return
  2898. else:
  2899. try:
  2900. self.trayIcon.hide()
  2901. except Exception:
  2902. pass
  2903. self.quit_application()
  2904. def quit_application(self):
  2905. """
  2906. Called (as a pyslot or not) when the application is quit.
  2907. :return: None
  2908. """
  2909. self.preferencesUiManager.save_defaults(silent=True)
  2910. log.debug("App.quit_application() --> App Defaults saved.")
  2911. if self.cmd_line_headless != 1:
  2912. # save app state to file
  2913. stgs = QSettings("Open Source", "FlatCAM")
  2914. stgs.setValue('saved_gui_state', self.ui.saveState())
  2915. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2916. stgs.setValue(
  2917. 'language',
  2918. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2919. )
  2920. stgs.setValue(
  2921. 'notebook_font_size',
  2922. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2923. )
  2924. stgs.setValue(
  2925. 'axis_font_size',
  2926. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2927. )
  2928. stgs.setValue(
  2929. 'textbox_font_size',
  2930. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2931. )
  2932. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2933. stgs.setValue(
  2934. 'machinist',
  2935. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2936. )
  2937. # This will write the setting to the platform specific storage.
  2938. del stgs
  2939. log.debug("App.quit_application() --> App UI state saved.")
  2940. # try to quit the Socket opened by ArgsThread class
  2941. try:
  2942. self.new_launch.stop.emit()
  2943. except Exception as err:
  2944. log.debug("App.quit_application() --> %s" % str(err))
  2945. # try to quit the QThread that run ArgsThread class
  2946. try:
  2947. self.th.quit()
  2948. except Exception as e:
  2949. log.debug("App.quit_application() --> %s" % str(e))
  2950. # terminate workers
  2951. self.workers.__del__()
  2952. # quit app by signalling for self.kill_app() method
  2953. # self.close_app_signal.emit()
  2954. QtWidgets.qApp.quit()
  2955. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2956. # we use the following command
  2957. minor_v = sys.version_info.minor
  2958. if minor_v < 8:
  2959. sys.exit(0)
  2960. else:
  2961. os._exit(0) # fix to work with Python 3.8
  2962. @staticmethod
  2963. def kill_app():
  2964. QtWidgets.qApp.quit()
  2965. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2966. # we use the following command
  2967. sys.exit(0)
  2968. def on_portable_checked(self, state):
  2969. """
  2970. Callback called when the checkbox in Preferences GUI is checked.
  2971. It will set the application as portable by creating the preferences and recent files in the
  2972. 'config' folder found in the FlatCAM installation folder.
  2973. :param state: boolean, the state of the checkbox when clicked/checked
  2974. :return:
  2975. """
  2976. line_no = 0
  2977. data = None
  2978. if sys.platform != 'win32':
  2979. # this won't work in Linux or MacOS
  2980. return
  2981. # test if the app was frozen and choose the path for the configuration file
  2982. if getattr(sys, "frozen", False) is True:
  2983. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2984. else:
  2985. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2986. config_file = current_data_path + '\\configuration.txt'
  2987. try:
  2988. with open(config_file, 'r') as f:
  2989. try:
  2990. data = f.readlines()
  2991. except Exception as e:
  2992. log.debug('App.__init__() -->%s' % str(e))
  2993. return
  2994. except FileNotFoundError:
  2995. pass
  2996. for line in data:
  2997. line = line.strip('\n')
  2998. param = str(line).rpartition('=')
  2999. if param[0] == 'portable':
  3000. break
  3001. line_no += 1
  3002. if state:
  3003. data[line_no] = 'portable=True\n'
  3004. # create the new defauults files
  3005. # create current_defaults.FlatConfig file if there is none
  3006. try:
  3007. f = open(current_data_path + '/current_defaults.FlatConfig')
  3008. f.close()
  3009. except IOError:
  3010. App.log.debug('Creating empty current_defaults.FlatConfig')
  3011. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3012. json.dump({}, f)
  3013. f.close()
  3014. # create factory_defaults.FlatConfig file if there is none
  3015. try:
  3016. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3017. f.close()
  3018. except IOError:
  3019. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3020. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3021. json.dump({}, f)
  3022. f.close()
  3023. try:
  3024. f = open(current_data_path + '/recent.json')
  3025. f.close()
  3026. except IOError:
  3027. App.log.debug('Creating empty recent.json')
  3028. f = open(current_data_path + '/recent.json', 'w')
  3029. json.dump([], f)
  3030. f.close()
  3031. try:
  3032. fp = open(current_data_path + '/recent_projects.json')
  3033. fp.close()
  3034. except IOError:
  3035. App.log.debug('Creating empty recent_projects.json')
  3036. fp = open(current_data_path + '/recent_projects.json', 'w')
  3037. json.dump([], fp)
  3038. fp.close()
  3039. # save the current defaults to the new defaults file
  3040. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3041. else:
  3042. data[line_no] = 'portable=False\n'
  3043. with open(config_file, 'w') as f:
  3044. f.writelines(data)
  3045. def on_register_files(self, obj_type=None):
  3046. """
  3047. Called whenever there is a need to register file extensions with FlatCAM.
  3048. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3049. :param obj_type: the type of object to be register for.
  3050. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3051. :return: None
  3052. """
  3053. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3054. new_reg_path = 'Software\\Classes\\'
  3055. # find if the current user is admin
  3056. try:
  3057. is_admin = os.getuid() == 0
  3058. except AttributeError:
  3059. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3060. if is_admin is True:
  3061. root_path = winreg.HKEY_LOCAL_MACHINE
  3062. else:
  3063. root_path = winreg.HKEY_CURRENT_USER
  3064. # create the keys
  3065. def set_reg(name, root_pth, new_reg_path, value):
  3066. try:
  3067. winreg.CreateKey(root_pth, new_reg_path)
  3068. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3069. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3070. return True
  3071. except WindowsError:
  3072. return False
  3073. # delete key in registry
  3074. def delete_reg(root_pth, reg_path, key_to_del):
  3075. key_to_del_path = reg_path + key_to_del
  3076. try:
  3077. winreg.DeleteKey(root_pth, key_to_del_path)
  3078. return True
  3079. except WindowsError:
  3080. return False
  3081. if obj_type is None or obj_type == 'excellon':
  3082. exc_list = \
  3083. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3084. exc_list = [x for x in exc_list if x != '']
  3085. # register all keys in the Preferences window
  3086. for ext in exc_list:
  3087. new_k = new_reg_path + '.%s' % ext
  3088. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3089. # and unregister those that are no longer in the Preferences windows but are in the file
  3090. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3091. if ext not in exc_list:
  3092. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3093. # now write the updated extensions to the self.defaults
  3094. # new_ext = ''
  3095. # for ext in exc_list:
  3096. # new_ext = new_ext + ext + ', '
  3097. # self.defaults["fa_excellon"] = new_ext
  3098. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3099. if obj_type is None or obj_type == 'gcode':
  3100. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3101. gco_list = [x for x in gco_list if x != '']
  3102. # register all keys in the Preferences window
  3103. for ext in gco_list:
  3104. new_k = new_reg_path + '.%s' % ext
  3105. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3106. # and unregister those that are no longer in the Preferences windows but are in the file
  3107. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3108. if ext not in gco_list:
  3109. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3110. # now write the updated extensions to the self.defaults
  3111. # new_ext = ''
  3112. # for ext in gco_list:
  3113. # new_ext = new_ext + ext + ', '
  3114. # self.defaults["fa_gcode"] = new_ext
  3115. self.inform.emit('[success] %s' %
  3116. _("Selected GCode file extensions registered with FlatCAM."))
  3117. if obj_type is None or obj_type == 'gerber':
  3118. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3119. grb_list = [x for x in grb_list if x != '']
  3120. # register all keys in the Preferences window
  3121. for ext in grb_list:
  3122. new_k = new_reg_path + '.%s' % ext
  3123. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3124. # and unregister those that are no longer in the Preferences windows but are in the file
  3125. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3126. if ext not in grb_list:
  3127. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3128. # now write the updated extensions to the self.defaults
  3129. # new_ext = ''
  3130. # for ext in grb_list:
  3131. # new_ext = new_ext + ext + ', '
  3132. # self.defaults["fa_gerber"] = new_ext
  3133. self.inform.emit('[success] %s' %
  3134. _("Selected Gerber file extensions registered with FlatCAM."))
  3135. def add_extension(self, ext_type):
  3136. """
  3137. Add a file extension to the list for a specific object
  3138. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3139. :return:
  3140. """
  3141. if ext_type == 'excellon':
  3142. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3143. if new_ext == '':
  3144. return
  3145. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3146. if new_ext in old_val:
  3147. return
  3148. old_val.append(new_ext)
  3149. old_val.sort()
  3150. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3151. if ext_type == 'gcode':
  3152. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3153. if new_ext == '':
  3154. return
  3155. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3156. if new_ext in old_val:
  3157. return
  3158. old_val.append(new_ext)
  3159. old_val.sort()
  3160. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3161. if ext_type == 'gerber':
  3162. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3163. if new_ext == '':
  3164. return
  3165. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3166. if new_ext in old_val:
  3167. return
  3168. old_val.append(new_ext)
  3169. old_val.sort()
  3170. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3171. if ext_type == 'keyword':
  3172. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3173. if new_kw == '':
  3174. return
  3175. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3176. if new_kw in old_val:
  3177. return
  3178. old_val.append(new_kw)
  3179. old_val.sort()
  3180. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3181. # update the self.myKeywords so the model is updated
  3182. self.autocomplete_kw_list = \
  3183. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3184. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3185. self.shell._edit.set_model_data(self.myKeywords)
  3186. def del_extension(self, ext_type):
  3187. """
  3188. Remove a file extension from the list for a specific object
  3189. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3190. :return:
  3191. """
  3192. if ext_type == 'excellon':
  3193. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3194. if new_ext == '':
  3195. return
  3196. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3197. if new_ext not in old_val:
  3198. return
  3199. old_val.remove(new_ext)
  3200. old_val.sort()
  3201. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3202. if ext_type == 'gcode':
  3203. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3204. if new_ext == '':
  3205. return
  3206. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3207. if new_ext not in old_val:
  3208. return
  3209. old_val.remove(new_ext)
  3210. old_val.sort()
  3211. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3212. if ext_type == 'gerber':
  3213. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3214. if new_ext == '':
  3215. return
  3216. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3217. if new_ext not in old_val:
  3218. return
  3219. old_val.remove(new_ext)
  3220. old_val.sort()
  3221. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3222. if ext_type == 'keyword':
  3223. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3224. if new_kw == '':
  3225. return
  3226. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3227. if new_kw not in old_val:
  3228. return
  3229. old_val.remove(new_kw)
  3230. old_val.sort()
  3231. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3232. # update the self.myKeywords so the model is updated
  3233. self.autocomplete_kw_list = \
  3234. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3235. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3236. self.shell._edit.set_model_data(self.myKeywords)
  3237. def restore_extensions(self, ext_type):
  3238. """
  3239. Restore all file extensions associations with FlatCAM, for a specific object
  3240. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3241. :return:
  3242. """
  3243. if ext_type == 'excellon':
  3244. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3245. # for the ability to open Excellon files with .txt extension
  3246. new_exc_list = deepcopy(self.exc_list)
  3247. try:
  3248. new_exc_list.remove('txt')
  3249. except ValueError:
  3250. pass
  3251. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3252. if ext_type == 'gcode':
  3253. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3254. if ext_type == 'gerber':
  3255. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3256. if ext_type == 'keyword':
  3257. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3258. # update the self.myKeywords so the model is updated
  3259. self.autocomplete_kw_list = self.default_keywords
  3260. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3261. self.shell._edit.set_model_data(self.myKeywords)
  3262. def delete_all_extensions(self, ext_type):
  3263. """
  3264. Delete all file extensions associations with FlatCAM, for a specific object
  3265. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3266. :return:
  3267. """
  3268. if ext_type == 'excellon':
  3269. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3270. if ext_type == 'gcode':
  3271. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3272. if ext_type == 'gerber':
  3273. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3274. if ext_type == 'keyword':
  3275. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3276. # update the self.myKeywords so the model is updated
  3277. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3278. self.shell._edit.set_model_data(self.myKeywords)
  3279. def on_edit_join(self, name=None):
  3280. """
  3281. Callback for Edit->Join. Joins the selected geometry objects into
  3282. a new one.
  3283. :return: None
  3284. """
  3285. self.defaults.report_usage("on_edit_join()")
  3286. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3287. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3288. geo_type_set = set()
  3289. objs = self.collection.get_selected()
  3290. if len(objs) < 2:
  3291. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3292. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3293. return 'fail'
  3294. for obj in objs:
  3295. geo_type_set.add(obj.multigeo)
  3296. # if len(geo_type_list) == 1 means that all list elements are the same
  3297. if len(geo_type_set) != 1:
  3298. self.inform.emit('[ERROR] %s' %
  3299. _("Failed join. The Geometry objects are of different types.\n"
  3300. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3301. "convert from one to another and retry joining \n"
  3302. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3303. "the result may not be what was expected. \n"
  3304. "Check the generated GCODE."))
  3305. return
  3306. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3307. if True in geo_type_set:
  3308. def initialize(geo_obj, app):
  3309. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3310. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3311. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3312. for v in geo_obj.tools.values():
  3313. v['data']['name'] = obj_name_multi
  3314. self.new_object("geometry", obj_name_multi, initialize)
  3315. else:
  3316. def initialize(geo_obj, app):
  3317. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3318. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3319. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3320. for v in geo_obj.tools.values():
  3321. v['data']['name'] = obj_name_single
  3322. self.new_object("geometry", obj_name_single, initialize)
  3323. self.should_we_save = True
  3324. def on_edit_join_exc(self):
  3325. """
  3326. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3327. a new Excellon.
  3328. :return: None
  3329. """
  3330. self.defaults.report_usage("on_edit_join_exc()")
  3331. objs = self.collection.get_selected()
  3332. for obj in objs:
  3333. if not isinstance(obj, ExcellonObject):
  3334. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3335. return
  3336. if len(objs) < 2:
  3337. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3338. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3339. return 'fail'
  3340. def initialize(exc_obj, app):
  3341. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3342. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3343. self.new_object("excellon", 'Combo_Excellon', initialize)
  3344. self.should_we_save = True
  3345. def on_edit_join_grb(self):
  3346. """
  3347. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3348. a new Gerber object.
  3349. :return: None
  3350. """
  3351. self.defaults.report_usage("on_edit_join_grb()")
  3352. objs = self.collection.get_selected()
  3353. for obj in objs:
  3354. if not isinstance(obj, GerberObject):
  3355. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3356. return
  3357. if len(objs) < 2:
  3358. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3359. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3360. return 'fail'
  3361. def initialize(grb_obj, app):
  3362. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3363. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3364. self.new_object("gerber", 'Combo_Gerber', initialize)
  3365. self.should_we_save = True
  3366. def on_convert_singlegeo_to_multigeo(self):
  3367. """
  3368. Called for converting a Geometry object from single-geo to multi-geo.
  3369. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3370. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3371. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3372. the solid-geometry of that tool.
  3373. :return: None
  3374. """
  3375. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3376. obj = self.collection.get_active()
  3377. if obj is None:
  3378. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3379. return
  3380. if not isinstance(obj, GeometryObject):
  3381. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3382. return
  3383. obj.multigeo = True
  3384. for tooluid, dict_value in obj.tools.items():
  3385. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3386. if not isinstance(obj.solid_geometry, list):
  3387. obj.solid_geometry = [obj.solid_geometry]
  3388. # obj.solid_geometry[:] = []
  3389. obj.plot()
  3390. self.should_we_save = True
  3391. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3392. def on_convert_multigeo_to_singlegeo(self):
  3393. """
  3394. Called for converting a Geometry object from multi-geo to single-geo.
  3395. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3396. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3397. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3398. the solid-geometry of that tool.
  3399. :return: None
  3400. """
  3401. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3402. obj = self.collection.get_active()
  3403. if obj is None:
  3404. self.inform.emit('[ERROR_NOTCL] %s' %
  3405. _("Failed. Select a Geometry Object and try again."))
  3406. return
  3407. if not isinstance(obj, GeometryObject):
  3408. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3409. (_("Expected a GeometryObject, got"), type(obj)))
  3410. return
  3411. obj.multigeo = False
  3412. total_solid_geometry = []
  3413. for tooluid, dict_value in obj.tools.items():
  3414. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3415. # clear the original geometry
  3416. dict_value['solid_geometry'][:] = []
  3417. obj.solid_geometry = deepcopy(total_solid_geometry)
  3418. obj.plot()
  3419. self.should_we_save = True
  3420. self.inform.emit('[success] %s' %
  3421. _("A Geometry object was converted to SingleGeo type."))
  3422. def on_defaults_dict_change(self, field):
  3423. """
  3424. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3425. Edit -> Preferences tab window.
  3426. :param field: the key of the self.defaults dictionary that was changed.
  3427. :return: None
  3428. """
  3429. self.preferencesUiManager.defaults_write_form_field(field=field)
  3430. if field == "units":
  3431. self.set_screen_units(self.defaults['units'])
  3432. def set_screen_units(self, units):
  3433. """
  3434. Set the FlatCAM units on the status bar.
  3435. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3436. :return: None
  3437. """
  3438. self.ui.units_label.setText("[" + units.lower() + "]")
  3439. def on_toggle_units_click(self):
  3440. try:
  3441. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3442. except (TypeError, AttributeError):
  3443. pass
  3444. if self.defaults["units"] == 'MM':
  3445. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3446. else:
  3447. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3448. self.on_toggle_units(no_pref=True)
  3449. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3450. lambda: self.on_toggle_units(no_pref=False))
  3451. def on_toggle_units(self, no_pref=False):
  3452. """
  3453. Callback for the Units radio-button change in the Preferences tab.
  3454. Changes the application's default units adn for the project too.
  3455. If changing the project's units, the change propagates to all of
  3456. the objects in the project.
  3457. :return: None
  3458. """
  3459. self.defaults.report_usage("on_toggle_units")
  3460. if self.toggle_units_ignore:
  3461. return
  3462. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3463. # If option is the same, then ignore
  3464. if new_units == self.defaults["units"].upper():
  3465. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3466. return
  3467. # Keys in self.defaults for which to scale their values
  3468. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3469. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3470. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3471. "gerber_editor_ma_high",
  3472. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3473. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3474. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3475. "excellon_feedrate_probe", "excellon_milling_dia",
  3476. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3477. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3478. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3479. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3480. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3481. "geometry_extracut_length", "geometry_z_pdepth",
  3482. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3483. 'cncjob_tooldia',
  3484. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3485. "tools_paintnewdia",
  3486. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3487. "tools_nccnewdia", "tools_ncc_offset_value",
  3488. "tools_2sided_drilldia",
  3489. "tools_film_boundary", "tools_film_scale_stroke",
  3490. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3491. "tools_cutout_depthperpass",
  3492. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3493. "tools_panelize_spacing_rows",
  3494. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3495. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3496. "tools_transform_buffer_dis",
  3497. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3498. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3499. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3500. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3501. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3502. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3503. "tools_cr_h2h_val", "tools_cr_dh_val",
  3504. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3505. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3506. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3507. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3508. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3509. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3510. "tools_copper_thieving_mask_clearance",
  3511. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3512. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3513. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3514. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3515. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3516. "tools_invert_margin",
  3517. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3518. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3519. def scale_defaults(sfactor):
  3520. for dim in dimensions:
  3521. if dim in [
  3522. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3523. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3524. 'tools_transform_mirror_point'
  3525. ]:
  3526. if self.defaults[dim] is None or self.defaults[dim] == '':
  3527. continue
  3528. try:
  3529. coordinates = self.defaults[dim].split(",")
  3530. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3531. coords_xy[0] *= sfactor
  3532. coords_xy[1] *= sfactor
  3533. self.defaults[dim] = "%.*f, %.*f" % (
  3534. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3535. except Exception as e:
  3536. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3537. elif dim in [
  3538. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3539. ]:
  3540. if self.defaults[dim] is None or self.defaults[dim] == '':
  3541. continue
  3542. try:
  3543. self.defaults[dim] = float(self.defaults[dim])
  3544. tools_diameters = [self.defaults[dim]]
  3545. except ValueError:
  3546. try:
  3547. tools_string = self.defaults[dim].split(",")
  3548. tools_diameters = [eval(a) for a in tools_string if a != '']
  3549. except Exception as e:
  3550. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3551. continue
  3552. self.defaults[dim] = ''
  3553. td_len = len(tools_diameters)
  3554. if td_len > 1:
  3555. for t in range(td_len):
  3556. tools_diameters[t] *= sfactor
  3557. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3558. else:
  3559. tools_diameters[0] *= sfactor
  3560. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3561. elif dim in ['global_gridx', 'global_gridy']:
  3562. # format the number of decimals to the one specified in self.decimals
  3563. try:
  3564. val = float(self.defaults[dim]) * sfactor
  3565. except Exception as e:
  3566. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3567. continue
  3568. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3569. else:
  3570. # the number of decimals for the rest is kept unchanged
  3571. if self.defaults[dim]:
  3572. try:
  3573. val = float(self.defaults[dim]) * sfactor
  3574. except Exception as e:
  3575. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3576. continue
  3577. self.defaults[dim] = val
  3578. # The scaling factor depending on choice of units.
  3579. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3580. # Changing project units. Warn user.
  3581. msgbox = QtWidgets.QMessageBox()
  3582. msgbox.setWindowTitle(_("Toggle Units"))
  3583. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3584. msgbox.setText(_("Changing the units of the project\n"
  3585. "will scale all objects.\n\n"
  3586. "Do you want to continue?"))
  3587. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3588. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3589. msgbox.setDefaultButton(bt_ok)
  3590. msgbox.exec_()
  3591. response = msgbox.clickedButton()
  3592. if response == bt_ok:
  3593. if no_pref is False:
  3594. self.preferencesUiManager.defaults_read_form()
  3595. scale_defaults(factor)
  3596. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3597. self.defaults["units"] = new_units
  3598. # update the defaults from form, some may assume that the conversion is enough and it's not
  3599. self.on_options_app2project()
  3600. # update the objects
  3601. for obj in self.collection.get_list():
  3602. obj.convert_units(new_units)
  3603. # make that the properties stored in the object are also updated
  3604. self.object_changed.emit(obj)
  3605. # rebuild the object UI
  3606. obj.build_ui()
  3607. # change this only if the workspace is active
  3608. if self.defaults['global_workspace'] is True:
  3609. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3610. # adjust the grid values on the main toolbar
  3611. val_x = float(self.defaults['global_gridx']) * factor
  3612. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3613. current = self.collection.get_active()
  3614. if current is not None:
  3615. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3616. if not isinstance(current, GeometryObject):
  3617. current.to_form()
  3618. # replot all objects
  3619. self.plot_all()
  3620. # set the status labels to reflect the current FlatCAM units
  3621. self.set_screen_units(new_units)
  3622. # signal to the app that we changed the object properties and it should save the project
  3623. self.should_we_save = True
  3624. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3625. else:
  3626. # Undo toggling
  3627. self.toggle_units_ignore = True
  3628. if self.defaults['units'].upper() == 'MM':
  3629. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3630. else:
  3631. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3632. self.toggle_units_ignore = False
  3633. # store the grid values so they are not changed in the next step
  3634. val_x = float(self.defaults['global_gridx'])
  3635. val_y = float(self.defaults['global_gridy'])
  3636. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3637. self.preferencesUiManager.defaults_read_form()
  3638. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3639. # in self.defaults from the GUI elements but
  3640. # I don't want it for the grid values, so I update them here
  3641. self.defaults['global_gridx'] = val_x
  3642. self.defaults['global_gridy'] = val_y
  3643. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3644. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3645. def on_fullscreen(self, disable=False):
  3646. self.defaults.report_usage("on_fullscreen()")
  3647. flags = self.ui.windowFlags()
  3648. if self.toggle_fscreen is False and disable is False:
  3649. # self.ui.showFullScreen()
  3650. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3651. a = self.ui.geometry()
  3652. self.x_pos = a.x()
  3653. self.y_pos = a.y()
  3654. self.width = a.width()
  3655. self.height = a.height()
  3656. # set new geometry to full desktop rect
  3657. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3658. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3659. # everything else will not work without this hack. This happen in Windows.
  3660. # https://bugreports.qt.io/browse/QTBUG-41309
  3661. desktop = QtWidgets.QApplication.desktop()
  3662. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3663. rec = desktop.screenGeometry(screen)
  3664. x = rec.x() - 1
  3665. y = rec.y() - 1
  3666. h = rec.height() + 2
  3667. w = rec.width() + 2
  3668. self.ui.setGeometry(x, y, w, h)
  3669. self.ui.show()
  3670. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3671. tb.setVisible(False)
  3672. self.ui.splitter_left.setVisible(False)
  3673. self.toggle_fscreen = True
  3674. elif self.toggle_fscreen is True or disable is True:
  3675. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3676. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3677. self.ui.showNormal()
  3678. self.restore_toolbar_view()
  3679. self.ui.splitter_left.setVisible(True)
  3680. self.toggle_fscreen = False
  3681. def on_toggle_plotarea(self):
  3682. self.defaults.report_usage("on_toggle_plotarea()")
  3683. try:
  3684. name = self.ui.plot_tab_area.widget(0).objectName()
  3685. except AttributeError:
  3686. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3687. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3688. self.ui.plot_tab_area.protectTab(0)
  3689. return
  3690. if name != 'plotarea_tab':
  3691. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3692. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3693. self.ui.plot_tab_area.protectTab(0)
  3694. else:
  3695. self.ui.plot_tab_area.closeTab(0)
  3696. def on_toggle_notebook(self):
  3697. if self.ui.splitter.sizes()[0] == 0:
  3698. self.ui.splitter.setSizes([1, 1])
  3699. self.ui.menu_toggle_nb.setChecked(True)
  3700. else:
  3701. self.ui.splitter.setSizes([0, 1])
  3702. self.ui.menu_toggle_nb.setChecked(False)
  3703. def on_toggle_axis(self):
  3704. self.defaults.report_usage("on_toggle_axis()")
  3705. if self.toggle_axis is False:
  3706. if self.is_legacy is False:
  3707. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3708. parent=self.plotcanvas.view.scene)
  3709. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3710. parent=self.plotcanvas.view.scene)
  3711. else:
  3712. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3713. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3714. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3715. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3716. self.plotcanvas.canvas.draw()
  3717. self.toggle_axis = True
  3718. else:
  3719. if self.is_legacy is False:
  3720. self.plotcanvas.v_line.parent = None
  3721. self.plotcanvas.h_line.parent = None
  3722. else:
  3723. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3724. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3725. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3726. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3727. self.plotcanvas.canvas.draw()
  3728. self.toggle_axis = False
  3729. def on_toggle_grid(self):
  3730. self.defaults.report_usage("on_toggle_grid()")
  3731. self.ui.grid_snap_btn.trigger()
  3732. self.ui.on_grid_snap_triggered(state=True)
  3733. def on_toggle_grid_lines(self):
  3734. self.defaults.report_usage("on_toggle_grd_lines()")
  3735. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3736. if tt_settings.contains("theme"):
  3737. theme = tt_settings.value('theme', type=str)
  3738. else:
  3739. theme = 'white'
  3740. if self.toggle_grid_lines is False:
  3741. if self.is_legacy is False:
  3742. if theme == 'white':
  3743. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3744. else:
  3745. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3746. else:
  3747. self.plotcanvas.axes.grid(True)
  3748. try:
  3749. self.plotcanvas.canvas.draw()
  3750. except IndexError:
  3751. pass
  3752. pass
  3753. self.toggle_grid_lines = True
  3754. else:
  3755. if self.is_legacy is False:
  3756. if theme == 'white':
  3757. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3758. else:
  3759. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3760. else:
  3761. self.plotcanvas.axes.grid(False)
  3762. try:
  3763. self.plotcanvas.canvas.draw()
  3764. except IndexError:
  3765. pass
  3766. self.toggle_grid_lines = False
  3767. if self.is_legacy is False:
  3768. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3769. # - perhaps is a bug in VisPy implementation
  3770. if self.grid_status() is True:
  3771. self.app_cursor.enabled = False
  3772. self.app_cursor.enabled = True
  3773. else:
  3774. self.app_cursor.enabled = True
  3775. self.app_cursor.enabled = False
  3776. def on_update_exc_export(self, state):
  3777. """
  3778. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3779. if the update_excellon_cb checkbox is checked
  3780. :param state: state of the checkbox whose signals is tied to his slot
  3781. :return:
  3782. """
  3783. if state:
  3784. # first try to disconnect
  3785. try:
  3786. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3787. disconnect(self.on_excellon_format_changed)
  3788. except TypeError:
  3789. pass
  3790. try:
  3791. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3792. disconnect(self.on_excellon_format_changed)
  3793. except TypeError:
  3794. pass
  3795. try:
  3796. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3797. disconnect(self.on_excellon_format_changed)
  3798. except TypeError:
  3799. pass
  3800. try:
  3801. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3802. disconnect(self.on_excellon_format_changed)
  3803. except TypeError:
  3804. pass
  3805. try:
  3806. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3807. disconnect(self.on_excellon_zeros_changed)
  3808. except TypeError:
  3809. pass
  3810. try:
  3811. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3812. disconnect(self.on_excellon_zeros_changed)
  3813. except TypeError:
  3814. pass
  3815. # the connect them
  3816. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3817. self.on_excellon_format_changed)
  3818. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3819. self.on_excellon_format_changed)
  3820. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3821. self.on_excellon_format_changed)
  3822. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3823. self.on_excellon_format_changed)
  3824. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3825. self.on_excellon_zeros_changed)
  3826. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3827. self.on_excellon_units_changed)
  3828. else:
  3829. # disconnect the signals
  3830. try:
  3831. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3832. disconnect(self.on_excellon_format_changed)
  3833. except TypeError:
  3834. pass
  3835. try:
  3836. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3837. disconnect(self.on_excellon_format_changed)
  3838. except TypeError:
  3839. pass
  3840. try:
  3841. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3842. disconnect(self.on_excellon_format_changed)
  3843. except TypeError:
  3844. pass
  3845. try:
  3846. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3847. disconnect(self.on_excellon_format_changed)
  3848. except TypeError:
  3849. pass
  3850. try:
  3851. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3852. disconnect(self.on_excellon_zeros_changed)
  3853. except TypeError:
  3854. pass
  3855. try:
  3856. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3857. disconnect(self.on_excellon_zeros_changed)
  3858. except TypeError:
  3859. pass
  3860. def on_excellon_format_changed(self):
  3861. """
  3862. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3863. :return: None
  3864. """
  3865. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3866. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3867. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3868. )
  3869. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3870. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3871. )
  3872. else:
  3873. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3874. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3875. )
  3876. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3877. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3878. )
  3879. def on_excellon_zeros_changed(self):
  3880. """
  3881. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3882. :return: None
  3883. """
  3884. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3885. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3886. )
  3887. def on_excellon_units_changed(self):
  3888. """
  3889. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3890. :return: None
  3891. """
  3892. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3893. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3894. )
  3895. self.on_excellon_format_changed()
  3896. def on_film_color_entry(self):
  3897. self.defaults['tools_film_color'] = \
  3898. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3899. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3900. "background-color:%s;"
  3901. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3902. )
  3903. def on_film_color_button(self):
  3904. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3905. c_dialog = QtWidgets.QColorDialog()
  3906. film_color = c_dialog.getColor(initial=current_color)
  3907. if film_color.isValid() is False:
  3908. return
  3909. # if new color is different then mark that the Preferences are changed
  3910. if film_color != current_color:
  3911. self.preferencesUiManager.on_preferences_edited()
  3912. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3913. "background-color:%s;"
  3914. "border-color: dimgray" % str(film_color.name())
  3915. )
  3916. new_val_sel = str(film_color.name())
  3917. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3918. self.defaults['tools_film_color'] = new_val_sel
  3919. def on_qrcode_fill_color_entry(self):
  3920. self.defaults['tools_qrcode_fill_color'] = \
  3921. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3922. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3923. "background-color:%s;"
  3924. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3925. )
  3926. def on_qrcode_fill_color_button(self):
  3927. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3928. c_dialog = QtWidgets.QColorDialog()
  3929. fill_color = c_dialog.getColor(initial=current_color)
  3930. if fill_color.isValid() is False:
  3931. return
  3932. # if new color is different then mark that the Preferences are changed
  3933. if fill_color != current_color:
  3934. self.preferencesUiManager.on_preferences_edited()
  3935. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3936. "background-color:%s;"
  3937. "border-color: dimgray" % str(fill_color.name())
  3938. )
  3939. new_val_sel = str(fill_color.name())
  3940. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3941. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3942. def on_qrcode_back_color_entry(self):
  3943. self.defaults['tools_qrcode_back_color'] = \
  3944. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3945. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3946. "background-color:%s;"
  3947. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3948. )
  3949. def on_qrcode_back_color_button(self):
  3950. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3951. c_dialog = QtWidgets.QColorDialog()
  3952. back_color = c_dialog.getColor(initial=current_color)
  3953. if back_color.isValid() is False:
  3954. return
  3955. # if new color is different then mark that the Preferences are changed
  3956. if back_color != current_color:
  3957. self.preferencesUiManager.on_preferences_edited()
  3958. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3959. "background-color:%s;"
  3960. "border-color: dimgray" % str(back_color.name())
  3961. )
  3962. new_val_sel = str(back_color.name())
  3963. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3964. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3965. def on_tab_rmb_click(self, checked):
  3966. self.ui.notebook.set_detachable(val=checked)
  3967. self.defaults["global_tabs_detachable"] = checked
  3968. self.ui.plot_tab_area.set_detachable(val=checked)
  3969. self.defaults["global_tabs_detachable"] = checked
  3970. def on_tab_setup_context_menu(self):
  3971. initial_checked = self.defaults["global_tabs_detachable"]
  3972. action_name = str(_("Detachable Tabs"))
  3973. action = QtWidgets.QAction(self)
  3974. action.setCheckable(True)
  3975. action.setText(action_name)
  3976. action.setChecked(initial_checked)
  3977. self.ui.notebook.tabBar.addAction(action)
  3978. self.ui.plot_tab_area.tabBar.addAction(action)
  3979. try:
  3980. action.triggered.disconnect()
  3981. except TypeError:
  3982. pass
  3983. action.triggered.connect(self.on_tab_rmb_click)
  3984. def on_deselect_all(self):
  3985. self.collection.set_all_inactive()
  3986. self.delete_selection_shape()
  3987. def on_workspace_modified(self):
  3988. # self.save_defaults(silent=True)
  3989. if self.is_legacy is True:
  3990. self.plotcanvas.delete_workspace()
  3991. self.preferencesUiManager.defaults_read_form()
  3992. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3993. def on_workspace(self):
  3994. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3995. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3996. else:
  3997. self.plotcanvas.delete_workspace()
  3998. self.preferencesUiManager.defaults_read_form()
  3999. # self.save_defaults(silent=True)
  4000. def on_workspace_toggle(self):
  4001. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4002. try:
  4003. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4004. except TypeError:
  4005. pass
  4006. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4007. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4008. self.on_workspace()
  4009. def on_cursor_type(self, val):
  4010. """
  4011. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4012. :return: None
  4013. """
  4014. self.app_cursor.enabled = False
  4015. if val == 'small':
  4016. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4017. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4018. self.app_cursor = self.plotcanvas.new_cursor()
  4019. else:
  4020. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4021. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4022. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4023. if self.ui.grid_snap_btn.isChecked():
  4024. self.app_cursor.enabled = True
  4025. else:
  4026. self.app_cursor.enabled = False
  4027. def on_tool_add_keypress(self):
  4028. # ## Current application units in Upper Case
  4029. self.units = self.defaults['units'].upper()
  4030. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4031. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4032. if notebook_widget_name == 'selected_tab':
  4033. if self.collection.get_active().kind == 'geometry':
  4034. # Tool add works for Geometry only if Advanced is True in Preferences
  4035. if self.defaults["global_app_level"] == 'a':
  4036. tool_add_popup = FCInputDialog(title="New Tool ...",
  4037. text='Enter a Tool Diameter:',
  4038. min=0.0000, max=99.9999, decimals=4)
  4039. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4040. val, ok = tool_add_popup.get_value()
  4041. if ok:
  4042. if float(val) == 0:
  4043. self.inform.emit('[WARNING_NOTCL] %s' %
  4044. _("Please enter a tool diameter with non-zero value, in Float format."))
  4045. return
  4046. self.collection.get_active().on_tool_add(dia=float(val))
  4047. else:
  4048. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4049. else:
  4050. msgbox = QtWidgets.QMessageBox()
  4051. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4052. "Go to Preferences -> General - Show Advanced Options."))
  4053. msgbox.setWindowTitle("Tool adding ...")
  4054. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4055. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4056. msgbox.setDefaultButton(bt_ok)
  4057. msgbox.exec_()
  4058. # work only if the notebook tab on focus is the Tools_Tab
  4059. if notebook_widget_name == 'tool_tab':
  4060. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4061. # and only if the tool is NCC Tool
  4062. if tool_widget == self.ncclear_tool.toolName:
  4063. self.ncclear_tool.on_add_tool_by_key()
  4064. # and only if the tool is Paint Area Tool
  4065. elif tool_widget == self.paint_tool.toolName:
  4066. self.paint_tool.on_add_tool_by_key()
  4067. # and only if the tool is Solder Paste Dispensing Tool
  4068. elif tool_widget == self.paste_tool.toolName:
  4069. self.paste_tool.on_add_tool_by_key()
  4070. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4071. # See description below.
  4072. def on_delete_keypress(self):
  4073. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4074. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4075. if notebook_widget_name == 'selected_tab':
  4076. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4077. self.collection.get_active().on_tool_delete()
  4078. # work only if the notebook tab on focus is the Tools_Tab
  4079. elif notebook_widget_name == 'tool_tab':
  4080. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4081. # and only if the tool is NCC Tool
  4082. if tool_widget == self.ncclear_tool.toolName:
  4083. self.ncclear_tool.on_tool_delete()
  4084. # and only if the tool is Paint Tool
  4085. elif tool_widget == self.paint_tool.toolName:
  4086. self.paint_tool.on_tool_delete()
  4087. # and only if the tool is Solder Paste Dispensing Tool
  4088. elif tool_widget == self.paste_tool.toolName:
  4089. self.paste_tool.on_tool_delete()
  4090. else:
  4091. self.on_delete()
  4092. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4093. # some screens you have to be careful where you hover with your mouse.
  4094. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4095. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4096. # Complicated, I know :)
  4097. def on_delete(self, force_deletion=False):
  4098. """
  4099. Delete the currently selected FlatCAMObjs.
  4100. :param force_deletion: used by Tcl command
  4101. :return: None
  4102. """
  4103. self.defaults.report_usage("on_delete()")
  4104. response = None
  4105. bt_ok = None
  4106. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4107. # a geometry object before we update it.
  4108. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4109. and self.grb_editor.editor_active is False:
  4110. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4111. msgbox = QtWidgets.QMessageBox()
  4112. msgbox.setWindowTitle(_("Delete objects"))
  4113. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4114. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4115. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4116. "the selected objects?"))
  4117. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4118. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4119. msgbox.setDefaultButton(bt_ok)
  4120. msgbox.exec_()
  4121. response = msgbox.clickedButton()
  4122. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4123. response = bt_ok
  4124. if response == bt_ok:
  4125. if self.collection.get_active():
  4126. self.log.debug("App.on_delete()")
  4127. for obj_active in self.collection.get_selected():
  4128. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4129. if obj_active.kind == 'gerber':
  4130. for el in obj_active.mark_shapes:
  4131. obj_active.mark_shapes[el].clear(update=True)
  4132. obj_active.mark_shapes[el].enabled = False
  4133. # obj_active.mark_shapes[el] = None
  4134. del el
  4135. elif isinstance(obj_active, CNCJobObject):
  4136. try:
  4137. obj_active.text_col.enabled = False
  4138. del obj_active.text_col
  4139. obj_active.annotation.clear(update=True)
  4140. del obj_active.annotation
  4141. except AttributeError as e:
  4142. log.debug(
  4143. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4144. )
  4145. while self.collection.get_selected():
  4146. self.delete_first_selected()
  4147. self.inform.emit('%s...' % _("Object(s) deleted"))
  4148. # make sure that the selection shape is deleted, too
  4149. self.delete_selection_shape()
  4150. # if there are no longer objects delete also the exclusion areas shapes
  4151. if not self.collection.get_list():
  4152. self.exc_areas.clear_shapes()
  4153. else:
  4154. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4155. else:
  4156. self.inform.emit(_("Save the work in Editor and try again ..."))
  4157. def delete_first_selected(self):
  4158. # Keep this for later
  4159. try:
  4160. sel_obj = self.collection.get_active()
  4161. name = sel_obj.options["name"]
  4162. isPlotted = sel_obj.options["plot"]
  4163. except AttributeError:
  4164. self.log.debug("Nothing selected for deletion")
  4165. return
  4166. if self.is_legacy is True:
  4167. # Remove plot only if the object was plotted otherwise delaxes will fail
  4168. if isPlotted:
  4169. try:
  4170. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4171. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4172. except Exception as e:
  4173. log.debug("App.delete_first_selected() --> %s" % str(e))
  4174. self.plotcanvas.auto_adjust_axes()
  4175. # Remove from dictionary
  4176. self.collection.delete_active()
  4177. # Clear form
  4178. self.setup_component_editor()
  4179. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4180. def on_set_origin(self):
  4181. """
  4182. Set the origin to the left mouse click position
  4183. :return: None
  4184. """
  4185. # display the message for the user
  4186. # and ask him to click on the desired position
  4187. self.defaults.report_usage("on_set_origin()")
  4188. def origin_replot():
  4189. def worker_task():
  4190. with self.proc_container.new('%s...' % _("Plotting")):
  4191. for obj in self.collection.get_list():
  4192. obj.plot()
  4193. self.plotcanvas.fit_view()
  4194. if self.is_legacy:
  4195. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4196. else:
  4197. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4198. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4199. self.inform.emit(_('Click to set the origin ...'))
  4200. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4201. # first disconnect it as it may have been used by something else
  4202. try:
  4203. self.replot_signal.disconnect()
  4204. except TypeError:
  4205. pass
  4206. self.replot_signal[list].connect(origin_replot)
  4207. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4208. """
  4209. :param event:
  4210. :param location:
  4211. :param noplot:
  4212. :param use_thread:
  4213. :return:
  4214. """
  4215. noplot_sig = noplot
  4216. def worker_task():
  4217. with self.proc_container.new(_("Setting Origin...")):
  4218. obj_list = self.collection.get_list()
  4219. for obj in obj_list:
  4220. obj.offset((x, y))
  4221. self.object_changed.emit(obj)
  4222. # Update the object bounding box options
  4223. a, b, c, d = obj.bounds()
  4224. obj.options['xmin'] = a
  4225. obj.options['ymin'] = b
  4226. obj.options['xmax'] = c
  4227. obj.options['ymax'] = d
  4228. self.inform.emit('[success] %s...' % _('Origin set'))
  4229. for obj in obj_list:
  4230. out_name = obj.options["name"]
  4231. if obj.kind == 'gerber':
  4232. obj.source_file = self.export_gerber(
  4233. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4234. elif obj.kind == 'excellon':
  4235. obj.source_file = self.export_excellon(
  4236. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4237. if noplot_sig is False:
  4238. self.replot_signal.emit([])
  4239. if location is not None:
  4240. if len(location) != 2:
  4241. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4242. return 'fail'
  4243. x, y = location
  4244. if use_thread is True:
  4245. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4246. else:
  4247. worker_task()
  4248. self.should_we_save = True
  4249. return
  4250. if event.button == 1:
  4251. if self.is_legacy is False:
  4252. event_pos = event.pos
  4253. else:
  4254. event_pos = (event.xdata, event.ydata)
  4255. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4256. if self.grid_status():
  4257. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4258. else:
  4259. pos = pos_canvas
  4260. x = 0 - pos[0]
  4261. y = 0 - pos[1]
  4262. if use_thread is True:
  4263. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4264. else:
  4265. worker_task()
  4266. self.should_we_save = True
  4267. def on_move2origin(self, use_thread=True):
  4268. """
  4269. Move selected objects to origin.
  4270. :param use_thread: Control if to use threaded operation. Boolean.
  4271. :return:
  4272. """
  4273. def worker_task():
  4274. with self.proc_container.new(_("Moving to Origin...")):
  4275. obj_list = self.collection.get_selected()
  4276. if not obj_list:
  4277. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4278. return
  4279. xminlist = []
  4280. yminlist = []
  4281. # first get a bounding box to fit all
  4282. for obj in obj_list:
  4283. xmin, ymin, xmax, ymax = obj.bounds()
  4284. xminlist.append(xmin)
  4285. yminlist.append(ymin)
  4286. # get the minimum x,y for all objects selected
  4287. x = min(xminlist)
  4288. y = min(yminlist)
  4289. for obj in obj_list:
  4290. obj.offset((-x, -y))
  4291. self.object_changed.emit(obj)
  4292. # Update the object bounding box options
  4293. a, b, c, d = obj.bounds()
  4294. obj.options['xmin'] = a
  4295. obj.options['ymin'] = b
  4296. obj.options['xmax'] = c
  4297. obj.options['ymax'] = d
  4298. for obj in obj_list:
  4299. obj.plot()
  4300. for obj in obj_list:
  4301. out_name = obj.options["name"]
  4302. if obj.kind == 'gerber':
  4303. obj.source_file = self.export_gerber(
  4304. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4305. elif obj.kind == 'excellon':
  4306. obj.source_file = self.export_excellon(
  4307. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4308. self.inform.emit('[success] %s...' % _('Origin set'))
  4309. if use_thread is True:
  4310. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4311. else:
  4312. worker_task()
  4313. self.should_we_save = True
  4314. def on_jump_to(self, custom_location=None, fit_center=True):
  4315. """
  4316. Jump to a location by setting the mouse cursor location.
  4317. :param custom_location: Jump to a specified point. (x, y) tuple.
  4318. :param fit_center: If to fit view. Boolean.
  4319. :return:
  4320. """
  4321. self.defaults.report_usage("on_jump_to()")
  4322. if not custom_location:
  4323. dia_box_location = None
  4324. try:
  4325. dia_box_location = eval(self.clipboard.text())
  4326. except Exception:
  4327. pass
  4328. if type(dia_box_location) == tuple:
  4329. dia_box_location = str(dia_box_location)
  4330. else:
  4331. dia_box_location = None
  4332. # dia_box = Dialog_box(title=_("Jump to ..."),
  4333. # label=_("Enter the coordinates in format X,Y:"),
  4334. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4335. # initial_text=dia_box_location)
  4336. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4337. label=_("Enter the coordinates in format X,Y:"),
  4338. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4339. initial_text=dia_box_location,
  4340. reference=self.defaults['global_jump_ref'])
  4341. if dia_box.ok is True:
  4342. try:
  4343. location = eval(dia_box.location)
  4344. if not isinstance(location, tuple):
  4345. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4346. return
  4347. if dia_box.reference == 'rel':
  4348. rel_x = self.mouse[0] + location[0]
  4349. rel_y = self.mouse[1] + location[1]
  4350. location = (rel_x, rel_y)
  4351. self.defaults['global_jump_ref'] = dia_box.reference
  4352. except Exception:
  4353. return
  4354. else:
  4355. return
  4356. else:
  4357. location = custom_location
  4358. self.jump_signal.emit(location)
  4359. if fit_center:
  4360. self.plotcanvas.fit_center(loc=location)
  4361. cursor = QtGui.QCursor()
  4362. if self.is_legacy is False:
  4363. # I don't know where those differences come from but they are constant for the current
  4364. # execution of the application and they are multiples of a value around 0.0263mm.
  4365. # In a random way sometimes they are more sometimes they are less
  4366. # if units == 'MM':
  4367. # cal_factor = 0.0263
  4368. # else:
  4369. # cal_factor = 0.0263 / 25.4
  4370. cal_location = (location[0], location[1])
  4371. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4372. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4373. j_pos = (
  4374. int(canvas_origin.x() + round(jump_loc[0])),
  4375. int(canvas_origin.y() + round(jump_loc[1]))
  4376. )
  4377. cursor.setPos(j_pos[0], j_pos[1])
  4378. else:
  4379. # find the canvas origin which is in the top left corner
  4380. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4381. # determine the coordinates for the lowest left point of the canvas
  4382. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4383. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4384. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4385. # canvas) and the point (width, height) is in the top-right location
  4386. loc = self.plotcanvas.axes.transData.transform_point(location)
  4387. j_pos = (
  4388. int(x0 + loc[0]),
  4389. int(y0 - loc[1])
  4390. )
  4391. cursor.setPos(j_pos[0], j_pos[1])
  4392. self.plotcanvas.mouse = [location[0], location[1]]
  4393. if self.defaults["global_cursor_color_enabled"] is True:
  4394. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4395. else:
  4396. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4397. if self.grid_status():
  4398. # Update cursor
  4399. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4400. symbol='++', edge_color=self.cursor_color_3D,
  4401. edge_width=self.defaults["global_cursor_width"],
  4402. size=self.defaults["global_cursor_size"])
  4403. # Set the relative position label
  4404. dx = location[0] - float(self.rel_point1[0])
  4405. dy = location[1] - float(self.rel_point1[1])
  4406. # self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4407. # "<b>Y</b>: %.4f" % (location[0], location[1]))
  4408. # # Set the position label
  4409. #
  4410. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4411. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4412. units = self.defaults["units"].lower()
  4413. self.plotcanvas.text_hud.text = \
  4414. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4415. dx, units, dy, units, location[0], units, location[1], units)
  4416. self.inform.emit('[success] %s' % _("Done."))
  4417. return location
  4418. def on_locate(self, obj, fit_center=True):
  4419. """
  4420. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4421. :param obj: The object on which to locate certain points
  4422. :param fit_center: If to fit view. Boolean.
  4423. :return: A point location. (x, y) tuple.
  4424. """
  4425. self.defaults.report_usage("on_locate()")
  4426. if obj is None:
  4427. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4428. return 'fail'
  4429. class DialogBoxChoice(QtWidgets.QDialog):
  4430. def __init__(self, title=None, icon=None, choice='bl'):
  4431. """
  4432. :param title: string with the window title
  4433. """
  4434. super(DialogBoxChoice, self).__init__()
  4435. self.ok = False
  4436. self.setWindowIcon(icon)
  4437. self.setWindowTitle(str(title))
  4438. self.form = QtWidgets.QFormLayout(self)
  4439. self.ref_radio = RadioSet([
  4440. {"label": _("Bottom-Left"), "value": "bl"},
  4441. {"label": _("Top-Left"), "value": "tl"},
  4442. {"label": _("Bottom-Right"), "value": "br"},
  4443. {"label": _("Top-Right"), "value": "tr"},
  4444. {"label": _("Center"), "value": "c"}
  4445. ], orientation='vertical', stretch=False)
  4446. self.ref_radio.set_value(choice)
  4447. self.form.addRow(self.ref_radio)
  4448. self.button_box = QtWidgets.QDialogButtonBox(
  4449. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4450. Qt.Horizontal, parent=self)
  4451. self.form.addRow(self.button_box)
  4452. self.button_box.accepted.connect(self.accept)
  4453. self.button_box.rejected.connect(self.reject)
  4454. if self.exec_() == QtWidgets.QDialog.Accepted:
  4455. self.ok = True
  4456. self.location_point = self.ref_radio.get_value()
  4457. else:
  4458. self.ok = False
  4459. self.location_point = None
  4460. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4461. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4462. choice=self.defaults['global_locate_pt'])
  4463. if dia_box.ok is True:
  4464. try:
  4465. location_point = dia_box.location_point
  4466. self.defaults['global_locate_pt'] = dia_box.location_point
  4467. except Exception:
  4468. return
  4469. else:
  4470. return
  4471. loc_b = obj.bounds()
  4472. if location_point == 'bl':
  4473. location = (loc_b[0], loc_b[1])
  4474. elif location_point == 'tl':
  4475. location = (loc_b[0], loc_b[3])
  4476. elif location_point == 'br':
  4477. location = (loc_b[2], loc_b[1])
  4478. elif location_point == 'tr':
  4479. location = (loc_b[2], loc_b[3])
  4480. else:
  4481. # center
  4482. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4483. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4484. location = (cx, cy)
  4485. self.locate_signal.emit(location, location_point)
  4486. if fit_center:
  4487. self.plotcanvas.fit_center(loc=location)
  4488. cursor = QtGui.QCursor()
  4489. if self.is_legacy is False:
  4490. # I don't know where those differences come from but they are constant for the current
  4491. # execution of the application and they are multiples of a value around 0.0263mm.
  4492. # In a random way sometimes they are more sometimes they are less
  4493. # if units == 'MM':
  4494. # cal_factor = 0.0263
  4495. # else:
  4496. # cal_factor = 0.0263 / 25.4
  4497. cal_location = (location[0], location[1])
  4498. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4499. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4500. j_pos = (
  4501. int(canvas_origin.x() + round(jump_loc[0])),
  4502. int(canvas_origin.y() + round(jump_loc[1]))
  4503. )
  4504. cursor.setPos(j_pos[0], j_pos[1])
  4505. else:
  4506. # find the canvas origin which is in the top left corner
  4507. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4508. # determine the coordinates for the lowest left point of the canvas
  4509. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4510. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4511. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4512. # canvas) and the point (width, height) is in the top-right location
  4513. loc = self.plotcanvas.axes.transData.transform_point(location)
  4514. j_pos = (
  4515. int(x0 + loc[0]),
  4516. int(y0 - loc[1])
  4517. )
  4518. cursor.setPos(j_pos[0], j_pos[1])
  4519. self.plotcanvas.mouse = [location[0], location[1]]
  4520. if self.defaults["global_cursor_color_enabled"] is True:
  4521. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4522. else:
  4523. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4524. if self.grid_status():
  4525. # Update cursor
  4526. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4527. symbol='++', edge_color=self.cursor_color_3D,
  4528. edge_width=self.defaults["global_cursor_width"],
  4529. size=self.defaults["global_cursor_size"])
  4530. # Set the relative position label
  4531. self.dx = location[0] - float(self.rel_point1[0])
  4532. self.dy = location[1] - float(self.rel_point1[1])
  4533. # Set the position label
  4534. # self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4535. # "<b>Y</b>: %.4f" % (location[0], location[1]))
  4536. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4537. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4538. units = self.defaults["units"].lower()
  4539. self.plotcanvas.text_hud.text = \
  4540. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4541. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4542. self.inform.emit('[success] %s' % _("Done."))
  4543. return location
  4544. def on_copy_command(self):
  4545. """
  4546. Will copy a selection of objects, creating new objects.
  4547. :return:
  4548. """
  4549. self.defaults.report_usage("on_copy_command()")
  4550. def initialize(obj_init, app):
  4551. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4552. try:
  4553. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4554. except AttributeError:
  4555. pass
  4556. try:
  4557. obj_init.apertures = deepcopy(obj.apertures)
  4558. except AttributeError:
  4559. pass
  4560. try:
  4561. if obj.tools:
  4562. obj_init.tools = deepcopy(obj.tools)
  4563. except Exception as err:
  4564. log.debug("App.on_copy_command() --> %s" % str(err))
  4565. try:
  4566. obj_init.source_file = deepcopy(obj.source_file)
  4567. except (AttributeError, TypeError):
  4568. pass
  4569. def initialize_excellon(obj_init, app):
  4570. obj_init.source_file = deepcopy(obj.source_file)
  4571. obj_init.tools = deepcopy(obj.tools)
  4572. # drills are offset, so they need to be deep copied
  4573. obj_init.drills = deepcopy(obj.drills)
  4574. # slots are offset, so they need to be deep copied
  4575. obj_init.slots = deepcopy(obj.slots)
  4576. obj_init.create_geometry()
  4577. def initialize_script(obj_init, app_obj):
  4578. obj_init.source_file = deepcopy(obj.source_file)
  4579. def initialize_document(obj_init, app_obj):
  4580. obj_init.source_file = deepcopy(obj.source_file)
  4581. for obj in self.collection.get_selected():
  4582. obj_name = obj.options["name"]
  4583. try:
  4584. if isinstance(obj, ExcellonObject):
  4585. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4586. elif isinstance(obj, GerberObject):
  4587. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4588. elif isinstance(obj, GeometryObject):
  4589. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4590. elif isinstance(obj, ScriptObject):
  4591. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4592. elif isinstance(obj, DocumentObject):
  4593. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4594. except Exception as e:
  4595. return "Operation failed: %s" % str(e)
  4596. def on_copy_object2(self, custom_name):
  4597. def initialize_geometry(obj_init, app):
  4598. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4599. try:
  4600. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4601. except AttributeError:
  4602. pass
  4603. try:
  4604. obj_init.apertures = deepcopy(obj.apertures)
  4605. except AttributeError:
  4606. pass
  4607. try:
  4608. if obj.tools:
  4609. obj_init.tools = deepcopy(obj.tools)
  4610. except Exception as ee:
  4611. log.debug("on_copy_object2() --> %s" % str(ee))
  4612. def initialize_gerber(obj_init, app):
  4613. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4614. obj_init.apertures = deepcopy(obj.apertures)
  4615. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4616. def initialize_excellon(obj_init, app):
  4617. obj_init.tools = deepcopy(obj.tools)
  4618. # drills are offset, so they need to be deep copied
  4619. obj_init.drills = deepcopy(obj.drills)
  4620. # slots are offset, so they need to be deep copied
  4621. obj_init.slots = deepcopy(obj.slots)
  4622. obj_init.create_geometry()
  4623. for obj in self.collection.get_selected():
  4624. obj_name = obj.options["name"]
  4625. try:
  4626. if isinstance(obj, ExcellonObject):
  4627. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4628. elif isinstance(obj, GerberObject):
  4629. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4630. elif isinstance(obj, GeometryObject):
  4631. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4632. except Exception as er:
  4633. return "Operation failed: %s" % str(er)
  4634. def on_rename_object(self, text):
  4635. """
  4636. Will rename an object.
  4637. :param text: New name for the object.
  4638. :return:
  4639. """
  4640. self.defaults.report_usage("on_rename_object()")
  4641. named_obj = self.collection.get_active()
  4642. for obj in named_obj:
  4643. if obj is list:
  4644. self.on_rename_object(text)
  4645. else:
  4646. try:
  4647. obj.options['name'] = text
  4648. except Exception as e:
  4649. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4650. def convert_any2geo(self):
  4651. """
  4652. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4653. :return:
  4654. """
  4655. self.defaults.report_usage("convert_any2geo()")
  4656. def initialize(obj_init, app):
  4657. obj_init.solid_geometry = obj.solid_geometry
  4658. try:
  4659. obj_init.follow_geometry = obj.follow_geometry
  4660. except AttributeError:
  4661. pass
  4662. try:
  4663. obj_init.apertures = obj.apertures
  4664. except AttributeError:
  4665. pass
  4666. try:
  4667. if obj.tools:
  4668. obj_init.tools = obj.tools
  4669. except AttributeError:
  4670. pass
  4671. def initialize_excellon(obj_init, app):
  4672. # objs = self.collection.get_selected()
  4673. # GeometryObject.merge(objs, obj)
  4674. solid_geo = []
  4675. for tool in obj.tools:
  4676. for geo in obj.tools[tool]['solid_geometry']:
  4677. solid_geo.append(geo)
  4678. obj_init.solid_geometry = deepcopy(solid_geo)
  4679. if not self.collection.get_selected():
  4680. log.warning("App.convert_any2geo --> No object selected")
  4681. self.inform.emit('[WARNING_NOTCL] %s' %
  4682. _("No object is selected. Select an object and try again."))
  4683. return
  4684. for obj in self.collection.get_selected():
  4685. obj_name = obj.options["name"]
  4686. try:
  4687. if isinstance(obj, ExcellonObject):
  4688. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4689. else:
  4690. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4691. except Exception as e:
  4692. return "Operation failed: %s" % str(e)
  4693. def convert_any2gerber(self):
  4694. """
  4695. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4696. :return:
  4697. """
  4698. self.defaults.report_usage("convert_any2gerber()")
  4699. def initialize_geometry(obj_init, app):
  4700. apertures = {}
  4701. apid = 0
  4702. apertures[str(apid)] = {}
  4703. apertures[str(apid)]['geometry'] = []
  4704. for obj_orig in obj.solid_geometry:
  4705. new_elem = {}
  4706. new_elem['solid'] = obj_orig
  4707. try:
  4708. new_elem['follow'] = obj_orig.exterior
  4709. except AttributeError:
  4710. pass
  4711. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4712. apertures[str(apid)]['size'] = 0.0
  4713. apertures[str(apid)]['type'] = 'C'
  4714. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4715. obj_init.apertures = deepcopy(apertures)
  4716. def initialize_excellon(obj_init, app):
  4717. apertures = {}
  4718. apid = 10
  4719. for tool in obj.tools:
  4720. apertures[str(apid)] = {}
  4721. apertures[str(apid)]['geometry'] = []
  4722. for geo in obj.tools[tool]['solid_geometry']:
  4723. new_el = {}
  4724. new_el['solid'] = geo
  4725. new_el['follow'] = geo.exterior
  4726. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4727. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4728. apertures[str(apid)]['type'] = 'C'
  4729. apid += 1
  4730. # create solid_geometry
  4731. solid_geometry = []
  4732. for apid in apertures:
  4733. for geo_el in apertures[apid]['geometry']:
  4734. solid_geometry.append(geo_el['solid'])
  4735. solid_geometry = MultiPolygon(solid_geometry)
  4736. solid_geometry = solid_geometry.buffer(0.0000001)
  4737. obj_init.solid_geometry = deepcopy(solid_geometry)
  4738. obj_init.apertures = deepcopy(apertures)
  4739. # clear the working objects (perhaps not necessary due of Python GC)
  4740. apertures.clear()
  4741. if not self.collection.get_selected():
  4742. log.warning("App.convert_any2gerber --> No object selected")
  4743. self.inform.emit('[WARNING_NOTCL] %s' %
  4744. _("No object is selected. Select an object and try again."))
  4745. return
  4746. for obj in self.collection.get_selected():
  4747. obj_name = obj.options["name"]
  4748. try:
  4749. if isinstance(obj, ExcellonObject):
  4750. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4751. elif isinstance(obj, GeometryObject):
  4752. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4753. else:
  4754. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4755. except Exception as e:
  4756. return "Operation failed: %s" % str(e)
  4757. def abort_all_tasks(self):
  4758. """
  4759. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4760. on the first possible occasion.
  4761. :return:
  4762. """
  4763. if self.abort_flag is False:
  4764. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4765. self.abort_flag = True
  4766. self.cleanup.emit()
  4767. def app_is_idle(self):
  4768. if self.abort_flag:
  4769. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4770. self.abort_flag = False
  4771. def on_selectall(self):
  4772. """
  4773. Will draw a selection box shape around the selected objects.
  4774. :return:
  4775. """
  4776. self.defaults.report_usage("on_selectall()")
  4777. # delete the possible selection box around a possible selected object
  4778. self.delete_selection_shape()
  4779. for name in self.collection.get_names():
  4780. self.collection.set_active(name)
  4781. curr_sel_obj = self.collection.get_by_name(name)
  4782. # create the selection box around the selected object
  4783. if self.defaults['global_selection_shape'] is True:
  4784. self.draw_selection_shape(curr_sel_obj)
  4785. def on_preferences(self):
  4786. """
  4787. Adds the Preferences in a Tab in Plot Area
  4788. :return:
  4789. """
  4790. # add the tab if it was closed
  4791. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4792. # delete the absolute and relative position and messages in the infobar
  4793. # self.ui.position_label.setText("")
  4794. # self.ui.rel_position_label.setText("")
  4795. # Switch plot_area to preferences page
  4796. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4797. # self.ui.show()
  4798. # detect changes in the preferences
  4799. for idx in range(self.ui.pref_tab_area.count()):
  4800. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4801. try:
  4802. try:
  4803. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4804. except (TypeError, AttributeError):
  4805. pass
  4806. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4807. except AttributeError:
  4808. pass
  4809. try:
  4810. try:
  4811. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4812. except (TypeError, AttributeError):
  4813. pass
  4814. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4815. except AttributeError:
  4816. pass
  4817. try:
  4818. try:
  4819. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4820. except (TypeError, AttributeError):
  4821. pass
  4822. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4823. except AttributeError:
  4824. pass
  4825. try:
  4826. try:
  4827. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4828. except (TypeError, AttributeError):
  4829. pass
  4830. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4831. except AttributeError:
  4832. pass
  4833. try:
  4834. try:
  4835. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4836. except (TypeError, AttributeError):
  4837. pass
  4838. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4839. except AttributeError:
  4840. pass
  4841. def on_tools_database(self, source='app'):
  4842. """
  4843. Adds the Tools Database in a Tab in Plot Area.
  4844. :return:
  4845. """
  4846. for idx in range(self.ui.plot_tab_area.count()):
  4847. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4848. # there can be only one instance of Tools Database at one time
  4849. return
  4850. if source == 'app':
  4851. self.tools_db_tab = ToolsDB2(
  4852. app=self,
  4853. parent=self.ui,
  4854. callback_on_edited=self.on_tools_db_edited,
  4855. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4856. )
  4857. elif source == 'ncc':
  4858. self.tools_db_tab = ToolsDB2(
  4859. app=self,
  4860. parent=self.ui,
  4861. callback_on_edited=self.on_tools_db_edited,
  4862. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4863. )
  4864. elif source == 'paint':
  4865. self.tools_db_tab = ToolsDB2(
  4866. app=self,
  4867. parent=self.ui,
  4868. callback_on_edited=self.on_tools_db_edited,
  4869. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4870. )
  4871. # add the tab if it was closed
  4872. try:
  4873. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4874. self.tools_db_tab.setObjectName("database_tab")
  4875. except Exception as e:
  4876. log.debug("App.on_tools_database() --> %s" % str(e))
  4877. return
  4878. # delete the absolute and relative position and messages in the infobar
  4879. self.ui.position_label.setText("")
  4880. self.ui.rel_position_label.setText("")
  4881. # Switch plot_area to preferences page
  4882. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4883. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4884. self.tools_db_tab.ui_connect()
  4885. def on_tools_db_edited(self):
  4886. """
  4887. Executed whenever a tool is edited in Tools Database.
  4888. Will color the text of the Tools Database tab to Red color.
  4889. :return:
  4890. """
  4891. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4892. for idx in range(self.ui.plot_tab_area.count()):
  4893. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4894. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4895. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4896. self.tools_db_changed_flag = True
  4897. def on_geometry_tool_add_from_db_executed(self, tool):
  4898. """
  4899. Here add the tool from DB in the selected geometry object.
  4900. :return:
  4901. """
  4902. tool_from_db = deepcopy(tool)
  4903. obj = self.collection.get_active()
  4904. if isinstance(obj, GeometryObject):
  4905. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4906. # close the tab and delete it
  4907. for idx in range(self.ui.plot_tab_area.count()):
  4908. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4909. wdg = self.ui.plot_tab_area.widget(idx)
  4910. wdg.deleteLater()
  4911. self.ui.plot_tab_area.removeTab(idx)
  4912. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4913. else:
  4914. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4915. def on_plot_area_tab_closed(self, tab_obj_name):
  4916. """
  4917. Executed whenever a QTab is closed in the Plot Area.
  4918. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4919. :return:
  4920. """
  4921. if tab_obj_name == "preferences_tab":
  4922. self.preferencesUiManager.on_close_preferences_tab()
  4923. elif tab_obj_name == "database_tab":
  4924. # disconnect the signals from the table widget in tab
  4925. self.tools_db_tab.ui_disconnect()
  4926. if self.tools_db_changed_flag is True:
  4927. msgbox = QtWidgets.QMessageBox()
  4928. msgbox.setText(_("One or more Tools are edited.\n"
  4929. "Do you want to update the Tools Database?"))
  4930. msgbox.setWindowTitle(_("Save Tools Database"))
  4931. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4932. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4933. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4934. msgbox.setDefaultButton(bt_yes)
  4935. msgbox.exec_()
  4936. response = msgbox.clickedButton()
  4937. if response == bt_yes:
  4938. self.tools_db_tab.on_save_tools_db()
  4939. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4940. else:
  4941. self.tools_db_changed_flag = False
  4942. self.inform.emit('')
  4943. return
  4944. self.tools_db_tab.deleteLater()
  4945. elif tab_obj_name == "text_editor_tab":
  4946. self.toggle_codeeditor = False
  4947. elif tab_obj_name == "bookmarks_tab":
  4948. self.book_dialog_tab.rebuild_actions()
  4949. self.book_dialog_tab.deleteLater()
  4950. else:
  4951. return
  4952. # def on_plotarea_tab_closed(self, tab_idx):
  4953. # """
  4954. #
  4955. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4956. # :return:
  4957. # """
  4958. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4959. #
  4960. # if widget is not None:
  4961. # widget.deleteLater()
  4962. # self.ui.plot_tab_area.removeTab(tab_idx)
  4963. def on_flipy(self):
  4964. """
  4965. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4966. :return:
  4967. """
  4968. self.defaults.report_usage("on_flipy()")
  4969. obj_list = self.collection.get_selected()
  4970. xminlist = []
  4971. yminlist = []
  4972. xmaxlist = []
  4973. ymaxlist = []
  4974. if not obj_list:
  4975. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4976. else:
  4977. try:
  4978. # first get a bounding box to fit all
  4979. for obj in obj_list:
  4980. xmin, ymin, xmax, ymax = obj.bounds()
  4981. xminlist.append(xmin)
  4982. yminlist.append(ymin)
  4983. xmaxlist.append(xmax)
  4984. ymaxlist.append(ymax)
  4985. # get the minimum x,y and maximum x,y for all objects selected
  4986. xminimal = min(xminlist)
  4987. yminimal = min(yminlist)
  4988. xmaximal = max(xmaxlist)
  4989. ymaximal = max(ymaxlist)
  4990. px = 0.5 * (xminimal + xmaximal)
  4991. py = 0.5 * (yminimal + ymaximal)
  4992. # execute mirroring
  4993. for obj in obj_list:
  4994. obj.mirror('X', [px, py])
  4995. obj.plot()
  4996. self.object_changed.emit(obj)
  4997. self.inform.emit('[success] %s' %
  4998. _("Flip on Y axis done."))
  4999. except Exception as e:
  5000. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5001. return
  5002. def on_flipx(self):
  5003. """
  5004. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5005. :return:
  5006. """
  5007. self.defaults.report_usage("on_flipx()")
  5008. obj_list = self.collection.get_selected()
  5009. xminlist = []
  5010. yminlist = []
  5011. xmaxlist = []
  5012. ymaxlist = []
  5013. if not obj_list:
  5014. self.inform.emit('[WARNING_NOTCL] %s' %
  5015. _("No object selected to Flip on X axis."))
  5016. else:
  5017. try:
  5018. # first get a bounding box to fit all
  5019. for obj in obj_list:
  5020. xmin, ymin, xmax, ymax = obj.bounds()
  5021. xminlist.append(xmin)
  5022. yminlist.append(ymin)
  5023. xmaxlist.append(xmax)
  5024. ymaxlist.append(ymax)
  5025. # get the minimum x,y and maximum x,y for all objects selected
  5026. xminimal = min(xminlist)
  5027. yminimal = min(yminlist)
  5028. xmaximal = max(xmaxlist)
  5029. ymaximal = max(ymaxlist)
  5030. px = 0.5 * (xminimal + xmaximal)
  5031. py = 0.5 * (yminimal + ymaximal)
  5032. # execute mirroring
  5033. for obj in obj_list:
  5034. obj.mirror('Y', [px, py])
  5035. obj.plot()
  5036. self.object_changed.emit(obj)
  5037. self.inform.emit('[success] %s' %
  5038. _("Flip on X axis done."))
  5039. except Exception as e:
  5040. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5041. return
  5042. def on_rotate(self, silent=False, preset=None):
  5043. """
  5044. Executed when Options -> Rotate Selection menu entry is clicked.
  5045. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5046. :param preset: A value to be used as predefined angle for rotation.
  5047. :return:
  5048. """
  5049. self.defaults.report_usage("on_rotate()")
  5050. obj_list = self.collection.get_selected()
  5051. xminlist = []
  5052. yminlist = []
  5053. xmaxlist = []
  5054. ymaxlist = []
  5055. if not obj_list:
  5056. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5057. else:
  5058. if silent is False:
  5059. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5060. min=-360, max=360, decimals=4,
  5061. init_val=float(self.defaults['tools_transform_rotate']))
  5062. num, ok = rotatebox.get_value()
  5063. else:
  5064. num = preset
  5065. ok = True
  5066. if ok:
  5067. try:
  5068. # first get a bounding box to fit all
  5069. for obj in obj_list:
  5070. xmin, ymin, xmax, ymax = obj.bounds()
  5071. xminlist.append(xmin)
  5072. yminlist.append(ymin)
  5073. xmaxlist.append(xmax)
  5074. ymaxlist.append(ymax)
  5075. # get the minimum x,y and maximum x,y for all objects selected
  5076. xminimal = min(xminlist)
  5077. yminimal = min(yminlist)
  5078. xmaximal = max(xmaxlist)
  5079. ymaximal = max(ymaxlist)
  5080. px = 0.5 * (xminimal + xmaximal)
  5081. py = 0.5 * (yminimal + ymaximal)
  5082. for sel_obj in obj_list:
  5083. sel_obj.rotate(-float(num), point=(px, py))
  5084. sel_obj.plot()
  5085. self.object_changed.emit(sel_obj)
  5086. self.inform.emit('[success] %s' %
  5087. _("Rotation done."))
  5088. except Exception as e:
  5089. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5090. return
  5091. def on_skewx(self):
  5092. """
  5093. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5094. :return:
  5095. """
  5096. self.defaults.report_usage("on_skewx()")
  5097. obj_list = self.collection.get_selected()
  5098. xminlist = []
  5099. yminlist = []
  5100. if not obj_list:
  5101. self.inform.emit('[WARNING_NOTCL] %s' %
  5102. _("No object selected to Skew/Shear on X axis."))
  5103. else:
  5104. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5105. min=-360, max=360, decimals=4,
  5106. init_val=float(self.defaults['tools_transform_skew_x']))
  5107. num, ok = skewxbox.get_value()
  5108. if ok:
  5109. # first get a bounding box to fit all
  5110. for obj in obj_list:
  5111. xmin, ymin, xmax, ymax = obj.bounds()
  5112. xminlist.append(xmin)
  5113. yminlist.append(ymin)
  5114. # get the minimum x,y and maximum x,y for all objects selected
  5115. xminimal = min(xminlist)
  5116. yminimal = min(yminlist)
  5117. for obj in obj_list:
  5118. obj.skew(num, 0, point=(xminimal, yminimal))
  5119. obj.plot()
  5120. self.object_changed.emit(obj)
  5121. self.inform.emit('[success] %s' %
  5122. _("Skew on X axis done."))
  5123. def on_skewy(self):
  5124. """
  5125. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5126. :return:
  5127. """
  5128. self.defaults.report_usage("on_skewy()")
  5129. obj_list = self.collection.get_selected()
  5130. xminlist = []
  5131. yminlist = []
  5132. if not obj_list:
  5133. self.inform.emit('[WARNING_NOTCL] %s' %
  5134. _("No object selected to Skew/Shear on Y axis."))
  5135. else:
  5136. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5137. min=-360, max=360, decimals=4,
  5138. init_val=float(self.defaults['tools_transform_skew_y']))
  5139. num, ok = skewybox.get_value()
  5140. if ok:
  5141. # first get a bounding box to fit all
  5142. for obj in obj_list:
  5143. xmin, ymin, xmax, ymax = obj.bounds()
  5144. xminlist.append(xmin)
  5145. yminlist.append(ymin)
  5146. # get the minimum x,y and maximum x,y for all objects selected
  5147. xminimal = min(xminlist)
  5148. yminimal = min(yminlist)
  5149. for obj in obj_list:
  5150. obj.skew(0, num, point=(xminimal, yminimal))
  5151. obj.plot()
  5152. self.object_changed.emit(obj)
  5153. self.inform.emit('[success] %s' %
  5154. _("Skew on Y axis done."))
  5155. def on_plots_updated(self):
  5156. """
  5157. Callback used to report when the plots have changed.
  5158. Adjust axes and zooms to fit.
  5159. :return: None
  5160. """
  5161. if self.is_legacy is False:
  5162. self.plotcanvas.update()
  5163. else:
  5164. self.plotcanvas.auto_adjust_axes()
  5165. self.on_zoom_fit(None)
  5166. self.collection.update_view()
  5167. # self.inform.emit(_("Plots updated ..."))
  5168. def on_toolbar_replot(self):
  5169. """
  5170. Callback for toolbar button. Re-plots all objects.
  5171. :return: None
  5172. """
  5173. self.defaults.report_usage("on_toolbar_replot")
  5174. self.log.debug("on_toolbar_replot()")
  5175. try:
  5176. self.collection.get_active().read_form()
  5177. except AttributeError:
  5178. self.log.debug("on_toolbar_replot(): AttributeError")
  5179. pass
  5180. self.plot_all()
  5181. def on_row_activated(self, index):
  5182. if index.isValid():
  5183. if index.internalPointer().parent_item != self.collection.root_item:
  5184. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5185. self.collection.on_item_activated(index)
  5186. def on_row_selected(self, obj_name):
  5187. """
  5188. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5189. It mean we clicked outside of the items and deselected all
  5190. :param obj_name:
  5191. :return:
  5192. """
  5193. if obj_name == 'none':
  5194. for act in self.ui.menuobjects.actions():
  5195. act.setChecked(False)
  5196. return
  5197. # get the name of the selected objects and add them to a list
  5198. name_list = []
  5199. for obj in self.collection.get_selected():
  5200. name_list.append(obj.options['name'])
  5201. # set all actions as unchecked but the ones selected make them checked
  5202. for act in self.ui.menuobjects.actions():
  5203. act.setChecked(False)
  5204. if act.text() in name_list:
  5205. act.setChecked(True)
  5206. def on_collection_updated(self, obj, state, old_name):
  5207. """
  5208. Create a menu from the object loaded in the collection.
  5209. :param obj: object that was changed (added, deleted, renamed)
  5210. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5211. :param old_name: the old name of the object before the action that triggered this slot happened
  5212. :return: None
  5213. """
  5214. icon_files = {
  5215. "gerber": self.resource_location + "/flatcam_icon16.png",
  5216. "excellon": self.resource_location + "/drill16.png",
  5217. "cncjob": self.resource_location + "/cnc16.png",
  5218. "geometry": self.resource_location + "/geometry16.png",
  5219. "script": self.resource_location + "/script_new16.png",
  5220. "document": self.resource_location + "/notes16_1.png"
  5221. }
  5222. if state == 'append':
  5223. for act in self.ui.menuobjects.actions():
  5224. try:
  5225. act.triggered.disconnect()
  5226. except TypeError:
  5227. pass
  5228. self.ui.menuobjects.clear()
  5229. gerber_list = []
  5230. exc_list = []
  5231. cncjob_list = []
  5232. geo_list = []
  5233. script_list = []
  5234. doc_list = []
  5235. for name in self.collection.get_names():
  5236. obj_named = self.collection.get_by_name(name)
  5237. if obj_named.kind == 'gerber':
  5238. gerber_list.append(name)
  5239. elif obj_named.kind == 'excellon':
  5240. exc_list.append(name)
  5241. elif obj_named.kind == 'cncjob':
  5242. cncjob_list.append(name)
  5243. elif obj_named.kind == 'geometry':
  5244. geo_list.append(name)
  5245. elif obj_named.kind == 'script':
  5246. script_list.append(name)
  5247. elif obj_named.kind == 'document':
  5248. doc_list.append(name)
  5249. def add_act(o_name):
  5250. obj_for_icon = self.collection.get_by_name(o_name)
  5251. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5252. add_action.setCheckable(True)
  5253. add_action.setText(o_name)
  5254. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5255. add_action.triggered.connect(
  5256. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5257. self.collection.set_inactive(o_name))
  5258. self.ui.menuobjects.addAction(add_action)
  5259. for name in gerber_list:
  5260. add_act(name)
  5261. self.ui.menuobjects.addSeparator()
  5262. for name in exc_list:
  5263. add_act(name)
  5264. self.ui.menuobjects.addSeparator()
  5265. for name in cncjob_list:
  5266. add_act(name)
  5267. self.ui.menuobjects.addSeparator()
  5268. for name in geo_list:
  5269. add_act(name)
  5270. self.ui.menuobjects.addSeparator()
  5271. for name in script_list:
  5272. add_act(name)
  5273. self.ui.menuobjects.addSeparator()
  5274. for name in doc_list:
  5275. add_act(name)
  5276. self.ui.menuobjects.addSeparator()
  5277. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5278. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5279. _('Select All')
  5280. )
  5281. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5282. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5283. _('Deselect All')
  5284. )
  5285. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5286. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5287. elif state == 'delete':
  5288. for act in self.ui.menuobjects.actions():
  5289. if act.text() == obj.options['name']:
  5290. try:
  5291. act.triggered.disconnect()
  5292. except TypeError:
  5293. pass
  5294. self.ui.menuobjects.removeAction(act)
  5295. break
  5296. elif state == 'rename':
  5297. for act in self.ui.menuobjects.actions():
  5298. if act.text() == old_name:
  5299. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5300. add_action.setText(obj.options['name'])
  5301. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5302. add_action.triggered.connect(
  5303. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5304. self.collection.set_inactive(obj.options['name']))
  5305. self.ui.menuobjects.insertAction(act, add_action)
  5306. try:
  5307. act.triggered.disconnect()
  5308. except TypeError:
  5309. pass
  5310. self.ui.menuobjects.removeAction(act)
  5311. break
  5312. elif state == 'delete_all':
  5313. for act in self.ui.menuobjects.actions():
  5314. try:
  5315. act.triggered.disconnect()
  5316. except TypeError:
  5317. pass
  5318. self.ui.menuobjects.clear()
  5319. self.ui.menuobjects.addSeparator()
  5320. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5321. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5322. _('Select All')
  5323. )
  5324. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5325. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5326. _('Deselect All')
  5327. )
  5328. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5329. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5330. def on_objects_selection(self, on_off):
  5331. obj_list = self.collection.get_names()
  5332. if on_off is True:
  5333. self.collection.set_all_active()
  5334. for act in self.ui.menuobjects.actions():
  5335. try:
  5336. act.setChecked(True)
  5337. except Exception:
  5338. pass
  5339. if obj_list:
  5340. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5341. else:
  5342. self.collection.set_all_inactive()
  5343. for act in self.ui.menuobjects.actions():
  5344. try:
  5345. act.setChecked(False)
  5346. except Exception:
  5347. pass
  5348. if obj_list:
  5349. self.inform.emit('%s' % _("Objects selection is cleared."))
  5350. else:
  5351. self.inform.emit('')
  5352. def grid_status(self):
  5353. if self.ui.grid_snap_btn.isChecked():
  5354. return True
  5355. else:
  5356. return False
  5357. def populate_cmenu_grids(self):
  5358. units = self.defaults['units'].lower()
  5359. # for act in self.ui.cmenu_gridmenu.actions():
  5360. # act.triggered.disconnect()
  5361. self.ui.cmenu_gridmenu.clear()
  5362. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5363. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5364. _("Grid On/Off"))
  5365. grid_toggle.setCheckable(True)
  5366. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5367. self.ui.cmenu_gridmenu.addSeparator()
  5368. for grid in sorted_list:
  5369. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5370. "%s" % str(grid))
  5371. action.triggered.connect(self.set_grid)
  5372. self.ui.cmenu_gridmenu.addSeparator()
  5373. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5374. _("Add"))
  5375. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5376. _("Delete"))
  5377. grid_add.triggered.connect(self.on_grid_add)
  5378. grid_delete.triggered.connect(self.on_grid_delete)
  5379. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5380. def set_grid(self):
  5381. menu_action = self.sender()
  5382. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5383. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5384. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5385. def on_grid_add(self):
  5386. # ## Current application units in lower Case
  5387. units = self.defaults['units'].lower()
  5388. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5389. text=_('Enter a Grid Value:'),
  5390. min=0.0000, max=99.9999, decimals=4)
  5391. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5392. val, ok = grid_add_popup.get_value()
  5393. if ok:
  5394. if float(val) == 0:
  5395. self.inform.emit('[WARNING_NOTCL] %s' %
  5396. _("Please enter a grid value with non-zero value, in Float format."))
  5397. return
  5398. else:
  5399. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5400. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5401. self.inform.emit('[success] %s...' %
  5402. _("New Grid added"))
  5403. else:
  5404. self.inform.emit('[WARNING_NOTCL] %s...' %
  5405. _("Grid already exists"))
  5406. else:
  5407. self.inform.emit('[WARNING_NOTCL] %s...' %
  5408. _("Adding New Grid cancelled"))
  5409. def on_grid_delete(self):
  5410. # ## Current application units in lower Case
  5411. units = self.defaults['units'].lower()
  5412. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5413. text='Enter a Grid Value:',
  5414. min=0.0000, max=99.9999, decimals=4)
  5415. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5416. val, ok = grid_del_popup.get_value()
  5417. if ok:
  5418. if float(val) == 0:
  5419. self.inform.emit('[WARNING_NOTCL] %s' %
  5420. _("Please enter a grid value with non-zero value, in Float format."))
  5421. return
  5422. else:
  5423. try:
  5424. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5425. except ValueError:
  5426. self.inform.emit('[ERROR_NOTCL]%s...' %
  5427. _(" Grid Value does not exist"))
  5428. return
  5429. self.inform.emit('[success] %s...' %
  5430. _("Grid Value deleted"))
  5431. else:
  5432. self.inform.emit('[WARNING_NOTCL] %s...' %
  5433. _("Delete Grid value cancelled"))
  5434. def on_shortcut_list(self):
  5435. self.defaults.report_usage("on_shortcut_list()")
  5436. # add the tab if it was closed
  5437. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5438. # delete the absolute and relative position and messages in the infobar
  5439. self.ui.position_label.setText("")
  5440. self.ui.rel_position_label.setText("")
  5441. # Switch plot_area to preferences page
  5442. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5443. # self.ui.show()
  5444. def on_select_tab(self, name):
  5445. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5446. if self.ui.splitter.sizes()[0] == 0:
  5447. self.ui.splitter.setSizes([1, 1])
  5448. else:
  5449. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5450. self.ui.splitter.setSizes([0, 1])
  5451. if name == 'project':
  5452. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5453. elif name == 'selected':
  5454. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5455. elif name == 'tool':
  5456. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5457. def on_copy_name(self):
  5458. self.defaults.report_usage("on_copy_name()")
  5459. obj = self.collection.get_active()
  5460. try:
  5461. name = obj.options["name"]
  5462. except AttributeError:
  5463. log.debug("on_copy_name() --> No object selected to copy it's name")
  5464. self.inform.emit('[WARNING_NOTCL]%s' %
  5465. _(" No object selected to copy it's name"))
  5466. return
  5467. self.clipboard.setText(name)
  5468. self.inform.emit(_("Name copied on clipboard ..."))
  5469. def on_mouse_click_over_plot(self, event):
  5470. """
  5471. Default actions are:
  5472. :param event: Contains information about the event, like which button
  5473. was clicked, the pixel coordinates and the axes coordinates.
  5474. :return: None
  5475. """
  5476. self.pos = []
  5477. if self.is_legacy is False:
  5478. event_pos = event.pos
  5479. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5480. # # Set the mouse button for panning
  5481. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5482. else:
  5483. event_pos = (event.xdata, event.ydata)
  5484. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5485. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5486. # So it can receive key presses
  5487. self.plotcanvas.native.setFocus()
  5488. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5489. if self.grid_status():
  5490. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5491. else:
  5492. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5493. try:
  5494. if event.button == 1:
  5495. # Reset here the relative coordinates so there is a new reference on the click position
  5496. if self.rel_point1 is None:
  5497. self.rel_point1 = self.pos
  5498. else:
  5499. self.rel_point2 = copy(self.rel_point1)
  5500. self.rel_point1 = self.pos
  5501. self.on_mouse_move_over_plot(event, origin_click=True)
  5502. except Exception as e:
  5503. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5504. def on_mouse_double_click_over_plot(self, event):
  5505. if event.button == 1:
  5506. self.doubleclick = True
  5507. def on_mouse_move_over_plot(self, event, origin_click=None):
  5508. """
  5509. Callback for the mouse motion event over the plot.
  5510. :param event: Contains information about the event.
  5511. :param origin_click
  5512. :return: None
  5513. """
  5514. if self.is_legacy is False:
  5515. event_pos = event.pos
  5516. if self.defaults["global_pan_button"] == '2':
  5517. pan_button = 2
  5518. else:
  5519. pan_button = 3
  5520. self.event_is_dragging = event.is_dragging
  5521. else:
  5522. event_pos = (event.xdata, event.ydata)
  5523. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5524. if self.defaults["global_pan_button"] == '2':
  5525. pan_button = 3
  5526. else:
  5527. pan_button = 2
  5528. self.event_is_dragging = self.plotcanvas.is_dragging
  5529. # So it can receive key presses but not when the Tcl Shell is active
  5530. if not self.ui.shell_dock.isVisible():
  5531. if not self.plotcanvas.native.hasFocus():
  5532. self.plotcanvas.native.setFocus()
  5533. self.pos_jump = event_pos
  5534. self.ui.popMenu.mouse_is_panning = False
  5535. if origin_click is None:
  5536. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5537. if event.button == pan_button and self.event_is_dragging == 1:
  5538. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5539. if self.ui.popMenu.popup_active:
  5540. self.ui.popMenu.popup_active = False
  5541. return
  5542. self.ui.popMenu.mouse_is_panning = True
  5543. return
  5544. if self.rel_point1 is not None:
  5545. try: # May fail in case mouse not within axes
  5546. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5547. if pos_canvas[0] is None or pos_canvas[1] is None:
  5548. return
  5549. if self.grid_status():
  5550. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5551. # Update cursor
  5552. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5553. symbol='++', edge_color=self.cursor_color_3D,
  5554. edge_width=self.defaults["global_cursor_width"],
  5555. size=self.defaults["global_cursor_size"])
  5556. else:
  5557. pos = (pos_canvas[0], pos_canvas[1])
  5558. self.dx = pos[0] - float(self.rel_point1[0])
  5559. self.dy = pos[1] - float(self.rel_point1[1])
  5560. # self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5561. # "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5562. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5563. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5564. units = self.defaults["units"].lower()
  5565. self.plotcanvas.text_hud.text = \
  5566. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5567. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5568. self.mouse = [pos[0], pos[1]]
  5569. # if the mouse is moved and the LMB is clicked then the action is a selection
  5570. if self.event_is_dragging == 1 and event.button == 1:
  5571. self.delete_selection_shape()
  5572. if self.dx < 0:
  5573. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5574. face_color=self.defaults['global_alt_sel_fill'])
  5575. self.selection_type = False
  5576. elif self.dx >= 0:
  5577. self.draw_moving_selection_shape(self.pos, pos)
  5578. self.selection_type = True
  5579. else:
  5580. self.selection_type = None
  5581. else:
  5582. self.selection_type = None
  5583. # hover effect - enabled in Preferences -> General -> GUI Settings
  5584. if self.defaults['global_hover']:
  5585. for obj in self.collection.get_list():
  5586. try:
  5587. # select the object(s) only if it is enabled (plotted)
  5588. if obj.options['plot']:
  5589. if obj not in self.collection.get_selected():
  5590. poly_obj = Polygon(
  5591. [(obj.options['xmin'], obj.options['ymin']),
  5592. (obj.options['xmax'], obj.options['ymin']),
  5593. (obj.options['xmax'], obj.options['ymax']),
  5594. (obj.options['xmin'], obj.options['ymax'])]
  5595. )
  5596. if Point(pos).within(poly_obj):
  5597. if obj.isHovering is False:
  5598. obj.isHovering = True
  5599. obj.notHovering = True
  5600. # create the selection box around the selected object
  5601. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5602. else:
  5603. if obj.notHovering is True:
  5604. obj.notHovering = False
  5605. obj.isHovering = False
  5606. self.delete_hover_shape()
  5607. except Exception:
  5608. # the Exception here will happen if we try to select on screen and we have an
  5609. # newly (and empty) just created Geometry or Excellon object that do not have the
  5610. # xmin, xmax, ymin, ymax options.
  5611. # In this case poly_obj creation (see above) will fail
  5612. pass
  5613. except Exception as e:
  5614. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5615. # self.ui.position_label.setText("")
  5616. # self.ui.rel_position_label.setText("")
  5617. self.mouse = None
  5618. def on_mouse_click_release_over_plot(self, event):
  5619. """
  5620. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5621. and has been registered in ''self.__init__()''.
  5622. :param event: contains information about the event.
  5623. :return:
  5624. """
  5625. if self.is_legacy is False:
  5626. event_pos = event.pos
  5627. right_button = 2
  5628. else:
  5629. event_pos = (event.xdata, event.ydata)
  5630. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5631. right_button = 3
  5632. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5633. if self.grid_status():
  5634. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5635. else:
  5636. pos = (pos_canvas[0], pos_canvas[1])
  5637. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5638. # canvas menu
  5639. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5640. self.ui.popMenu.mouse_is_panning = False
  5641. self.cursor = QtGui.QCursor()
  5642. self.populate_cmenu_grids()
  5643. self.ui.popMenu.popup(self.cursor.pos())
  5644. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5645. # selection and then select a type of selection ("enclosing" or "touching")
  5646. if event.button == 1: # left click
  5647. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5648. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5649. if modifiers == QtCore.Qt.ShiftModifier:
  5650. # do not auto open the Project Tab
  5651. self.click_noproject = True
  5652. self.clipboard.setText(
  5653. self.defaults["global_point_clipboard_format"] %
  5654. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5655. )
  5656. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5657. return
  5658. if self.doubleclick is True:
  5659. self.doubleclick = False
  5660. if self.collection.get_selected():
  5661. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5662. if self.ui.splitter.sizes()[0] == 0:
  5663. self.ui.splitter.setSizes([1, 1])
  5664. try:
  5665. # delete the selection shape(S) as it may be in the way
  5666. self.delete_selection_shape()
  5667. self.delete_hover_shape()
  5668. except Exception as e:
  5669. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5670. return
  5671. else:
  5672. # WORKAROUND for LEGACY MODE
  5673. if self.is_legacy is True:
  5674. # if there is no move on canvas then we have no dragging selection
  5675. if self.dx == 0 or self.dy == 0:
  5676. self.selection_type = None
  5677. if self.selection_type is not None:
  5678. try:
  5679. self.selection_area_handler(self.pos, pos, self.selection_type)
  5680. self.selection_type = None
  5681. except Exception as e:
  5682. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5683. return
  5684. else:
  5685. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5686. if key_modifier == QtCore.Qt.ShiftModifier:
  5687. mod_key = 'Shift'
  5688. elif key_modifier == QtCore.Qt.ControlModifier:
  5689. mod_key = 'Control'
  5690. else:
  5691. mod_key = None
  5692. try:
  5693. if self.command_active is None:
  5694. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5695. # deselect, and if it's not selected then it will be selected
  5696. # If there is no active command (self.command_active is None) then we check if we clicked
  5697. # on a object by checking the bounding limits against mouse click position
  5698. if mod_key == self.defaults["global_mselect_key"]:
  5699. self.select_objects(key='multisel')
  5700. else:
  5701. # If there is no active command (self.command_active is None) then we check if
  5702. # we clicked on a object by checking the bounding limits against mouse click position
  5703. self.select_objects()
  5704. self.delete_hover_shape()
  5705. except Exception as e:
  5706. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5707. return
  5708. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5709. """
  5710. :param start_pos: mouse position when the selection LMB click was done
  5711. :param end_pos: mouse position when the left mouse button is released
  5712. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5713. :return:
  5714. """
  5715. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5716. # delete previous selection shape
  5717. self.delete_selection_shape()
  5718. # make all objects inactive
  5719. self.collection.set_all_inactive()
  5720. for obj in self.collection.get_list():
  5721. try:
  5722. # select the object(s) only if it is enabled (plotted)
  5723. if obj.options['plot']:
  5724. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5725. (obj.options['xmax'], obj.options['ymin']),
  5726. (obj.options['xmax'], obj.options['ymax']),
  5727. (obj.options['xmin'], obj.options['ymax'])])
  5728. if sel_type is True:
  5729. if poly_obj.within(poly_selection):
  5730. # create the selection box around the selected object
  5731. if self.defaults['global_selection_shape'] is True:
  5732. self.draw_selection_shape(obj)
  5733. self.collection.set_active(obj.options['name'])
  5734. else:
  5735. if poly_selection.intersects(poly_obj):
  5736. # create the selection box around the selected object
  5737. if self.defaults['global_selection_shape'] is True:
  5738. self.draw_selection_shape(obj)
  5739. self.collection.set_active(obj.options['name'])
  5740. obj.selection_shape_drawn = True
  5741. except Exception as e:
  5742. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5743. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5744. # In this case poly_obj creation (see above) will fail
  5745. log.debug("App.selection_area_handler() --> %s" % str(e))
  5746. def select_objects(self, key=None):
  5747. """
  5748. Will select objects clicked on canvas
  5749. :param key: for future use in cumulative selection
  5750. :return:
  5751. """
  5752. # list where we store the overlapped objects under our mouse left click position
  5753. if key is None:
  5754. self.objects_under_the_click_list = []
  5755. # Populate the list with the overlapped objects on the click position
  5756. curr_x, curr_y = self.pos
  5757. for obj in self.all_objects_list:
  5758. # ScriptObject and DocumentObject objects can't be selected
  5759. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5760. continue
  5761. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5762. continue
  5763. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5764. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5765. if obj.options['name'] not in self.objects_under_the_click_list:
  5766. if obj.options['plot']:
  5767. # add objects to the objects_under_the_click list only if the object is plotted
  5768. # (active and not disabled)
  5769. self.objects_under_the_click_list.append(obj.options['name'])
  5770. try:
  5771. if self.objects_under_the_click_list:
  5772. curr_sel_obj = self.collection.get_active()
  5773. # case when there is only an object under the click and we toggle it
  5774. if len(self.objects_under_the_click_list) == 1:
  5775. if curr_sel_obj is None:
  5776. self.collection.set_active(self.objects_under_the_click_list[0])
  5777. curr_sel_obj = self.collection.get_active()
  5778. # create the selection box around the selected object
  5779. if self.defaults['global_selection_shape'] is True:
  5780. self.draw_selection_shape(curr_sel_obj)
  5781. curr_sel_obj.selection_shape_drawn = True
  5782. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5783. self.on_objects_selection(False)
  5784. self.delete_selection_shape()
  5785. curr_sel_obj.selection_shape_drawn = False
  5786. self.collection.set_active(self.objects_under_the_click_list[0])
  5787. curr_sel_obj = self.collection.get_active()
  5788. # create the selection box around the selected object
  5789. if self.defaults['global_selection_shape'] is True:
  5790. self.draw_selection_shape(curr_sel_obj)
  5791. curr_sel_obj.selection_shape_drawn = True
  5792. self.selected_message(curr_sel_obj=curr_sel_obj)
  5793. elif curr_sel_obj.selection_shape_drawn is False:
  5794. if self.defaults['global_selection_shape'] is True:
  5795. self.draw_selection_shape(curr_sel_obj)
  5796. curr_sel_obj.selection_shape_drawn = True
  5797. else:
  5798. self.on_objects_selection(False)
  5799. self.delete_selection_shape()
  5800. if self.call_source != 'app':
  5801. self.call_source = 'app'
  5802. self.selected_message(curr_sel_obj=curr_sel_obj)
  5803. else:
  5804. # If there is no selected object
  5805. # make active the first element of the overlapped objects list
  5806. if self.collection.get_active() is None:
  5807. self.collection.set_active(self.objects_under_the_click_list[0])
  5808. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5809. name_sel_obj = self.collection.get_active().options['name']
  5810. # In case that there is a selected object but it is not in the overlapped object list
  5811. # make that object inactive and activate the first element in the overlapped object list
  5812. if name_sel_obj not in self.objects_under_the_click_list:
  5813. self.collection.set_inactive(name_sel_obj)
  5814. name_sel_obj = self.objects_under_the_click_list[0]
  5815. self.collection.set_active(name_sel_obj)
  5816. else:
  5817. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5818. self.collection.set_all_inactive()
  5819. self.collection.set_active(
  5820. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5821. curr_sel_obj = self.collection.get_active()
  5822. # delete the possible selection box around a possible selected object
  5823. self.delete_selection_shape()
  5824. curr_sel_obj.selection_shape_drawn = False
  5825. # create the selection box around the selected object
  5826. if self.defaults['global_selection_shape'] is True:
  5827. self.draw_selection_shape(curr_sel_obj)
  5828. curr_sel_obj.selection_shape_drawn = True
  5829. self.selected_message(curr_sel_obj=curr_sel_obj)
  5830. else:
  5831. # deselect everything
  5832. self.on_objects_selection(False)
  5833. # delete the possible selection box around a possible selected object
  5834. self.delete_selection_shape()
  5835. for o in self.collection.get_list():
  5836. o.selection_shape_drawn = False
  5837. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5838. # only when working on App
  5839. if self.call_source == 'app':
  5840. if self.click_noproject is False:
  5841. # if the Tool Tab is in focus don't change focus to Project Tab
  5842. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5843. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5844. else:
  5845. # restore auto open the Project Tab
  5846. self.click_noproject = False
  5847. # delete any text in the status bar, implicitly the last object name that was selected
  5848. # self.inform.emit("")
  5849. else:
  5850. self.call_source = 'app'
  5851. except Exception as e:
  5852. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5853. def selected_message(self, curr_sel_obj):
  5854. if curr_sel_obj:
  5855. if curr_sel_obj.kind == 'gerber':
  5856. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5857. color='green',
  5858. name=str(curr_sel_obj.options['name']),
  5859. tx=_("selected"))
  5860. )
  5861. elif curr_sel_obj.kind == 'excellon':
  5862. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5863. color='brown',
  5864. name=str(curr_sel_obj.options['name']),
  5865. tx=_("selected"))
  5866. )
  5867. elif curr_sel_obj.kind == 'cncjob':
  5868. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5869. color='blue',
  5870. name=str(curr_sel_obj.options['name']),
  5871. tx=_("selected"))
  5872. )
  5873. elif curr_sel_obj.kind == 'geometry':
  5874. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5875. color='red',
  5876. name=str(curr_sel_obj.options['name']),
  5877. tx=_("selected"))
  5878. )
  5879. def delete_hover_shape(self):
  5880. self.hover_shapes.clear()
  5881. self.hover_shapes.redraw()
  5882. def draw_hover_shape(self, sel_obj, color=None):
  5883. """
  5884. :param sel_obj: The object for which the hover shape must be drawn
  5885. :param color: The color of the hover shape
  5886. :return: None
  5887. """
  5888. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5889. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5890. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5891. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5892. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5893. if self.defaults['units'].upper() == 'MM':
  5894. hover_rect = hover_rect.buffer(-0.1)
  5895. hover_rect = hover_rect.buffer(0.2)
  5896. else:
  5897. hover_rect = hover_rect.buffer(-0.00393)
  5898. hover_rect = hover_rect.buffer(0.00787)
  5899. # if color:
  5900. # face = Color(color)
  5901. # face.alpha = 0.2
  5902. # outline = Color(color, alpha=0.8)
  5903. # else:
  5904. # face = Color(self.defaults['global_sel_fill'])
  5905. # face.alpha = 0.2
  5906. # outline = self.defaults['global_sel_line']
  5907. if color:
  5908. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5909. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5910. else:
  5911. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5912. outline = self.defaults['global_sel_line']
  5913. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5914. if self.is_legacy is True:
  5915. self.hover_shapes.redraw()
  5916. def delete_selection_shape(self):
  5917. self.move_tool.sel_shapes.clear()
  5918. self.move_tool.sel_shapes.redraw()
  5919. def draw_selection_shape(self, sel_obj, color=None):
  5920. """
  5921. Will draw a selection shape around the selected object.
  5922. :param sel_obj: The object for which the selection shape must be drawn
  5923. :param color: The color for the selection shape.
  5924. :return: None
  5925. """
  5926. if sel_obj is None:
  5927. return
  5928. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5929. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5930. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5931. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5932. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5933. if self.defaults['units'].upper() == 'MM':
  5934. sel_rect = sel_rect.buffer(-0.1)
  5935. sel_rect = sel_rect.buffer(0.2)
  5936. else:
  5937. sel_rect = sel_rect.buffer(-0.00393)
  5938. sel_rect = sel_rect.buffer(0.00787)
  5939. if color:
  5940. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5941. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5942. else:
  5943. if self.is_legacy is False:
  5944. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5945. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5946. else:
  5947. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5948. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5949. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5950. color=outline,
  5951. face_color=face,
  5952. update=True,
  5953. layer=0,
  5954. tolerance=None))
  5955. if self.is_legacy is True:
  5956. self.move_tool.sel_shapes.redraw()
  5957. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5958. """
  5959. Will draw a selection shape when dragging mouse on canvas.
  5960. :param old_coords: Old coordinates
  5961. :param coords: New coordinates
  5962. :param kwargs: Keyword arguments
  5963. :return:
  5964. """
  5965. if 'color' in kwargs:
  5966. color = kwargs['color']
  5967. else:
  5968. color = self.defaults['global_sel_line']
  5969. if 'face_color' in kwargs:
  5970. face_color = kwargs['face_color']
  5971. else:
  5972. face_color = self.defaults['global_sel_fill']
  5973. if 'face_alpha' in kwargs:
  5974. face_alpha = kwargs['face_alpha']
  5975. else:
  5976. face_alpha = 0.3
  5977. x0, y0 = old_coords
  5978. x1, y1 = coords
  5979. pt1 = (x0, y0)
  5980. pt2 = (x1, y0)
  5981. pt3 = (x1, y1)
  5982. pt4 = (x0, y1)
  5983. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5984. # color_t = Color(face_color)
  5985. # color_t.alpha = face_alpha
  5986. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5987. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5988. layer=0, tolerance=None)
  5989. if self.is_legacy is True:
  5990. self.move_tool.sel_shapes.redraw()
  5991. def on_file_new_click(self):
  5992. """
  5993. Callback for menu item File -> New.
  5994. Executed on clicking the Menu -> File -> New Project
  5995. :return:
  5996. """
  5997. if self.collection.get_list() and self.should_we_save:
  5998. msgbox = QtWidgets.QMessageBox()
  5999. # msgbox.setText("<B>Save changes ...</B>")
  6000. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6001. "Creating a New project will delete them.\n"
  6002. "Do you want to Save the project?"))
  6003. msgbox.setWindowTitle(_("Save changes"))
  6004. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6005. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6006. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6007. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6008. msgbox.setDefaultButton(bt_yes)
  6009. msgbox.exec_()
  6010. response = msgbox.clickedButton()
  6011. if response == bt_yes:
  6012. self.on_file_saveprojectas()
  6013. elif response == bt_cancel:
  6014. return
  6015. elif response == bt_no:
  6016. self.on_file_new()
  6017. else:
  6018. self.on_file_new()
  6019. self.inform.emit('[success] %s...' % _("New Project created"))
  6020. def on_file_new(self, cli=None):
  6021. """
  6022. Returns the application to its startup state. This method is thread-safe.
  6023. :param cli: Boolean. If True this method was run from command line
  6024. :return: None
  6025. """
  6026. self.defaults.report_usage("on_file_new")
  6027. # Remove everything from memory
  6028. App.log.debug("on_file_new()")
  6029. # close any editor that might be open
  6030. if self.call_source != 'app':
  6031. self.editor2object(cleanup=True)
  6032. # ## EDITOR section
  6033. self.geo_editor = FlatCAMGeoEditor(self)
  6034. self.exc_editor = FlatCAMExcEditor(self)
  6035. self.grb_editor = FlatCAMGrbEditor(self)
  6036. # Clear pool
  6037. self.clear_pool()
  6038. for obj in self.collection.get_list():
  6039. # delete shapes left drawn from mark shape_collections, if any
  6040. if isinstance(obj, GerberObject):
  6041. try:
  6042. for el in obj.mark_shapes:
  6043. obj.mark_shapes[el].clear(update=True)
  6044. obj.mark_shapes[el].enabled = False
  6045. del el
  6046. except AttributeError:
  6047. pass
  6048. # also delete annotation shapes, if any
  6049. elif isinstance(obj, CNCJobObject):
  6050. try:
  6051. obj.text_col.enabled = False
  6052. del obj.text_col
  6053. obj.annotation.clear(update=True)
  6054. del obj.annotation
  6055. except AttributeError:
  6056. pass
  6057. # delete the exclusion areas
  6058. self.exc_areas.clear_shapes()
  6059. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6060. self.shell.init_tcl()
  6061. # delete any selection shape on canvas
  6062. self.delete_selection_shape()
  6063. # delete all FlatCAM objects
  6064. self.collection.delete_all()
  6065. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  6066. self.setup_component_editor()
  6067. # Clear project filename
  6068. self.project_filename = None
  6069. # Load the application defaults
  6070. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6071. # Re-fresh project options
  6072. self.on_options_app2project()
  6073. # Init FlatCAMTools
  6074. self.init_tools()
  6075. # Try to close all tabs in the PlotArea but only if the GUI is active (CLI is None)
  6076. if cli is None:
  6077. # we need to go in reverse because once we remove a tab then the index changes
  6078. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  6079. # and so on. Therefore the deletion should be done in reverse
  6080. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  6081. for index in range(wdg_count, -1, -1):
  6082. try:
  6083. self.ui.plot_tab_area.closeTab(index)
  6084. except Exception as e:
  6085. log.debug("App.on_file_new() --> %s" % str(e))
  6086. # # And then add again the Plot Area
  6087. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  6088. self.ui.plot_tab_area.protectTab(0)
  6089. # take the focus of the Notebook on Project Tab.
  6090. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6091. self.set_ui_title(name=_("New Project - Not saved"))
  6092. def obj_properties(self):
  6093. """
  6094. Will launch the object Properties Tool
  6095. :return:
  6096. """
  6097. self.defaults.report_usage("obj_properties()")
  6098. self.properties_tool.run(toggle=False)
  6099. def on_project_context_save(self):
  6100. """
  6101. Wrapper, will save the object function of it's type
  6102. :return:
  6103. """
  6104. obj = self.collection.get_active()
  6105. if type(obj) == GeometryObject:
  6106. self.on_file_exportdxf()
  6107. elif type(obj) == ExcellonObject:
  6108. self.on_file_saveexcellon()
  6109. elif type(obj) == CNCJobObject:
  6110. obj.on_exportgcode_button_click()
  6111. elif type(obj) == GerberObject:
  6112. self.on_file_savegerber()
  6113. elif type(obj) == ScriptObject:
  6114. self.on_file_savescript()
  6115. elif type(obj) == DocumentObject:
  6116. self.on_file_savedocument()
  6117. def obj_move(self):
  6118. """
  6119. Callback for the Move menu entry in various Context Menu's.
  6120. :return:
  6121. """
  6122. self.defaults.report_usage("obj_move()")
  6123. self.move_tool.run(toggle=False)
  6124. def on_fileopengerber(self, signal, name=None):
  6125. """
  6126. File menu callback for opening a Gerber.
  6127. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6128. :param name:
  6129. :return: None
  6130. """
  6131. self.defaults.report_usage("on_fileopengerber")
  6132. App.log.debug("on_fileopengerber()")
  6133. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6134. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6135. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6136. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6137. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6138. "*.mil);;" \
  6139. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6140. "Allegro Files (*.art);;" \
  6141. "Mentor Files (*.pho *.gdo);;" \
  6142. "All Files (*.*)"
  6143. if name is None:
  6144. try:
  6145. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6146. directory=self.get_last_folder(),
  6147. filter=_filter_)
  6148. except TypeError:
  6149. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6150. filenames = [str(filename) for filename in filenames]
  6151. else:
  6152. filenames = [name]
  6153. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6154. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6155. _("Opening Gerber file.")),
  6156. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6157. color=QtGui.QColor("gray"))
  6158. if len(filenames) == 0:
  6159. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6160. else:
  6161. for filename in filenames:
  6162. if filename != '':
  6163. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6164. def on_fileopenexcellon(self, signal, name=None):
  6165. """
  6166. File menu callback for opening an Excellon file.
  6167. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6168. :param name:
  6169. :return: None
  6170. """
  6171. self.defaults.report_usage("on_fileopenexcellon")
  6172. App.log.debug("on_fileopenexcellon()")
  6173. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6174. "All Files (*.*)"
  6175. if name is None:
  6176. try:
  6177. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6178. directory=self.get_last_folder(),
  6179. filter=_filter_)
  6180. except TypeError:
  6181. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6182. filenames = [str(filename) for filename in filenames]
  6183. else:
  6184. filenames = [str(name)]
  6185. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6186. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6187. _("Opening Excellon file.")),
  6188. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6189. color=QtGui.QColor("gray"))
  6190. if len(filenames) == 0:
  6191. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6192. else:
  6193. for filename in filenames:
  6194. if filename != '':
  6195. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6196. def on_fileopengcode(self, signal, name=None):
  6197. """
  6198. File menu call back for opening gcode.
  6199. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6200. :param name:
  6201. :return:
  6202. """
  6203. self.defaults.report_usage("on_fileopengcode")
  6204. App.log.debug("on_fileopengcode()")
  6205. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6206. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6207. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6208. "All Files (*.*)"
  6209. if name is None:
  6210. try:
  6211. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6212. directory=self.get_last_folder(),
  6213. filter=_filter_)
  6214. except TypeError:
  6215. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6216. filenames = [str(filename) for filename in filenames]
  6217. else:
  6218. filenames = [name]
  6219. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6220. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6221. _("Opening G-Code file.")),
  6222. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6223. color=QtGui.QColor("gray"))
  6224. if len(filenames) == 0:
  6225. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6226. else:
  6227. for filename in filenames:
  6228. if filename != '':
  6229. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6230. def on_file_openproject(self, signal):
  6231. """
  6232. File menu callback for opening a project.
  6233. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6234. :return: None
  6235. """
  6236. self.defaults.report_usage("on_file_openproject")
  6237. App.log.debug("on_file_openproject()")
  6238. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6239. try:
  6240. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6241. directory=self.get_last_folder(), filter=_filter_)
  6242. except TypeError:
  6243. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6244. # The Qt methods above will return a QString which can cause problems later.
  6245. # So far json.dump() will fail to serialize it.
  6246. # TODO: Improve the serialization methods and remove this fix.
  6247. filename = str(filename)
  6248. if filename == "":
  6249. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6250. else:
  6251. # self.worker_task.emit({'fcn': self.open_project,
  6252. # 'params': [filename]})
  6253. # The above was failing because open_project() is not
  6254. # thread safe. The new_project()
  6255. self.open_project(filename)
  6256. def on_fileopenhpgl2(self, signal, name=None):
  6257. """
  6258. File menu callback for opening a HPGL2.
  6259. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6260. :param name:
  6261. :return: None
  6262. """
  6263. self.defaults.report_usage("on_fileopenhpgl2")
  6264. App.log.debug("on_fileopenhpgl2()")
  6265. _filter_ = "HPGL2 Files (*.plt);;" \
  6266. "All Files (*.*)"
  6267. if name is None:
  6268. try:
  6269. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6270. directory=self.get_last_folder(),
  6271. filter=_filter_)
  6272. except TypeError:
  6273. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6274. filenames = [str(filename) for filename in filenames]
  6275. else:
  6276. filenames = [name]
  6277. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6278. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6279. _("Opening HPGL2 file.")),
  6280. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6281. color=QtGui.QColor("gray"))
  6282. if len(filenames) == 0:
  6283. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6284. else:
  6285. for filename in filenames:
  6286. if filename != '':
  6287. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6288. def on_file_openconfig(self, signal):
  6289. """
  6290. File menu callback for opening a config file.
  6291. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6292. :return: None
  6293. """
  6294. self.defaults.report_usage("on_file_openconfig")
  6295. App.log.debug("on_file_openconfig()")
  6296. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6297. try:
  6298. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6299. directory=self.data_path, filter=_filter_)
  6300. except TypeError:
  6301. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6302. filter=_filter_)
  6303. if filename == "":
  6304. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6305. else:
  6306. self.open_config_file(filename)
  6307. def on_file_exportsvg(self):
  6308. """
  6309. Callback for menu item File->Export SVG.
  6310. :return: None
  6311. """
  6312. self.defaults.report_usage("on_file_exportsvg")
  6313. App.log.debug("on_file_exportsvg()")
  6314. obj = self.collection.get_active()
  6315. if obj is None:
  6316. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6317. msg = _("Please Select a Geometry object to export")
  6318. msgbox = QtWidgets.QMessageBox()
  6319. msgbox.setInformativeText(msg)
  6320. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6321. msgbox.setDefaultButton(bt_ok)
  6322. msgbox.exec_()
  6323. return
  6324. # Check for more compatible types and add as required
  6325. if (not isinstance(obj, GeometryObject)
  6326. and not isinstance(obj, GerberObject)
  6327. and not isinstance(obj, CNCJobObject)
  6328. and not isinstance(obj, ExcellonObject)):
  6329. msg = '[ERROR_NOTCL] %s' % \
  6330. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6331. msgbox = QtWidgets.QMessageBox()
  6332. msgbox.setInformativeText(msg)
  6333. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6334. msgbox.setDefaultButton(bt_ok)
  6335. msgbox.exec_()
  6336. return
  6337. name = obj.options["name"]
  6338. _filter = "SVG File (*.svg);;All Files (*.*)"
  6339. try:
  6340. filename, _f = FCFileSaveDialog.get_saved_filename(
  6341. caption=_("Export SVG"),
  6342. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6343. filter=_filter)
  6344. except TypeError:
  6345. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6346. filename = str(filename)
  6347. if filename == "":
  6348. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6349. return
  6350. else:
  6351. self.export_svg(name, filename)
  6352. if self.defaults["global_open_style"] is False:
  6353. self.file_opened.emit("SVG", filename)
  6354. self.file_saved.emit("SVG", filename)
  6355. def on_file_exportpng(self):
  6356. self.defaults.report_usage("on_file_exportpng")
  6357. App.log.debug("on_file_exportpng()")
  6358. self.date = str(datetime.today()).rpartition('.')[0]
  6359. self.date = ''.join(c for c in self.date if c not in ':-')
  6360. self.date = self.date.replace(' ', '_')
  6361. if self.is_legacy is False:
  6362. image = _screenshot()
  6363. data = np.asarray(image)
  6364. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6365. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6366. return
  6367. filter_ = "PNG File (*.png);;All Files (*.*)"
  6368. try:
  6369. filename, _f = FCFileSaveDialog.get_saved_filename(
  6370. caption=_("Export PNG Image"),
  6371. directory=self.get_last_save_folder() + '/png_' + self.date,
  6372. filter=filter_)
  6373. except TypeError:
  6374. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6375. filename = str(filename)
  6376. if filename == "":
  6377. self.inform.emit(_("Cancelled."))
  6378. return
  6379. else:
  6380. if self.is_legacy is False:
  6381. write_png(filename, data)
  6382. else:
  6383. self.plotcanvas.figure.savefig(filename)
  6384. if self.defaults["global_open_style"] is False:
  6385. self.file_opened.emit("png", filename)
  6386. self.file_saved.emit("png", filename)
  6387. def on_file_savegerber(self):
  6388. """
  6389. Callback for menu item in Project context menu.
  6390. :return: None
  6391. """
  6392. self.defaults.report_usage("on_file_savegerber")
  6393. App.log.debug("on_file_savegerber()")
  6394. obj = self.collection.get_active()
  6395. if obj is None:
  6396. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6397. return
  6398. # Check for more compatible types and add as required
  6399. if not isinstance(obj, GerberObject):
  6400. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6401. return
  6402. name = self.collection.get_active().options["name"]
  6403. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6404. try:
  6405. filename, _f = FCFileSaveDialog.get_saved_filename(
  6406. caption="Save Gerber source file",
  6407. directory=self.get_last_save_folder() + '/' + name,
  6408. filter=_filter)
  6409. except TypeError:
  6410. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6411. filename = str(filename)
  6412. if filename == "":
  6413. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6414. return
  6415. else:
  6416. self.save_source_file(name, filename)
  6417. if self.defaults["global_open_style"] is False:
  6418. self.file_opened.emit("Gerber", filename)
  6419. self.file_saved.emit("Gerber", filename)
  6420. def on_file_savescript(self):
  6421. """
  6422. Callback for menu item in Project context menu.
  6423. :return: None
  6424. """
  6425. self.defaults.report_usage("on_file_savescript")
  6426. App.log.debug("on_file_savescript()")
  6427. obj = self.collection.get_active()
  6428. if obj is None:
  6429. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6430. return
  6431. # Check for more compatible types and add as required
  6432. if not isinstance(obj, ScriptObject):
  6433. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6434. return
  6435. name = self.collection.get_active().options["name"]
  6436. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6437. try:
  6438. filename, _f = FCFileSaveDialog.get_saved_filename(
  6439. caption="Save Script source file",
  6440. directory=self.get_last_save_folder() + '/' + name,
  6441. filter=_filter)
  6442. except TypeError:
  6443. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6444. filename = str(filename)
  6445. if filename == "":
  6446. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6447. return
  6448. else:
  6449. self.save_source_file(name, filename)
  6450. if self.defaults["global_open_style"] is False:
  6451. self.file_opened.emit("Script", filename)
  6452. self.file_saved.emit("Script", filename)
  6453. def on_file_savedocument(self):
  6454. """
  6455. Callback for menu item in Project context menu.
  6456. :return: None
  6457. """
  6458. self.defaults.report_usage("on_file_savedocument")
  6459. App.log.debug("on_file_savedocument()")
  6460. obj = self.collection.get_active()
  6461. if obj is None:
  6462. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6463. return
  6464. # Check for more compatible types and add as required
  6465. if not isinstance(obj, ScriptObject):
  6466. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6467. return
  6468. name = self.collection.get_active().options["name"]
  6469. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6470. try:
  6471. filename, _f = FCFileSaveDialog.get_saved_filename(
  6472. caption="Save Document source file",
  6473. directory=self.get_last_save_folder() + '/' + name,
  6474. filter=_filter)
  6475. except TypeError:
  6476. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6477. filename = str(filename)
  6478. if filename == "":
  6479. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6480. return
  6481. else:
  6482. self.save_source_file(name, filename)
  6483. if self.defaults["global_open_style"] is False:
  6484. self.file_opened.emit("Document", filename)
  6485. self.file_saved.emit("Document", filename)
  6486. def on_file_saveexcellon(self):
  6487. """
  6488. Callback for menu item in project context menu.
  6489. :return: None
  6490. """
  6491. self.defaults.report_usage("on_file_saveexcellon")
  6492. App.log.debug("on_file_saveexcellon()")
  6493. obj = self.collection.get_active()
  6494. if obj is None:
  6495. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6496. return
  6497. # Check for more compatible types and add as required
  6498. if not isinstance(obj, ExcellonObject):
  6499. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6500. return
  6501. name = self.collection.get_active().options["name"]
  6502. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6503. try:
  6504. filename, _f = FCFileSaveDialog.get_saved_filename(
  6505. caption=_("Save Excellon source file"),
  6506. directory=self.get_last_save_folder() + '/' + name,
  6507. filter=_filter)
  6508. except TypeError:
  6509. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6510. filename = str(filename)
  6511. if filename == "":
  6512. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6513. return
  6514. else:
  6515. self.save_source_file(name, filename)
  6516. if self.defaults["global_open_style"] is False:
  6517. self.file_opened.emit("Excellon", filename)
  6518. self.file_saved.emit("Excellon", filename)
  6519. def on_file_exportexcellon(self):
  6520. """
  6521. Callback for menu item File->Export->Excellon.
  6522. :return: None
  6523. """
  6524. self.defaults.report_usage("on_file_exportexcellon")
  6525. App.log.debug("on_file_exportexcellon()")
  6526. obj = self.collection.get_active()
  6527. if obj is None:
  6528. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6529. return
  6530. # Check for more compatible types and add as required
  6531. if not isinstance(obj, ExcellonObject):
  6532. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6533. return
  6534. name = self.collection.get_active().options["name"]
  6535. _filter = self.defaults["excellon_save_filters"]
  6536. try:
  6537. filename, _f = FCFileSaveDialog.get_saved_filename(
  6538. caption=_("Export Excellon"),
  6539. directory=self.get_last_save_folder() + '/' + name,
  6540. filter=_filter)
  6541. except TypeError:
  6542. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6543. filename = str(filename)
  6544. if filename == "":
  6545. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6546. return
  6547. else:
  6548. used_extension = filename.rpartition('.')[2]
  6549. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6550. self.export_excellon(name, filename)
  6551. if self.defaults["global_open_style"] is False:
  6552. self.file_opened.emit("Excellon", filename)
  6553. self.file_saved.emit("Excellon", filename)
  6554. def on_file_exportgerber(self):
  6555. """
  6556. Callback for menu item File->Export->Gerber.
  6557. :return: None
  6558. """
  6559. self.defaults.report_usage("on_file_exportgerber")
  6560. App.log.debug("on_file_exportgerber()")
  6561. obj = self.collection.get_active()
  6562. if obj is None:
  6563. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6564. return
  6565. # Check for more compatible types and add as required
  6566. if not isinstance(obj, GerberObject):
  6567. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6568. return
  6569. name = self.collection.get_active().options["name"]
  6570. _filter_ = self.defaults['gerber_save_filters']
  6571. try:
  6572. filename, _f = FCFileSaveDialog.get_saved_filename(
  6573. caption=_("Export Gerber"),
  6574. directory=self.get_last_save_folder() + '/' + name,
  6575. filter=_filter_)
  6576. except TypeError:
  6577. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6578. filename = str(filename)
  6579. if filename == "":
  6580. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6581. return
  6582. else:
  6583. used_extension = filename.rpartition('.')[2]
  6584. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6585. self.export_gerber(name, filename)
  6586. if self.defaults["global_open_style"] is False:
  6587. self.file_opened.emit("Gerber", filename)
  6588. self.file_saved.emit("Gerber", filename)
  6589. def on_file_exportdxf(self):
  6590. """
  6591. Callback for menu item File->Export DXF.
  6592. :return: None
  6593. """
  6594. self.defaults.report_usage("on_file_exportdxf")
  6595. App.log.debug("on_file_exportdxf()")
  6596. obj = self.collection.get_active()
  6597. if obj is None:
  6598. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6599. msg = _("Please Select a Geometry object to export")
  6600. msgbox = QtWidgets.QMessageBox()
  6601. msgbox.setInformativeText(msg)
  6602. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6603. msgbox.setDefaultButton(bt_ok)
  6604. msgbox.exec_()
  6605. return
  6606. # Check for more compatible types and add as required
  6607. if not isinstance(obj, GeometryObject):
  6608. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6609. msgbox = QtWidgets.QMessageBox()
  6610. msgbox.setInformativeText(msg)
  6611. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6612. msgbox.setDefaultButton(bt_ok)
  6613. msgbox.exec_()
  6614. return
  6615. name = self.collection.get_active().options["name"]
  6616. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6617. try:
  6618. filename, _f = FCFileSaveDialog.get_saved_filename(
  6619. caption=_("Export DXF"),
  6620. directory=self.get_last_save_folder() + '/' + name,
  6621. filter=_filter_)
  6622. except TypeError:
  6623. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6624. filename = str(filename)
  6625. if filename == "":
  6626. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6627. return
  6628. else:
  6629. self.export_dxf(name, filename)
  6630. if self.defaults["global_open_style"] is False:
  6631. self.file_opened.emit("DXF", filename)
  6632. self.file_saved.emit("DXF", filename)
  6633. def on_file_importsvg(self, type_of_obj):
  6634. """
  6635. Callback for menu item File->Import SVG.
  6636. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6637. :type type_of_obj: str
  6638. :return: None
  6639. """
  6640. self.defaults.report_usage("on_file_importsvg")
  6641. App.log.debug("on_file_importsvg()")
  6642. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6643. try:
  6644. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6645. directory=self.get_last_folder(), filter=_filter_)
  6646. except TypeError:
  6647. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6648. filter=_filter_)
  6649. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6650. type_of_obj = "geometry"
  6651. filenames = [str(filename) for filename in filenames]
  6652. if len(filenames) == 0:
  6653. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6654. else:
  6655. for filename in filenames:
  6656. if filename != '':
  6657. self.worker_task.emit({'fcn': self.import_svg,
  6658. 'params': [filename, type_of_obj]})
  6659. def on_file_importdxf(self, type_of_obj):
  6660. """
  6661. Callback for menu item File->Import DXF.
  6662. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6663. :type type_of_obj: str
  6664. :return: None
  6665. """
  6666. self.defaults.report_usage("on_file_importdxf")
  6667. App.log.debug("on_file_importdxf()")
  6668. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6669. try:
  6670. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6671. directory=self.get_last_folder(),
  6672. filter=_filter_)
  6673. except TypeError:
  6674. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6675. filter=_filter_)
  6676. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6677. type_of_obj = "geometry"
  6678. filenames = [str(filename) for filename in filenames]
  6679. if len(filenames) == 0:
  6680. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6681. else:
  6682. for filename in filenames:
  6683. if filename != '':
  6684. self.worker_task.emit({'fcn': self.import_dxf,
  6685. 'params': [filename, type_of_obj]})
  6686. # ###############################################################################################################
  6687. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6688. # ###############################################################################################################
  6689. def init_code_editor(self, name):
  6690. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6691. # add the tab if it was closed
  6692. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6693. self.text_editor_tab.setObjectName('text_editor_tab')
  6694. # delete the absolute and relative position and messages in the infobar
  6695. self.ui.position_label.setText("")
  6696. self.ui.rel_position_label.setText("")
  6697. # first clear previous text in text editor (if any)
  6698. self.text_editor_tab.code_editor.clear()
  6699. self.text_editor_tab.code_editor.setReadOnly(False)
  6700. self.toggle_codeeditor = True
  6701. self.text_editor_tab.code_editor.completer_enable = False
  6702. self.text_editor_tab.buttonRun.hide()
  6703. # make sure to keep a reference to the code editor
  6704. self.reference_code_editor = self.text_editor_tab.code_editor
  6705. # Switch plot_area to CNCJob tab
  6706. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6707. def on_view_source(self):
  6708. """
  6709. Called when the user wants to see the source file of the selected object
  6710. :return:
  6711. """
  6712. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6713. self.proc_container.view.set_busy(_("Loading..."))
  6714. try:
  6715. obj = self.collection.get_active()
  6716. except Exception as e:
  6717. log.debug("App.on_view_source() --> %s" % str(e))
  6718. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6719. return 'fail'
  6720. if obj is None:
  6721. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6722. return 'fail'
  6723. flt = "All Files (*.*)"
  6724. if obj.kind == 'gerber':
  6725. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6726. elif obj.kind == 'excellon':
  6727. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6728. elif obj.kind == 'cncjob':
  6729. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6730. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6731. # add the tab if it was closed
  6732. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6733. self.source_editor_tab.setObjectName('source_editor_tab')
  6734. # delete the absolute and relative position and messages in the infobar
  6735. self.ui.position_label.setText("")
  6736. self.ui.rel_position_label.setText("")
  6737. # first clear previous text in text editor (if any)
  6738. self.source_editor_tab.code_editor.clear()
  6739. self.source_editor_tab.code_editor.setReadOnly(False)
  6740. self.source_editor_tab.code_editor.completer_enable = False
  6741. self.source_editor_tab.buttonRun.hide()
  6742. # Switch plot_area to CNCJob tab
  6743. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6744. try:
  6745. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6746. except TypeError:
  6747. pass
  6748. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6749. try:
  6750. self.source_editor_tab.buttonSave.clicked.disconnect()
  6751. except TypeError:
  6752. pass
  6753. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6754. # then append the text from GCode to the text editor
  6755. if obj.kind == 'cncjob':
  6756. try:
  6757. file = obj.export_gcode(
  6758. preamble=self.defaults["cncjob_prepend"],
  6759. postamble=self.defaults["cncjob_append"],
  6760. to_file=True)
  6761. if file == 'fail':
  6762. return 'fail'
  6763. except AttributeError:
  6764. self.inform.emit('[WARNING_NOTCL] %s' %
  6765. _("There is no selected object for which to see it's source file code."))
  6766. return 'fail'
  6767. else:
  6768. try:
  6769. file = StringIO(obj.source_file)
  6770. except (AttributeError, TypeError):
  6771. self.inform.emit('[WARNING_NOTCL] %s' %
  6772. _("There is no selected object for which to see it's source file code."))
  6773. return 'fail'
  6774. self.source_editor_tab.t_frame.hide()
  6775. try:
  6776. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6777. # for line in file:
  6778. # QtWidgets.QApplication.processEvents()
  6779. # proc_line = str(line).strip('\n')
  6780. # self.source_editor_tab.code_editor.append(proc_line)
  6781. except Exception as e:
  6782. log.debug('App.on_view_source() -->%s' % str(e))
  6783. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6784. return
  6785. self.source_editor_tab.handleTextChanged()
  6786. self.source_editor_tab.t_frame.show()
  6787. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6788. self.proc_container.view.set_idle()
  6789. # self.ui.show()
  6790. def on_toggle_code_editor(self):
  6791. self.defaults.report_usage("on_toggle_code_editor()")
  6792. if self.toggle_codeeditor is False:
  6793. self.init_code_editor(name=_("Code Editor"))
  6794. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6795. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6796. self.text_editor_tab.buttonSave.clicked.disconnect()
  6797. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6798. else:
  6799. for idx in range(self.ui.plot_tab_area.count()):
  6800. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6801. self.ui.plot_tab_area.closeTab(idx)
  6802. break
  6803. self.toggle_codeeditor = False
  6804. def on_code_editor_close(self):
  6805. self.toggle_codeeditor = False
  6806. def goto_text_line(self):
  6807. """
  6808. Will scroll a text to the specified text line.
  6809. :return: None
  6810. """
  6811. dia_box = Dialog_box(title=_("Go to Line ..."),
  6812. label=_("Line:"),
  6813. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6814. initial_text='')
  6815. try:
  6816. line = int(dia_box.location) - 1
  6817. except (ValueError, TypeError):
  6818. line = 0
  6819. if dia_box.ok:
  6820. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6821. # at the top of the window
  6822. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6823. # get the document() of the TextEditor
  6824. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6825. # create a Text Cursor based on the searched line
  6826. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6827. # set cursor of the code editor with the cursor at the searcehd line
  6828. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6829. def on_filenewscript(self, silent=False):
  6830. """
  6831. Will create a new script file and open it in the Code Editor
  6832. :param silent: if True will not display status messages
  6833. :param name: if specified will be the name of the new script
  6834. :param text: pass a source file to the newly created script to be loaded in it
  6835. :return: None
  6836. """
  6837. if silent is False:
  6838. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6839. # delete the absolute and relative position and messages in the infobar
  6840. self.ui.position_label.setText("")
  6841. self.ui.rel_position_label.setText("")
  6842. self.new_script_object()
  6843. # script_text = script_obj.source_file
  6844. #
  6845. # self.proc_container.view.set_busy(_("Loading..."))
  6846. # script_obj.script_editor_tab.t_frame.hide()
  6847. #
  6848. # script_obj.script_editor_tab.t_frame.show()
  6849. # self.proc_container.view.set_idle()
  6850. def on_fileopenscript(self, name=None, silent=False):
  6851. """
  6852. Will open a Tcl script file into the Code Editor
  6853. :param silent: if True will not display status messages
  6854. :param name: name of a Tcl script file to open
  6855. :return: None
  6856. """
  6857. self.defaults.report_usage("on_fileopenscript")
  6858. App.log.debug("on_fileopenscript()")
  6859. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6860. "All Files (*.*)"
  6861. if name:
  6862. filenames = [name]
  6863. else:
  6864. try:
  6865. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6866. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6867. except TypeError:
  6868. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6869. if len(filenames) == 0:
  6870. if silent is False:
  6871. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6872. else:
  6873. for filename in filenames:
  6874. if filename != '':
  6875. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6876. def on_fileopenscript_example(self, name=None, silent=False):
  6877. """
  6878. Will open a Tcl script file into the Code Editor
  6879. :param silent: if True will not display status messages
  6880. :param name: name of a Tcl script file to open
  6881. :return:
  6882. """
  6883. self.defaults.report_usage("on_fileopenscript_example")
  6884. log.debug("on_fileopenscript_example()")
  6885. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6886. "All Files (*.*)"
  6887. # test if the app was frozen and choose the path for the configuration file
  6888. if getattr(sys, "frozen", False) is True:
  6889. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6890. else:
  6891. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6892. if name:
  6893. filenames = [name]
  6894. else:
  6895. try:
  6896. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6897. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6898. except TypeError:
  6899. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6900. if len(filenames) == 0:
  6901. if silent is False:
  6902. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6903. else:
  6904. for filename in filenames:
  6905. if filename != '':
  6906. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6907. def on_filerunscript(self, name=None, silent=False):
  6908. """
  6909. File menu callback for loading and running a TCL script.
  6910. :param silent: if True will not display status messages
  6911. :param name: name of a Tcl script file to be run by FlatCAM
  6912. :return: None
  6913. """
  6914. self.defaults.report_usage("on_filerunscript")
  6915. App.log.debug("on_file_runscript()")
  6916. if name:
  6917. filename = name
  6918. if self.cmd_line_headless != 1:
  6919. self.splash.showMessage('%s: %ssec\n%s' %
  6920. (_("Canvas initialization started.\n"
  6921. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6922. _("Executing ScriptObject file.")
  6923. ),
  6924. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6925. color=QtGui.QColor("gray"))
  6926. else:
  6927. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6928. "All Files (*.*)"
  6929. try:
  6930. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6931. directory=self.get_last_folder(), filter=_filter_)
  6932. except TypeError:
  6933. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6934. # The Qt methods above will return a QString which can cause problems later.
  6935. # So far json.dump() will fail to serialize it.
  6936. filename = str(filename)
  6937. if filename == "":
  6938. if silent is False:
  6939. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6940. else:
  6941. if self.cmd_line_headless != 1:
  6942. if self.ui.shell_dock.isHidden():
  6943. self.ui.shell_dock.show()
  6944. try:
  6945. with open(filename, "r") as tcl_script:
  6946. cmd_line_shellfile_content = tcl_script.read()
  6947. if self.cmd_line_headless != 1:
  6948. self.shell.exec_command(cmd_line_shellfile_content)
  6949. else:
  6950. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6951. if silent is False:
  6952. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6953. except Exception as e:
  6954. log.debug("App.on_filerunscript() -> %s" % str(e))
  6955. sys.exit(2)
  6956. def on_file_saveproject(self, silent=False):
  6957. """
  6958. Callback for menu item File->Save Project. Saves the project to
  6959. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6960. if set to None. The project is saved by calling ``self.save_project()``.
  6961. :param silent: if True will not display status messages
  6962. :return: None
  6963. """
  6964. self.defaults.report_usage("on_file_saveproject")
  6965. if self.project_filename is None:
  6966. self.on_file_saveprojectas()
  6967. else:
  6968. self.worker_task.emit({'fcn': self.save_project,
  6969. 'params': [self.project_filename, silent]})
  6970. if self.defaults["global_open_style"] is False:
  6971. self.file_opened.emit("project", self.project_filename)
  6972. self.file_saved.emit("project", self.project_filename)
  6973. self.set_ui_title(name=self.project_filename)
  6974. self.should_we_save = False
  6975. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6976. """
  6977. Callback for menu item File->Save Project As... Opens a file
  6978. chooser and saves the project to the given file via
  6979. ``self.save_project()``.
  6980. :param make_copy if to be create a copy of the project; boolean
  6981. :param use_thread: if to be run in a separate thread; boolean
  6982. :param quit_action: if to be followed by quiting the application; boolean
  6983. :return: None
  6984. """
  6985. self.defaults.report_usage("on_file_saveprojectas")
  6986. self.date = str(datetime.today()).rpartition('.')[0]
  6987. self.date = ''.join(c for c in self.date if c not in ':-')
  6988. self.date = self.date.replace(' ', '_')
  6989. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6990. try:
  6991. filename, _f = FCFileSaveDialog.get_saved_filename(
  6992. caption=_("Save Project As ..."),
  6993. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6994. proj=_("Project")),
  6995. filter=filter_
  6996. )
  6997. except TypeError:
  6998. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6999. filename = str(filename)
  7000. if filename == '':
  7001. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7002. return
  7003. if use_thread is True:
  7004. self.worker_task.emit({'fcn': self.save_project,
  7005. 'params': [filename, quit_action]})
  7006. else:
  7007. self.save_project(filename, quit_action)
  7008. # self.save_project(filename)
  7009. if self.defaults["global_open_style"] is False:
  7010. self.file_opened.emit("project", filename)
  7011. self.file_saved.emit("project", filename)
  7012. if not make_copy:
  7013. self.project_filename = filename
  7014. self.set_ui_title(name=self.project_filename)
  7015. self.should_we_save = False
  7016. def on_file_save_objects_pdf(self, use_thread=True):
  7017. self.date = str(datetime.today()).rpartition('.')[0]
  7018. self.date = ''.join(c for c in self.date if c not in ':-')
  7019. self.date = self.date.replace(' ', '_')
  7020. try:
  7021. obj_selection = self.collection.get_selected()
  7022. if len(obj_selection) == 1:
  7023. obj_name = str(obj_selection[0].options['name'])
  7024. else:
  7025. obj_name = _("FlatCAM objects print")
  7026. except AttributeError as err:
  7027. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7028. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7029. return
  7030. if not obj_selection:
  7031. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7032. return
  7033. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7034. try:
  7035. filename, _f = FCFileSaveDialog.get_saved_filename(
  7036. caption=_("Save Object as PDF ..."),
  7037. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7038. obj_name=obj_name,
  7039. date=self.date),
  7040. filter=filter_
  7041. )
  7042. except TypeError:
  7043. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7044. filename = str(filename)
  7045. if filename == '':
  7046. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7047. return
  7048. if use_thread is True:
  7049. self.proc_container.new(_("Printing PDF ... Please wait."))
  7050. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7051. else:
  7052. self.save_pdf(filename, obj_selection)
  7053. # self.save_project(filename)
  7054. if self.defaults["global_open_style"] is False:
  7055. self.file_opened.emit("pdf", filename)
  7056. self.file_saved.emit("pdf", filename)
  7057. def save_pdf(self, file_name, obj_selection):
  7058. p_size = self.defaults['global_workspaceT']
  7059. orientation = self.defaults['global_workspace_orientation']
  7060. color = 'black'
  7061. transparency_level = 1.0
  7062. self.pagesize = {}
  7063. self.pagesize.update(
  7064. {
  7065. 'Bounds': None,
  7066. 'A0': (841 * mm, 1189 * mm),
  7067. 'A1': (594 * mm, 841 * mm),
  7068. 'A2': (420 * mm, 594 * mm),
  7069. 'A3': (297 * mm, 420 * mm),
  7070. 'A4': (210 * mm, 297 * mm),
  7071. 'A5': (148 * mm, 210 * mm),
  7072. 'A6': (105 * mm, 148 * mm),
  7073. 'A7': (74 * mm, 105 * mm),
  7074. 'A8': (52 * mm, 74 * mm),
  7075. 'A9': (37 * mm, 52 * mm),
  7076. 'A10': (26 * mm, 37 * mm),
  7077. 'B0': (1000 * mm, 1414 * mm),
  7078. 'B1': (707 * mm, 1000 * mm),
  7079. 'B2': (500 * mm, 707 * mm),
  7080. 'B3': (353 * mm, 500 * mm),
  7081. 'B4': (250 * mm, 353 * mm),
  7082. 'B5': (176 * mm, 250 * mm),
  7083. 'B6': (125 * mm, 176 * mm),
  7084. 'B7': (88 * mm, 125 * mm),
  7085. 'B8': (62 * mm, 88 * mm),
  7086. 'B9': (44 * mm, 62 * mm),
  7087. 'B10': (31 * mm, 44 * mm),
  7088. 'C0': (917 * mm, 1297 * mm),
  7089. 'C1': (648 * mm, 917 * mm),
  7090. 'C2': (458 * mm, 648 * mm),
  7091. 'C3': (324 * mm, 458 * mm),
  7092. 'C4': (229 * mm, 324 * mm),
  7093. 'C5': (162 * mm, 229 * mm),
  7094. 'C6': (114 * mm, 162 * mm),
  7095. 'C7': (81 * mm, 114 * mm),
  7096. 'C8': (57 * mm, 81 * mm),
  7097. 'C9': (40 * mm, 57 * mm),
  7098. 'C10': (28 * mm, 40 * mm),
  7099. # American paper sizes
  7100. 'LETTER': (8.5 * inch, 11 * inch),
  7101. 'LEGAL': (8.5 * inch, 14 * inch),
  7102. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7103. # From https://en.wikipedia.org/wiki/Paper_size
  7104. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7105. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7106. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7107. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7108. 'LEDGER': (17 * inch, 11 * inch),
  7109. }
  7110. )
  7111. exported_svg = []
  7112. for obj in obj_selection:
  7113. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7114. scale_factor_x=None, scale_factor_y=None,
  7115. skew_factor_x=None, skew_factor_y=None,
  7116. mirror=None)
  7117. if obj.kind.lower() == 'gerber':
  7118. # color = self.defaults["gerber_plot_fill"][:-2]
  7119. color = obj.fill_color[:-2]
  7120. elif obj.kind.lower() == 'excellon':
  7121. color = '#C40000'
  7122. elif obj.kind.lower() == 'geometry':
  7123. color = self.defaults["global_draw_color"]
  7124. # Change the attributes of the exported SVG
  7125. # We don't need stroke-width
  7126. # We set opacity to maximum
  7127. # We set the colour to WHITE
  7128. root = ET.fromstring(svg_obj)
  7129. for child in root:
  7130. child.set('fill', str(color))
  7131. child.set('opacity', str(transparency_level))
  7132. child.set('stroke', str(color))
  7133. exported_svg.append(ET.tostring(root))
  7134. xmin = Inf
  7135. ymin = Inf
  7136. xmax = -Inf
  7137. ymax = -Inf
  7138. for obj in obj_selection:
  7139. try:
  7140. gxmin, gymin, gxmax, gymax = obj.bounds()
  7141. xmin = min([xmin, gxmin])
  7142. ymin = min([ymin, gymin])
  7143. xmax = max([xmax, gxmax])
  7144. ymax = max([ymax, gymax])
  7145. except Exception as e:
  7146. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7147. # Determine bounding area for svg export
  7148. bounds = [xmin, ymin, xmax, ymax]
  7149. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7150. # This contain the measure units
  7151. uom = obj_selection[0].units.lower()
  7152. # Define a boundary around SVG of about 1.0mm (~39mils)
  7153. if uom in "mm":
  7154. boundary = 1.0
  7155. else:
  7156. boundary = 0.0393701
  7157. # Convert everything to strings for use in the xml doc
  7158. svgwidth = str(size[0] + (2 * boundary))
  7159. svgheight = str(size[1] + (2 * boundary))
  7160. minx = str(bounds[0] - boundary)
  7161. miny = str(bounds[1] + boundary + size[1])
  7162. # Add a SVG Header and footer to the svg output from shapely
  7163. # The transform flips the Y Axis so that everything renders
  7164. # properly within svg apps such as inkscape
  7165. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7166. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7167. svg_header += 'width="' + svgwidth + uom + '" '
  7168. svg_header += 'height="' + svgheight + uom + '" '
  7169. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7170. svg_header += '>'
  7171. svg_header += '<g transform="scale(1,-1)">'
  7172. svg_footer = '</g> </svg>'
  7173. svg_elem = str(svg_header)
  7174. for svg_item in exported_svg:
  7175. svg_elem += str(svg_item)
  7176. svg_elem += str(svg_footer)
  7177. # Parse the xml through a xml parser just to add line feeds
  7178. # and to make it look more pretty for the output
  7179. doc = parse_xml_string(svg_elem)
  7180. doc_final = doc.toprettyxml()
  7181. try:
  7182. if self.defaults['units'].upper() == 'IN':
  7183. unit = inch
  7184. else:
  7185. unit = mm
  7186. doc_final = StringIO(doc_final)
  7187. drawing = svg2rlg(doc_final)
  7188. if p_size == 'Bounds':
  7189. renderPDF.drawToFile(drawing, file_name)
  7190. else:
  7191. if orientation == 'p':
  7192. page_size = portrait(self.pagesize[p_size])
  7193. else:
  7194. page_size = landscape(self.pagesize[p_size])
  7195. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7196. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7197. renderPDF.draw(drawing, my_canvas, 0, 0)
  7198. my_canvas.save()
  7199. except Exception as e:
  7200. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7201. return 'fail'
  7202. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7203. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7204. """
  7205. Exports a Geometry Object to an SVG file.
  7206. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7207. :param filename: Path to the SVG file to save to.
  7208. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7209. :return:
  7210. """
  7211. self.defaults.report_usage("export_svg()")
  7212. if filename is None:
  7213. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7214. is not None else self.defaults["global_last_folder"]
  7215. self.log.debug("export_svg()")
  7216. try:
  7217. obj = self.collection.get_by_name(str(obj_name))
  7218. except Exception:
  7219. # TODO: The return behavior has not been established... should raise exception?
  7220. return "Could not retrieve object: %s" % obj_name
  7221. with self.proc_container.new(_("Exporting SVG")) as proc:
  7222. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7223. # Determine bounding area for svg export
  7224. bounds = obj.bounds()
  7225. size = obj.size()
  7226. # Convert everything to strings for use in the xml doc
  7227. svgwidth = str(size[0])
  7228. svgheight = str(size[1])
  7229. minx = str(bounds[0])
  7230. miny = str(bounds[1] - size[1])
  7231. uom = obj.units.lower()
  7232. # Add a SVG Header and footer to the svg output from shapely
  7233. # The transform flips the Y Axis so that everything renders
  7234. # properly within svg apps such as inkscape
  7235. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7236. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7237. svg_header += 'width="' + svgwidth + uom + '" '
  7238. svg_header += 'height="' + svgheight + uom + '" '
  7239. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7240. svg_header += '<g transform="scale(1,-1)">'
  7241. svg_footer = '</g> </svg>'
  7242. svg_elem = svg_header + exported_svg + svg_footer
  7243. # Parse the xml through a xml parser just to add line feeds
  7244. # and to make it look more pretty for the output
  7245. svgcode = parse_xml_string(svg_elem)
  7246. svgcode = svgcode.toprettyxml()
  7247. try:
  7248. with open(filename, 'w') as fp:
  7249. fp.write(svgcode)
  7250. except PermissionError:
  7251. self.inform.emit('[WARNING] %s' %
  7252. _("Permission denied, saving not possible.\n"
  7253. "Most likely another app is holding the file open and not accessible."))
  7254. return 'fail'
  7255. if self.defaults["global_open_style"] is False:
  7256. self.file_opened.emit("SVG", filename)
  7257. self.file_saved.emit("SVG", filename)
  7258. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7259. def save_source_file(self, obj_name, filename, use_thread=True):
  7260. """
  7261. Exports a FlatCAM Object to an Gerber/Excellon file.
  7262. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7263. :param filename: Path to the Gerber file to save to.
  7264. :param use_thread: if to be run in a separate thread
  7265. :return:
  7266. """
  7267. self.defaults.report_usage("save source file()")
  7268. if filename is None:
  7269. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7270. is not None else self.defaults["global_last_folder"]
  7271. self.log.debug("save source file()")
  7272. obj = self.collection.get_by_name(obj_name)
  7273. file_string = StringIO(obj.source_file)
  7274. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7275. if file_string.getvalue() == '':
  7276. self.inform.emit('[ERROR_NOTCL] %s' %
  7277. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7278. return 'fail'
  7279. try:
  7280. with open(filename, 'w') as file:
  7281. file.writelines('G04*\n')
  7282. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7283. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7284. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7285. file.writelines('G04 Created on : %s*\n' % time_string)
  7286. for line in file_string:
  7287. file.writelines(line)
  7288. except PermissionError:
  7289. self.inform.emit('[WARNING] %s' %
  7290. _("Permission denied, saving not possible.\n"
  7291. "Most likely another app is holding the file open and not accessible."))
  7292. return 'fail'
  7293. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7294. """
  7295. Exports a Excellon Object to an Excellon file.
  7296. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7297. :param filename: Path to the Excellon file to save to.
  7298. :param local_use:
  7299. :param use_thread: if to be run in a separate thread
  7300. :return:
  7301. """
  7302. self.defaults.report_usage("export_excellon()")
  7303. if filename is None:
  7304. if self.defaults["global_last_save_folder"]:
  7305. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7306. else:
  7307. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7308. self.log.debug("export_excellon()")
  7309. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7310. self.defaults["excellon_exp_decimals"]
  7311. )
  7312. if local_use is None:
  7313. try:
  7314. obj = self.collection.get_by_name(str(obj_name))
  7315. except Exception:
  7316. return "Could not retrieve object: %s" % obj_name
  7317. else:
  7318. obj = local_use
  7319. if not isinstance(obj, ExcellonObject):
  7320. self.inform.emit('[ERROR_NOTCL] %s' %
  7321. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7322. return
  7323. # updated units
  7324. eunits = self.defaults["excellon_exp_units"]
  7325. ewhole = self.defaults["excellon_exp_integer"]
  7326. efract = self.defaults["excellon_exp_decimals"]
  7327. ezeros = self.defaults["excellon_exp_zeros"]
  7328. eformat = self.defaults["excellon_exp_format"]
  7329. slot_type = self.defaults["excellon_exp_slot_type"]
  7330. fc_units = self.defaults['units'].upper()
  7331. if fc_units == 'MM':
  7332. factor = 1 if eunits == 'METRIC' else 0.03937
  7333. else:
  7334. factor = 25.4 if eunits == 'METRIC' else 1
  7335. def make_excellon():
  7336. try:
  7337. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7338. header = 'M48\n'
  7339. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7340. (str(self.version), str(self.version_date))
  7341. header += ';Filename: %s' % str(obj_name) + '\n'
  7342. header += ';Created on : %s' % time_str + '\n'
  7343. if eformat == 'dec':
  7344. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7345. header += eunits + '\n'
  7346. for tool in obj.tools:
  7347. if eunits == 'METRIC':
  7348. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7349. tool=str(tool),
  7350. dec=2)
  7351. else:
  7352. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7353. tool=str(tool),
  7354. dec=4)
  7355. else:
  7356. if ezeros == 'LZ':
  7357. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7358. form='ndec', e_zeros='LZ', factor=factor,
  7359. slot_type=slot_type)
  7360. header += '%s,%s\n' % (eunits, 'LZ')
  7361. header += format_exc
  7362. for tool in obj.tools:
  7363. if eunits == 'METRIC':
  7364. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7365. tool=str(tool),
  7366. dec=2)
  7367. else:
  7368. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7369. tool=str(tool),
  7370. dec=4)
  7371. else:
  7372. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7373. form='ndec', e_zeros='TZ', factor=factor,
  7374. slot_type=slot_type)
  7375. header += '%s,%s\n' % (eunits, 'TZ')
  7376. header += format_exc
  7377. for tool in obj.tools:
  7378. if eunits == 'METRIC':
  7379. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7380. tool=str(tool),
  7381. dec=2)
  7382. else:
  7383. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7384. tool=str(tool),
  7385. dec=4)
  7386. header += '%\n'
  7387. footer = 'M30\n'
  7388. exported_excellon = header
  7389. exported_excellon += excellon_code
  7390. exported_excellon += footer
  7391. if local_use is None:
  7392. try:
  7393. with open(filename, 'w') as fp:
  7394. fp.write(exported_excellon)
  7395. except PermissionError:
  7396. self.inform.emit('[WARNING] %s' %
  7397. _("Permission denied, saving not possible.\n"
  7398. "Most likely another app is holding the file open and not accessible."))
  7399. return 'fail'
  7400. if self.defaults["global_open_style"] is False:
  7401. self.file_opened.emit("Excellon", filename)
  7402. self.file_saved.emit("Excellon", filename)
  7403. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7404. else:
  7405. return exported_excellon
  7406. except Exception as e:
  7407. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7408. return 'fail'
  7409. if use_thread is True:
  7410. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7411. def job_thread_exc(app_obj):
  7412. ret = make_excellon()
  7413. if ret == 'fail':
  7414. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7415. return
  7416. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7417. else:
  7418. eret = make_excellon()
  7419. if eret == 'fail':
  7420. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7421. return 'fail'
  7422. if local_use is not None:
  7423. return eret
  7424. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7425. """
  7426. Exports a Gerber Object to an Gerber file.
  7427. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7428. :param filename: Path to the Gerber file to save to.
  7429. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7430. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7431. :param use_thread: if to be run in a separate thread
  7432. :return:
  7433. """
  7434. self.defaults.report_usage("export_gerber()")
  7435. if filename is None:
  7436. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7437. is not None else self.defaults["global_last_folder"]
  7438. self.log.debug("export_gerber()")
  7439. if local_use is None:
  7440. try:
  7441. obj = self.collection.get_by_name(str(obj_name))
  7442. except Exception:
  7443. return "Could not retrieve object: %s" % obj_name
  7444. else:
  7445. obj = local_use
  7446. # updated units
  7447. gunits = self.defaults["gerber_exp_units"]
  7448. gwhole = self.defaults["gerber_exp_integer"]
  7449. gfract = self.defaults["gerber_exp_decimals"]
  7450. gzeros = self.defaults["gerber_exp_zeros"]
  7451. fc_units = self.defaults['units'].upper()
  7452. if fc_units == 'MM':
  7453. factor = 1 if gunits == 'MM' else 0.03937
  7454. else:
  7455. factor = 25.4 if gunits == 'MM' else 1
  7456. def make_gerber():
  7457. try:
  7458. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7459. header = 'G04*\n'
  7460. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7461. (str(self.version), str(self.version_date))
  7462. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7463. header += 'G04 Created on : %s*' % time_str + '\n'
  7464. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7465. header += "%MO{units}*%\n".format(units=gunits)
  7466. for apid in obj.apertures:
  7467. if obj.apertures[apid]['type'] == 'C':
  7468. header += "%ADD{apid}{type},{size}*%\n".format(
  7469. apid=str(apid),
  7470. type='C',
  7471. size=(factor * obj.apertures[apid]['size'])
  7472. )
  7473. elif obj.apertures[apid]['type'] == 'R':
  7474. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7475. apid=str(apid),
  7476. type='R',
  7477. width=(factor * obj.apertures[apid]['width']),
  7478. height=(factor * obj.apertures[apid]['height'])
  7479. )
  7480. elif obj.apertures[apid]['type'] == 'O':
  7481. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7482. apid=str(apid),
  7483. type='O',
  7484. width=(factor * obj.apertures[apid]['width']),
  7485. height=(factor * obj.apertures[apid]['height'])
  7486. )
  7487. header += '\n'
  7488. # obsolete units but some software may need it
  7489. if gunits == 'IN':
  7490. header += 'G70*\n'
  7491. else:
  7492. header += 'G71*\n'
  7493. # Absolute Mode
  7494. header += 'G90*\n'
  7495. header += 'G01*\n'
  7496. # positive polarity
  7497. header += '%LPD*%\n'
  7498. footer = 'M02*\n'
  7499. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7500. exported_gerber = header
  7501. exported_gerber += gerber_code
  7502. exported_gerber += footer
  7503. if local_use is None:
  7504. try:
  7505. with open(filename, 'w') as fp:
  7506. fp.write(exported_gerber)
  7507. except PermissionError:
  7508. self.inform.emit('[WARNING] %s' %
  7509. _("Permission denied, saving not possible.\n"
  7510. "Most likely another app is holding the file open and not accessible."))
  7511. return 'fail'
  7512. if self.defaults["global_open_style"] is False:
  7513. self.file_opened.emit("Gerber", filename)
  7514. self.file_saved.emit("Gerber", filename)
  7515. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7516. else:
  7517. return exported_gerber
  7518. except Exception as e:
  7519. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7520. return 'fail'
  7521. if use_thread is True:
  7522. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7523. def job_thread_grb(app_obj):
  7524. ret = make_gerber()
  7525. if ret == 'fail':
  7526. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7527. return
  7528. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7529. else:
  7530. gret = make_gerber()
  7531. if gret == 'fail':
  7532. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7533. return 'fail'
  7534. if local_use is not None:
  7535. return gret
  7536. def export_dxf(self, obj_name, filename, use_thread=True):
  7537. """
  7538. Exports a Geometry Object to an DXF file.
  7539. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7540. :param filename: Path to the DXF file to save to.
  7541. :param use_thread: if to be run in a separate thread
  7542. :return:
  7543. """
  7544. self.defaults.report_usage("export_dxf()")
  7545. if filename is None:
  7546. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7547. is not None else self.defaults["global_last_folder"]
  7548. self.log.debug("export_dxf()")
  7549. try:
  7550. obj = self.collection.get_by_name(str(obj_name))
  7551. except Exception:
  7552. # TODO: The return behavior has not been established... should raise exception?
  7553. return "Could not retrieve object: %s" % obj_name
  7554. def make_dxf():
  7555. try:
  7556. dxf_code = obj.export_dxf()
  7557. dxf_code.saveas(filename)
  7558. if self.defaults["global_open_style"] is False:
  7559. self.file_opened.emit("DXF", filename)
  7560. self.file_saved.emit("DXF", filename)
  7561. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7562. except Exception:
  7563. return 'fail'
  7564. if use_thread is True:
  7565. with self.proc_container.new(_("Exporting DXF")) as proc:
  7566. def job_thread_exc(app_obj):
  7567. ret_dxf_val = make_dxf()
  7568. if ret_dxf_val == 'fail':
  7569. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7570. return
  7571. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7572. else:
  7573. ret = make_dxf()
  7574. if ret == 'fail':
  7575. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7576. return
  7577. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7578. """
  7579. Adds a new Geometry Object to the projects and populates
  7580. it with shapes extracted from the SVG file.
  7581. :param plot: If True then the resulting object will be plotted on canvas
  7582. :param filename: Path to the SVG file.
  7583. :param geo_type: Type of FlatCAM object that will be created from SVG
  7584. :param outname: The name given to the resulting FlatCAM object
  7585. :return:
  7586. """
  7587. self.defaults.report_usage("import_svg()")
  7588. log.debug("App.import_svg()")
  7589. obj_type = ""
  7590. if geo_type is None or geo_type == "geometry":
  7591. obj_type = "geometry"
  7592. elif geo_type == "gerber":
  7593. obj_type = "gerber"
  7594. else:
  7595. self.inform.emit('[ERROR_NOTCL] %s' %
  7596. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7597. return
  7598. units = self.defaults['units'].upper()
  7599. def obj_init(geo_obj, app_obj):
  7600. geo_obj.import_svg(filename, obj_type, units=units)
  7601. geo_obj.multigeo = False
  7602. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7603. with self.proc_container.new(_("Importing SVG")) as proc:
  7604. # Object name
  7605. name = outname or filename.split('/')[-1].split('\\')[-1]
  7606. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7607. if ret == 'fail':
  7608. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7609. return 'fail'
  7610. # Register recent file
  7611. self.file_opened.emit("svg", filename)
  7612. # GUI feedback
  7613. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7614. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7615. """
  7616. Adds a new Geometry Object to the projects and populates
  7617. it with shapes extracted from the DXF file.
  7618. :param filename: Path to the DXF file.
  7619. :param geo_type: Type of FlatCAM object that will be created from DXF
  7620. :param outname: Name for the imported Geometry
  7621. :param plot: If True then the resulting object will be plotted on canvas
  7622. :return:
  7623. """
  7624. self.defaults.report_usage("import_dxf()")
  7625. obj_type = ""
  7626. if geo_type is None or geo_type == "geometry":
  7627. obj_type = "geometry"
  7628. elif geo_type == "gerber":
  7629. obj_type = geo_type
  7630. else:
  7631. self.inform.emit('[ERROR_NOTCL] %s' %
  7632. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7633. return
  7634. units = self.defaults['units'].upper()
  7635. def obj_init(geo_obj, app_obj):
  7636. geo_obj.import_dxf(filename, obj_type, units=units)
  7637. geo_obj.multigeo = False
  7638. with self.proc_container.new(_("Importing DXF")):
  7639. # Object name
  7640. name = outname or filename.split('/')[-1].split('\\')[-1]
  7641. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7642. if ret == 'fail':
  7643. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7644. return 'fail'
  7645. # Register recent file
  7646. self.file_opened.emit("dxf", filename)
  7647. # GUI feedback
  7648. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7649. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7650. """
  7651. Opens a Gerber file, parses it and creates a new object for
  7652. it in the program. Thread-safe.
  7653. :param outname: Name of the resulting object. None causes the
  7654. name to be that of the file. Str.
  7655. :param filename: Gerber file filename
  7656. :type filename: str
  7657. :param plot: boolean, to plot or not the resulting object
  7658. :param from_tcl: True if run from Tcl Shell
  7659. :return: None
  7660. """
  7661. # How the object should be initialized
  7662. def obj_init(gerber_obj, app_obj):
  7663. assert isinstance(gerber_obj, GerberObject), \
  7664. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7665. # Opening the file happens here
  7666. try:
  7667. gerber_obj.parse_file(filename)
  7668. except IOError:
  7669. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7670. return "fail"
  7671. except ParseError as err:
  7672. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7673. app_obj.log.error(str(err))
  7674. return "fail"
  7675. except Exception as e:
  7676. log.debug("App.open_gerber() --> %s" % str(e))
  7677. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7678. msg += traceback.format_exc()
  7679. app_obj.inform.emit(msg)
  7680. return "fail"
  7681. if gerber_obj.is_empty():
  7682. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7683. _("Object is not Gerber file or empty. Aborting object creation."))
  7684. return "fail"
  7685. App.log.debug("open_gerber()")
  7686. with self.proc_container.new(_("Opening Gerber")):
  7687. # Object name
  7688. name = outname or filename.split('/')[-1].split('\\')[-1]
  7689. # # ## Object creation # ##
  7690. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7691. if ret_val == 'fail':
  7692. if from_tcl:
  7693. filename = self.defaults['global_tcl_path'] + '/' + name
  7694. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7695. if ret_val == 'fail':
  7696. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7697. return 'fail'
  7698. # Register recent file
  7699. self.file_opened.emit("gerber", filename)
  7700. # GUI feedback
  7701. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7702. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7703. """
  7704. Opens an Excellon file, parses it and creates a new object for
  7705. it in the program. Thread-safe.
  7706. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7707. :param filename: Excellon file filename
  7708. :type filename: str
  7709. :param plot: boolean, to plot or not the resulting object
  7710. :param from_tcl: True if run from Tcl Shell
  7711. :return: None
  7712. """
  7713. App.log.debug("open_excellon()")
  7714. # How the object should be initialized
  7715. def obj_init(excellon_obj, app_obj):
  7716. try:
  7717. ret = excellon_obj.parse_file(filename=filename)
  7718. if ret == "fail":
  7719. log.debug("Excellon parsing failed.")
  7720. self.inform.emit('[ERROR_NOTCL] %s' %
  7721. _("This is not Excellon file."))
  7722. return "fail"
  7723. except IOError:
  7724. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7725. (_("Cannot open file"), filename))
  7726. log.debug("Could not open Excellon object.")
  7727. return "fail"
  7728. except Exception:
  7729. msg = '[ERROR_NOTCL] %s' % \
  7730. _("An internal error has occurred. See shell.\n")
  7731. msg += traceback.format_exc()
  7732. app_obj.inform.emit(msg)
  7733. return "fail"
  7734. ret = excellon_obj.create_geometry()
  7735. if ret == 'fail':
  7736. log.debug("Could not create geometry for Excellon object.")
  7737. return "fail"
  7738. for tool in excellon_obj.tools:
  7739. if excellon_obj.tools[tool]['solid_geometry']:
  7740. return
  7741. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7742. return "fail"
  7743. with self.proc_container.new(_("Opening Excellon.")):
  7744. # Object name
  7745. name = outname or filename.split('/')[-1].split('\\')[-1]
  7746. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7747. if ret_val == 'fail':
  7748. if from_tcl:
  7749. filename = self.defaults['global_tcl_path'] + '/' + name
  7750. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7751. if ret_val == 'fail':
  7752. self.inform.emit('[ERROR_NOTCL] %s' %
  7753. _('Open Excellon file failed. Probable not an Excellon file.'))
  7754. return
  7755. # Register recent file
  7756. self.file_opened.emit("excellon", filename)
  7757. # GUI feedback
  7758. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7759. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7760. """
  7761. Opens a G-gcode file, parses it and creates a new object for
  7762. it in the program. Thread-safe.
  7763. :param filename: G-code file filename
  7764. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7765. :param force_parsing:
  7766. :param plot: If True plot the object on canvas
  7767. :param from_tcl: True if run from Tcl Shell
  7768. :return: None
  7769. """
  7770. App.log.debug("open_gcode()")
  7771. # How the object should be initialized
  7772. def obj_init(job_obj, app_obj_):
  7773. """
  7774. :param job_obj: the resulting object
  7775. :type app_obj_: App
  7776. """
  7777. assert isinstance(app_obj_, App), \
  7778. "Initializer expected App, got %s" % type(app_obj_)
  7779. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7780. try:
  7781. f = open(filename)
  7782. gcode = f.read()
  7783. f.close()
  7784. except IOError:
  7785. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7786. return "fail"
  7787. job_obj.gcode = gcode
  7788. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7789. if gcode_ret == "fail":
  7790. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7791. return "fail"
  7792. job_obj.create_geometry()
  7793. with self.proc_container.new(_("Opening G-Code.")):
  7794. # Object name
  7795. name = outname or filename.split('/')[-1].split('\\')[-1]
  7796. # New object creation and file processing
  7797. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7798. if ret_val == 'fail':
  7799. if from_tcl:
  7800. filename = self.defaults['global_tcl_path'] + '/' + name
  7801. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7802. if ret_val == 'fail':
  7803. self.inform.emit('[ERROR_NOTCL] %s' %
  7804. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7805. "Try to load it from File menu.\n "
  7806. "Attempting to create a FlatCAM CNCJob Object from "
  7807. "G-Code file failed during processing"))
  7808. return "fail"
  7809. # Register recent file
  7810. self.file_opened.emit("cncjob", filename)
  7811. # GUI feedback
  7812. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7813. def open_hpgl2(self, filename, outname=None):
  7814. """
  7815. Opens a HPGL2 file, parses it and creates a new object for
  7816. it in the program. Thread-safe.
  7817. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7818. :param filename: HPGL2 file filename
  7819. :return: None
  7820. """
  7821. filename = filename
  7822. # How the object should be initialized
  7823. def obj_init(geo_obj, app_obj):
  7824. assert isinstance(geo_obj, GeometryObject), \
  7825. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7826. # Opening the file happens here
  7827. obj = HPGL2(self)
  7828. try:
  7829. HPGL2.parse_file(obj, filename)
  7830. except IOError:
  7831. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7832. return "fail"
  7833. except ParseError as err:
  7834. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7835. app_obj.log.error(str(err))
  7836. return "fail"
  7837. except Exception as e:
  7838. log.debug("App.open_hpgl2() --> %s" % str(e))
  7839. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7840. msg += traceback.format_exc()
  7841. app_obj.inform.emit(msg)
  7842. return "fail"
  7843. geo_obj.multigeo = True
  7844. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7845. geo_obj.tools = deepcopy(obj.tools)
  7846. geo_obj.source_file = deepcopy(obj.source_file)
  7847. del obj
  7848. if not geo_obj.solid_geometry:
  7849. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7850. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7851. return "fail"
  7852. App.log.debug("open_hpgl2()")
  7853. with self.proc_container.new(_("Opening HPGL2")):
  7854. # Object name
  7855. name = outname or filename.split('/')[-1].split('\\')[-1]
  7856. # # ## Object creation # ##
  7857. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7858. if ret == 'fail':
  7859. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7860. return 'fail'
  7861. # Register recent file
  7862. self.file_opened.emit("geometry", filename)
  7863. # GUI feedback
  7864. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7865. def open_script(self, filename, outname=None, silent=False):
  7866. """
  7867. Opens a Script file, parses it and creates a new object for
  7868. it in the program. Thread-safe.
  7869. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7870. :param filename: Script file filename
  7871. :param silent: If True there will be no messages printed to StatusBar
  7872. :return: None
  7873. """
  7874. def obj_init(script_obj, app_obj):
  7875. assert isinstance(script_obj, ScriptObject), \
  7876. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7877. if silent is False:
  7878. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7879. try:
  7880. script_obj.parse_file(filename)
  7881. except IOError:
  7882. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7883. return "fail"
  7884. except ParseError as err:
  7885. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7886. app_obj.log.error(str(err))
  7887. return "fail"
  7888. except Exception as e:
  7889. log.debug("App.open_script() -> %s" % str(e))
  7890. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7891. msg += traceback.format_exc()
  7892. app_obj.inform.emit(msg)
  7893. return "fail"
  7894. App.log.debug("open_script()")
  7895. with self.proc_container.new(_("Opening TCL Script...")):
  7896. # Object name
  7897. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7898. # Object creation
  7899. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7900. if ret_val == 'fail':
  7901. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7902. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7903. if ret_val == 'fail':
  7904. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7905. return 'fail'
  7906. # Register recent file
  7907. self.file_opened.emit("script", filename)
  7908. # GUI feedback
  7909. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7910. def open_config_file(self, filename, run_from_arg=None):
  7911. """
  7912. Loads a config file from the specified file.
  7913. :param filename: Name of the file from which to load.
  7914. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7915. :return: None
  7916. """
  7917. App.log.debug("Opening config file: " + filename)
  7918. if run_from_arg:
  7919. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7920. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7921. _("Opening FlatCAM Config file.")),
  7922. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7923. color=QtGui.QColor("gray"))
  7924. # # add the tab if it was closed
  7925. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7926. # # first clear previous text in text editor (if any)
  7927. # self.ui.text_editor_tab.code_editor.clear()
  7928. #
  7929. # # Switch plot_area to CNCJob tab
  7930. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7931. # close the Code editor if already open
  7932. if self.toggle_codeeditor:
  7933. self.on_toggle_code_editor()
  7934. self.on_toggle_code_editor()
  7935. try:
  7936. if filename:
  7937. f = QtCore.QFile(filename)
  7938. if f.open(QtCore.QIODevice.ReadOnly):
  7939. stream = QtCore.QTextStream(f)
  7940. code_edited = stream.readAll()
  7941. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7942. f.close()
  7943. except IOError:
  7944. App.log.error("Failed to open config file: %s" % filename)
  7945. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7946. (_("Failed to open config file"), filename))
  7947. return
  7948. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7949. """
  7950. Loads a project from the specified file.
  7951. 1) Loads and parses file
  7952. 2) Registers the file as recently opened.
  7953. 3) Calls on_file_new()
  7954. 4) Updates options
  7955. 5) Calls new_object() with the object's from_dict() as init method.
  7956. 6) Calls plot_all() if plot=True
  7957. :param filename: Name of the file from which to load.
  7958. :param run_from_arg: True if run for arguments
  7959. :param plot: If True plot all objects in the project
  7960. :param cli: Run from command line
  7961. :param from_tcl: True if run from Tcl Sehll
  7962. :return: None
  7963. """
  7964. App.log.debug("Opening project: " + filename)
  7965. # block autosaving while a project is loaded
  7966. self.block_autosave = True
  7967. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7968. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7969. if cli is None:
  7970. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7971. if run_from_arg:
  7972. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7973. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7974. _("Opening FlatCAM Project file.")),
  7975. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7976. color=QtGui.QColor("gray"))
  7977. # Open and parse an uncompressed Project file
  7978. try:
  7979. f = open(filename, 'r')
  7980. except IOError:
  7981. if from_tcl:
  7982. name = filename.split('/')[-1].split('\\')[-1]
  7983. filename = self.defaults['global_tcl_path'] + '/' + name
  7984. try:
  7985. f = open(filename, 'r')
  7986. except IOError:
  7987. log.error("Failed to open project file: %s" % filename)
  7988. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7989. return
  7990. else:
  7991. log.error("Failed to open project file: %s" % filename)
  7992. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7993. return
  7994. try:
  7995. d = json.load(f, object_hook=dict2obj)
  7996. except Exception as e:
  7997. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7998. (filename, str(e)))
  7999. f.close()
  8000. # Open and parse a compressed Project file
  8001. try:
  8002. with lzma.open(filename) as f:
  8003. file_content = f.read().decode('utf-8')
  8004. d = json.loads(file_content, object_hook=dict2obj)
  8005. except Exception as e:
  8006. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8007. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8008. return
  8009. # Clear the current project
  8010. # # NOT THREAD SAFE # ##
  8011. if run_from_arg is True:
  8012. pass
  8013. elif cli is True:
  8014. self.delete_selection_shape()
  8015. else:
  8016. self.on_file_new()
  8017. # Project options
  8018. self.options.update(d['options'])
  8019. self.project_filename = filename
  8020. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8021. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8022. if cli is None:
  8023. self.set_screen_units(self.options["units"])
  8024. # Re create objects
  8025. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8026. for obj in d['objs']:
  8027. try:
  8028. def obj_init(obj_inst, app_inst):
  8029. obj_inst.from_dict(obj)
  8030. App.log.debug("Recreating from opened project an %s object: %s" %
  8031. (obj['kind'].capitalize(), obj['options']['name']))
  8032. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8033. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8034. if cli is None:
  8035. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8036. obj['kind'].upper(),
  8037. obj['options']['name']
  8038. )
  8039. )
  8040. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8041. except Exception as e:
  8042. print('App.open_project() --> ' + str(e))
  8043. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8044. self.should_we_save = False
  8045. self.file_opened.emit("project", filename)
  8046. # restore autosaving after a project was loaded
  8047. self.block_autosave = False
  8048. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8049. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8050. if cli is None:
  8051. self.set_ui_title(name=self.project_filename)
  8052. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8053. def plot_all(self, fit_view=True, use_thread=True):
  8054. """
  8055. Re-generates all plots from all objects.
  8056. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8057. :param use_thread: if True will use threading for plotting the objects
  8058. :return: None
  8059. """
  8060. self.log.debug("Plot_all()")
  8061. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8062. for plot_obj in self.collection.get_list():
  8063. def worker_task(obj):
  8064. with self.proc_container.new("Plotting"):
  8065. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8066. if fit_view is True:
  8067. self.object_plotted.emit(obj)
  8068. if use_thread is True:
  8069. # Send to worker
  8070. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8071. else:
  8072. worker_task(plot_obj)
  8073. def register_folder(self, filename):
  8074. """
  8075. Register the last folder used by the app to open something
  8076. :param filename: the last folder is extracted from the filename
  8077. :return: None
  8078. """
  8079. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8080. def register_save_folder(self, filename):
  8081. """
  8082. Register the last folder used by the app to save something
  8083. :param filename: the last folder is extracted from the filename
  8084. :return: None
  8085. """
  8086. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8087. # def set_progress_bar(self, percentage, text=""):
  8088. # """
  8089. # Set a progress bar to a value (percentage)
  8090. #
  8091. # :param percentage: Value set to the progressbar
  8092. # :param text: Not used
  8093. # :return: None
  8094. # """
  8095. # self.ui.progress_bar.setValue(int(percentage))
  8096. def setup_recent_items(self):
  8097. """
  8098. Setup a dictionary with the recent files accessed, organized by type
  8099. :return:
  8100. """
  8101. icons = {
  8102. "gerber": self.resource_location + "/flatcam_icon16.png",
  8103. "excellon": self.resource_location + "/drill16.png",
  8104. 'geometry': self.resource_location + "/geometry16.png",
  8105. "cncjob": self.resource_location + "/cnc16.png",
  8106. "script": self.resource_location + "/script_new24.png",
  8107. "document": self.resource_location + "/notes16_1.png",
  8108. "project": self.resource_location + "/project16.png",
  8109. "svg": self.resource_location + "/geometry16.png",
  8110. "dxf": self.resource_location + "/dxf16.png",
  8111. "pdf": self.resource_location + "/pdf32.png",
  8112. "image": self.resource_location + "/image16.png"
  8113. }
  8114. try:
  8115. image_opener = self.image_tool.import_image
  8116. except AttributeError:
  8117. image_opener = None
  8118. openers = {
  8119. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8120. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8121. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8122. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8123. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8124. "document": None,
  8125. 'project': self.open_project,
  8126. 'svg': self.import_svg,
  8127. 'dxf': self.import_dxf,
  8128. 'image': image_opener,
  8129. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8130. }
  8131. # Open recent file for files
  8132. try:
  8133. f = open(self.data_path + '/recent.json')
  8134. except IOError:
  8135. App.log.error("Failed to load recent item list.")
  8136. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8137. return
  8138. try:
  8139. self.recent = json.load(f)
  8140. except json.errors.JSONDecodeError:
  8141. App.log.error("Failed to parse recent item list.")
  8142. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8143. f.close()
  8144. return
  8145. f.close()
  8146. # Open recent file for projects
  8147. try:
  8148. fp = open(self.data_path + '/recent_projects.json')
  8149. except IOError:
  8150. App.log.error("Failed to load recent project item list.")
  8151. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8152. return
  8153. try:
  8154. self.recent_projects = json.load(fp)
  8155. except json.errors.JSONDecodeError:
  8156. App.log.error("Failed to parse recent project item list.")
  8157. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8158. fp.close()
  8159. return
  8160. fp.close()
  8161. # Closure needed to create callbacks in a loop.
  8162. # Otherwise late binding occurs.
  8163. def make_callback(func, fname):
  8164. def opener():
  8165. func(fname)
  8166. return opener
  8167. def reset_recent_files():
  8168. # Reset menu
  8169. self.ui.recent.clear()
  8170. self.recent = []
  8171. try:
  8172. ff = open(self.data_path + '/recent.json', 'w')
  8173. except IOError:
  8174. App.log.error("Failed to open recent items file for writing.")
  8175. return
  8176. json.dump(self.recent, ff)
  8177. def reset_recent_projects():
  8178. # Reset menu
  8179. self.ui.recent_projects.clear()
  8180. self.recent_projects = []
  8181. try:
  8182. frp = open(self.data_path + '/recent_projects.json', 'w')
  8183. except IOError:
  8184. App.log.error("Failed to open recent projects items file for writing.")
  8185. return
  8186. json.dump(self.recent, frp)
  8187. # Reset menu
  8188. self.ui.recent.clear()
  8189. self.ui.recent_projects.clear()
  8190. # Create menu items for projects
  8191. for recent in self.recent_projects:
  8192. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8193. if recent['kind'] == 'project':
  8194. try:
  8195. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8196. # Attach callback
  8197. o = make_callback(openers[recent["kind"]], recent['filename'])
  8198. action.triggered.connect(o)
  8199. self.ui.recent_projects.addAction(action)
  8200. except KeyError:
  8201. App.log.error("Unsupported file type: %s" % recent["kind"])
  8202. # Last action in Recent Files menu is one that Clear the content
  8203. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8204. (_("Clear Recent projects")), self)
  8205. clear_action_proj.triggered.connect(reset_recent_projects)
  8206. self.ui.recent_projects.addSeparator()
  8207. self.ui.recent_projects.addAction(clear_action_proj)
  8208. # Create menu items for files
  8209. for recent in self.recent:
  8210. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8211. if recent['kind'] != 'project':
  8212. try:
  8213. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8214. # Attach callback
  8215. o = make_callback(openers[recent["kind"]], recent['filename'])
  8216. action.triggered.connect(o)
  8217. self.ui.recent.addAction(action)
  8218. except KeyError:
  8219. App.log.error("Unsupported file type: %s" % recent["kind"])
  8220. # Last action in Recent Files menu is one that Clear the content
  8221. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8222. (_("Clear Recent files")), self)
  8223. clear_action.triggered.connect(reset_recent_files)
  8224. self.ui.recent.addSeparator()
  8225. self.ui.recent.addAction(clear_action)
  8226. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8227. # self.ui.menufilerecent.set_submenu(recent_menu)
  8228. # recent_menu.show_all()
  8229. # self.ui.recent.show()
  8230. self.log.debug("Recent items list has been populated.")
  8231. def setup_component_editor(self):
  8232. """
  8233. Default text for the Selected tab when is not taken by the Object UI.
  8234. :return:
  8235. """
  8236. # label = QtWidgets.QLabel("Choose an item from Project")
  8237. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8238. sel_title = QtWidgets.QTextEdit(
  8239. _('<b>Shortcut Key List</b>'))
  8240. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8241. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8242. f_settings = QSettings("Open Source", "FlatCAM")
  8243. if f_settings.contains("notebook_font_size"):
  8244. fsize = f_settings.value('notebook_font_size', type=int)
  8245. else:
  8246. fsize = 12
  8247. tsize = fsize + int(fsize / 2)
  8248. # selected_text = (_('''
  8249. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8250. # </p>
  8251. #
  8252. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8253. # The normal flow when working in FlatCAM is the following:</span></p>
  8254. #
  8255. # <ol>
  8256. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8257. # file into
  8258. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8259. # even dragging and dropping the files on the GUI.<br />
  8260. # <br />
  8261. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8262. # drop of the
  8263. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8264. # &nbsp;</li>
  8265. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8266. # and then
  8267. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8268. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8269. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8270. # <br />
  8271. # If the selection of the object is done on the canvas by single click instead, and the
  8272. # <strong>SELECTED TAB</strong>
  8273. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8274. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8275. # it even if it was out of focus.<br />
  8276. # <br />
  8277. # You can change the parameters in this screen and the flow direction is like this:<br />
  8278. # <br />
  8279. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8280. # <strong> Geometry Object
  8281. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8282. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8283. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8284. # </ol>
  8285. #
  8286. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8287. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8288. # <strong>F3</strong>.</span></p>
  8289. #
  8290. # ''').format(fsize=fsize, tsize=tsize))
  8291. selected_text = '''
  8292. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8293. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8294. {s1}</span></p>
  8295. <ol>
  8296. <li><span style="font-size:{fsize}px">{s2}<br />
  8297. <br />
  8298. {s3}</span><br />
  8299. &nbsp;</li>
  8300. <li><span style="font-size:{fsize}px">{s4}<br />
  8301. &nbsp;</li>
  8302. <br />
  8303. <li><span style="font-size:{fsize}px">{s5}<br />
  8304. &nbsp;</li>
  8305. <br />
  8306. <li><span style="font-size:{fsize}px">{s6}<br />
  8307. <br />
  8308. {s7}</span></li>
  8309. </ol>
  8310. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8311. '''.format(
  8312. title=_("Selected Tab - Choose an Item from Project Tab"),
  8313. subtitle=_("Details"),
  8314. s1=_("The normal flow when working in FlatCAM is the following:"),
  8315. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8316. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8317. "files on the GUI."),
  8318. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8319. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8320. "actions offered within the app."),
  8321. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8322. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8323. "SELECTED TAB will be updated with the object properties according to its kind: "
  8324. "Gerber, Excellon, Geometry or CNCJob object."),
  8325. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8326. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8327. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8328. "the SELECTED TAB and populate it even if it was out of focus."),
  8329. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8330. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8331. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8332. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8333. "(again, done in SELECTED TAB) --> Save GCode."),
  8334. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8335. "or through its own key shortcut: <b>F3</b>."),
  8336. tsize=tsize,
  8337. fsize=fsize
  8338. )
  8339. sel_title.setText(selected_text)
  8340. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8341. self.ui.selected_scroll_area.setWidget(sel_title)
  8342. def setup_obj_classes(self):
  8343. """
  8344. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8345. class.
  8346. :return: None
  8347. """
  8348. FlatCAMObj.app = self
  8349. ObjectCollection.app = self
  8350. Gerber.app = self
  8351. Excellon.app = self
  8352. Geometry.app = self
  8353. CNCjob.app = self
  8354. FCProcess.app = self
  8355. FCProcessContainer.app = self
  8356. OptionsGroupUI.app = self
  8357. def version_check(self):
  8358. """
  8359. Checks for the latest version of the program. Alerts the
  8360. user if theirs is outdated. This method is meant to be run
  8361. in a separate thread.
  8362. :return: None
  8363. """
  8364. self.log.debug("version_check()")
  8365. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8366. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8367. App.version_url,
  8368. str(self.defaults['global_serial']),
  8369. str(self.version),
  8370. str(self.os),
  8371. urllib.parse.urlencode(self.defaults["global_stats"])
  8372. )
  8373. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8374. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8375. # urllib.parse.urlencode(self.defaults["global_stats"])
  8376. else:
  8377. # no_stats dict; just so it won't break things on website
  8378. no_ststs_dict = {}
  8379. no_ststs_dict["global_ststs"] = {}
  8380. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8381. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8382. App.log.debug("Checking for updates @ %s" % full_url)
  8383. # ## Get the data
  8384. try:
  8385. f = urllib.request.urlopen(full_url)
  8386. except Exception:
  8387. # App.log.warning("Failed checking for latest version. Could not connect.")
  8388. self.log.warning("Failed checking for latest version. Could not connect.")
  8389. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8390. return
  8391. try:
  8392. data = json.load(f)
  8393. except Exception as e:
  8394. App.log.error("Could not parse information about latest version.")
  8395. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8396. App.log.debug("json.load(): %s" % str(e))
  8397. f.close()
  8398. return
  8399. f.close()
  8400. # ## Latest version?
  8401. if self.version >= data["version"]:
  8402. App.log.debug("FlatCAM is up to date!")
  8403. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8404. return
  8405. App.log.debug("Newer version available.")
  8406. self.message.emit(
  8407. _("Newer Version Available"),
  8408. '%s<br><br>><b>%s</b><br>%s' % (
  8409. _("There is a newer version of FlatCAM available for download:"),
  8410. str(data["name"]),
  8411. str(data["message"])
  8412. ),
  8413. _("info")
  8414. )
  8415. def on_plotcanvas_setup(self, container=None):
  8416. """
  8417. This is doing the setup for the plot area (canvas).
  8418. :param container: QT Widget where to install the canvas
  8419. :return: None
  8420. """
  8421. if container:
  8422. plot_container = container
  8423. else:
  8424. plot_container = self.ui.right_layout
  8425. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8426. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8427. self.is_legacy = True
  8428. self.defaults["global_graphic_engine"] = "2D"
  8429. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8430. else:
  8431. try:
  8432. self.plotcanvas = PlotCanvas(plot_container, self)
  8433. except Exception as er:
  8434. msg_txt = traceback.format_exc()
  8435. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8436. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8437. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8438. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8439. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8440. msg += msg_txt
  8441. self.inform.emit(msg)
  8442. return 'fail'
  8443. # So it can receive key presses
  8444. self.plotcanvas.native.setFocus()
  8445. if self.is_legacy is False:
  8446. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8447. # Set the mouse button for panning
  8448. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8449. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8450. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8451. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8452. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8453. # Keys over plot enabled
  8454. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8455. if self.defaults['global_cursor_type'] == 'small':
  8456. self.app_cursor = self.plotcanvas.new_cursor()
  8457. else:
  8458. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8459. if self.ui.grid_snap_btn.isChecked():
  8460. self.app_cursor.enabled = True
  8461. else:
  8462. self.app_cursor.enabled = False
  8463. if self.is_legacy is False:
  8464. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8465. else:
  8466. # will use the default Matplotlib axes
  8467. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8468. def on_zoom_fit(self, event):
  8469. """
  8470. Callback for zoom-fit request. This can be either from the corresponding
  8471. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8472. with axes limits from the geometry bounds of all objects.
  8473. :param event: Ignored.
  8474. :return: None
  8475. """
  8476. if self.is_legacy is False:
  8477. self.plotcanvas.fit_view()
  8478. else:
  8479. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8480. width = xmax - xmin
  8481. height = ymax - ymin
  8482. xmin -= 0.05 * width
  8483. xmax += 0.05 * width
  8484. ymin -= 0.05 * height
  8485. ymax += 0.05 * height
  8486. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8487. def on_zoom_in(self):
  8488. """
  8489. Callback for zoom-in request.
  8490. :return:
  8491. """
  8492. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8493. def on_zoom_out(self):
  8494. """
  8495. Callback for zoom-out request.
  8496. :return:
  8497. """
  8498. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8499. def disable_all_plots(self):
  8500. self.defaults.report_usage("disable_all_plots()")
  8501. self.disable_plots(self.collection.get_list())
  8502. self.inform.emit('[success] %s' %
  8503. _("All plots disabled."))
  8504. def disable_other_plots(self):
  8505. self.defaults.report_usage("disable_other_plots()")
  8506. self.disable_plots(self.collection.get_non_selected())
  8507. self.inform.emit('[success] %s' %
  8508. _("All non selected plots disabled."))
  8509. def enable_all_plots(self):
  8510. self.defaults.report_usage("enable_all_plots()")
  8511. self.enable_plots(self.collection.get_list())
  8512. self.inform.emit('[success] %s' %
  8513. _("All plots enabled."))
  8514. def on_enable_sel_plots(self):
  8515. log.debug("App.on_enable_sel_plot()")
  8516. object_list = self.collection.get_selected()
  8517. self.enable_plots(objects=object_list)
  8518. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8519. def on_disable_sel_plots(self):
  8520. log.debug("App.on_disable_sel_plot()")
  8521. # self.inform.emit(_("Disabling plots ..."))
  8522. object_list = self.collection.get_selected()
  8523. self.disable_plots(objects=object_list)
  8524. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8525. def enable_plots(self, objects):
  8526. """
  8527. Enable plots
  8528. :param objects: list of Objects to be enabled
  8529. :return:
  8530. """
  8531. log.debug("Enabling plots ...")
  8532. # self.inform.emit(_("Working ..."))
  8533. for obj in objects:
  8534. if obj.options['plot'] is False:
  8535. obj.options.set_change_callback(lambda x: None)
  8536. obj.options['plot'] = True
  8537. try:
  8538. # only the Gerber obj has on_plot_cb_click() method
  8539. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8540. # disable this cb while disconnected,
  8541. # in case the operation takes time the user is not allowed to change it
  8542. obj.ui.plot_cb.setDisabled(True)
  8543. except AttributeError:
  8544. pass
  8545. obj.set_form_item("plot")
  8546. try:
  8547. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8548. obj.ui.plot_cb.setDisabled(False)
  8549. except AttributeError:
  8550. pass
  8551. obj.options.set_change_callback(obj.on_options_change)
  8552. def worker_task(objs):
  8553. with self.proc_container.new(_("Enabling plots ...")):
  8554. for plot_obj in objs:
  8555. # obj.options['plot'] = True
  8556. if isinstance(plot_obj, CNCJobObject):
  8557. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8558. else:
  8559. plot_obj.plot(visible=True)
  8560. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8561. # self.plots_updated.emit()
  8562. def disable_plots(self, objects):
  8563. """
  8564. Disables plots
  8565. :param objects: list of Objects to be disabled
  8566. :return:
  8567. """
  8568. # if no objects selected then do nothing
  8569. if not self.collection.get_selected():
  8570. return
  8571. log.debug("Disabling plots ...")
  8572. # self.inform.emit(_("Working ..."))
  8573. for obj in objects:
  8574. if obj.options['plot'] is True:
  8575. obj.options.set_change_callback(lambda x: None)
  8576. obj.options['plot'] = False
  8577. try:
  8578. # only the Gerber obj has on_plot_cb_click() method
  8579. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8580. obj.ui.plot_cb.setDisabled(True)
  8581. except AttributeError:
  8582. pass
  8583. obj.set_form_item("plot")
  8584. try:
  8585. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8586. obj.ui.plot_cb.setDisabled(False)
  8587. except AttributeError:
  8588. pass
  8589. obj.options.set_change_callback(obj.on_options_change)
  8590. try:
  8591. self.delete_selection_shape()
  8592. except Exception as e:
  8593. log.debug("App.disable_plots() --> %s" % str(e))
  8594. # self.plots_updated.emit()
  8595. def worker_task(objs):
  8596. with self.proc_container.new(_("Disabling plots ...")):
  8597. for plot_obj in objs:
  8598. # obj.options['plot'] = True
  8599. if isinstance(plot_obj, CNCJobObject):
  8600. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8601. else:
  8602. plot_obj.plot(visible=False)
  8603. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8604. def toggle_plots(self, objects):
  8605. """
  8606. Toggle plots visibility
  8607. :param objects: list of Objects for which to be toggled the visibility
  8608. :return: None
  8609. """
  8610. # if no objects selected then do nothing
  8611. if not self.collection.get_selected():
  8612. return
  8613. log.debug("Toggling plots ...")
  8614. self.inform.emit(_("Working ..."))
  8615. for obj in objects:
  8616. if obj.options['plot'] is False:
  8617. obj.options['plot'] = True
  8618. else:
  8619. obj.options['plot'] = False
  8620. self.plots_updated.emit()
  8621. def clear_plots(self):
  8622. """
  8623. Clear the plots
  8624. :return: None
  8625. """
  8626. objects = self.collection.get_list()
  8627. for obj in objects:
  8628. obj.clear(obj == objects[-1])
  8629. # Clear pool to free memory
  8630. self.clear_pool()
  8631. def on_set_color_action_triggered(self):
  8632. """
  8633. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8634. :return:
  8635. """
  8636. new_color = self.defaults['gerber_plot_fill']
  8637. clicked_action = self.sender()
  8638. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8639. act_name = clicked_action.text()
  8640. sel_obj_list = self.collection.get_selected()
  8641. if not sel_obj_list:
  8642. return
  8643. # a default value, I just chose this one
  8644. alpha_level = 'BF'
  8645. for sel_obj in sel_obj_list:
  8646. if sel_obj.kind == 'excellon':
  8647. alpha_level = str(hex(
  8648. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8649. elif sel_obj.kind == 'gerber':
  8650. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8651. elif sel_obj.kind == 'geometry':
  8652. alpha_level = 'FF'
  8653. else:
  8654. log.debug(
  8655. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8656. continue
  8657. sel_obj.alpha_level = alpha_level
  8658. if act_name == _('Red'):
  8659. new_color = '#FF0000' + alpha_level
  8660. if act_name == _('Blue'):
  8661. new_color = '#0000FF' + alpha_level
  8662. if act_name == _('Yellow'):
  8663. new_color = '#FFDF00' + alpha_level
  8664. if act_name == _('Green'):
  8665. new_color = '#00FF00' + alpha_level
  8666. if act_name == _('Purple'):
  8667. new_color = '#FF00FF' + alpha_level
  8668. if act_name == _('Brown'):
  8669. new_color = '#A52A2A' + alpha_level
  8670. if act_name == _('White'):
  8671. new_color = '#FFFFFF' + alpha_level
  8672. if act_name == _('Black'):
  8673. new_color = '#000000' + alpha_level
  8674. if act_name == _('Custom'):
  8675. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8676. c_dialog = QtWidgets.QColorDialog()
  8677. plot_fill_color = c_dialog.getColor(initial=new_color)
  8678. if plot_fill_color.isValid() is False:
  8679. return
  8680. new_color = str(plot_fill_color.name()) + alpha_level
  8681. if act_name == _("Default"):
  8682. for sel_obj in sel_obj_list:
  8683. if sel_obj.kind == 'excellon':
  8684. new_color = self.defaults['excellon_plot_fill']
  8685. new_line_color = self.defaults['excellon_plot_line']
  8686. elif sel_obj.kind == 'gerber':
  8687. new_color = self.defaults['gerber_plot_fill']
  8688. new_line_color = self.defaults['gerber_plot_line']
  8689. elif sel_obj.kind == 'geometry':
  8690. new_color = self.defaults['geometry_plot_line']
  8691. new_line_color = self.defaults['geometry_plot_line']
  8692. else:
  8693. log.debug(
  8694. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8695. continue
  8696. sel_obj.fill_color = new_color
  8697. sel_obj.outline_color = new_line_color
  8698. sel_obj.shapes.redraw(
  8699. update_colors=(new_color, new_line_color)
  8700. )
  8701. return
  8702. if act_name == _("Opacity"):
  8703. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8704. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8705. if ok_button:
  8706. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8707. for sel_obj in sel_obj_list:
  8708. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8709. sel_obj.shapes.redraw(
  8710. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8711. )
  8712. return
  8713. new_line_color = color_variant(new_color[:7], 0.7)
  8714. if act_name == _("White"):
  8715. new_line_color = color_variant("#dedede", 0.7)
  8716. for sel_obj in sel_obj_list:
  8717. sel_obj.fill_color = new_color
  8718. sel_obj.outline_color = new_line_color
  8719. sel_obj.shapes.redraw(
  8720. update_colors=(new_color, new_line_color)
  8721. )
  8722. def generate_cnc_job(self, objects):
  8723. """
  8724. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8725. :param objects: Selected objects in the Project Tab
  8726. :return:
  8727. """
  8728. self.defaults.report_usage("generate_cnc_job()")
  8729. # for obj in objects:
  8730. # obj.generatecncjob()
  8731. for obj in objects:
  8732. obj.on_generatecnc_button_click()
  8733. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8734. """
  8735. Saves the current project to the specified file.
  8736. :param filename: Name of the file in which to save.
  8737. :type filename: str
  8738. :param quit_action: if the project saving will be followed by an app quit; boolean
  8739. :param silent: if True will not display status messages
  8740. :param from_tcl True is run from Tcl Shell
  8741. :return: None
  8742. """
  8743. self.log.debug("save_project()")
  8744. self.save_in_progress = True
  8745. with self.proc_container.new(_("Saving FlatCAM Project")):
  8746. # Capture the latest changes
  8747. # Current object
  8748. try:
  8749. current_object = self.collection.get_active()
  8750. if current_object:
  8751. current_object.read_form()
  8752. except Exception as e:
  8753. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8754. pass
  8755. # Serialize the whole project
  8756. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8757. "options": self.options,
  8758. "version": self.version}
  8759. if self.defaults["global_save_compressed"] is True:
  8760. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8761. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8762. # # Write
  8763. f.write(g)
  8764. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8765. else:
  8766. # Open file
  8767. try:
  8768. f = open(filename, 'w')
  8769. except IOError:
  8770. App.log.error("Failed to open file for saving: %s", filename)
  8771. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8772. return
  8773. # Write
  8774. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8775. f.close()
  8776. # verification of the saved project
  8777. # Open and parse
  8778. try:
  8779. saved_f = open(filename, 'r')
  8780. except IOError:
  8781. if silent is False:
  8782. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8783. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8784. return
  8785. try:
  8786. saved_d = json.load(saved_f, object_hook=dict2obj)
  8787. except Exception:
  8788. if silent is False:
  8789. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8790. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8791. f.close()
  8792. return
  8793. saved_f.close()
  8794. if silent is False:
  8795. if 'version' in saved_d:
  8796. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8797. else:
  8798. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8799. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8800. tb_settings = QSettings("Open Source", "FlatCAM")
  8801. lock_state = self.ui.lock_action.isChecked()
  8802. tb_settings.setValue('toolbar_lock', lock_state)
  8803. # This will write the setting to the platform specific storage.
  8804. del tb_settings
  8805. # if quit:
  8806. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8807. # t.start()
  8808. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8809. def start_delayed_quit(self, delay, filename, should_quit=None):
  8810. """
  8811. :param delay: period of checking if project file size is more than zero; in seconds
  8812. :param filename: the name of the project file to be checked periodically for size more than zero
  8813. :param should_quit: if the task finished will be followed by an app quit; boolean
  8814. :return:
  8815. """
  8816. to_quit = should_quit
  8817. self.save_timer = QtCore.QTimer()
  8818. self.save_timer.setInterval(delay)
  8819. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8820. self.save_timer.start()
  8821. def check_project_file_size(self, filename, should_quit=None):
  8822. """
  8823. :param filename: the name of the project file to be checked periodically for size more than zero
  8824. :param should_quit: will quit the app if True; boolean
  8825. :return:
  8826. """
  8827. try:
  8828. if os.stat(filename).st_size > 0:
  8829. self.save_in_progress = False
  8830. self.save_timer.stop()
  8831. if should_quit:
  8832. self.app_quit.emit()
  8833. except Exception:
  8834. traceback.print_exc()
  8835. def save_project_auto(self):
  8836. """
  8837. Called periodically to save the project.
  8838. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  8839. # progress.
  8840. :return:
  8841. """
  8842. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8843. self.on_file_saveproject()
  8844. def save_project_auto_update(self):
  8845. """
  8846. Update the auto save time interval value.
  8847. :return:
  8848. """
  8849. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8850. try:
  8851. if self.autosave_timer.isActive():
  8852. self.autosave_timer.stop()
  8853. except Exception:
  8854. pass
  8855. if self.defaults['global_autosave'] is True:
  8856. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8857. self.autosave_timer.start()
  8858. def on_options_app2project(self):
  8859. """
  8860. Callback for Options->Transfer Options->App=>Project. Copies options
  8861. from application defaults to project defaults.
  8862. :return: None
  8863. """
  8864. self.defaults.report_usage("on_options_app2project")
  8865. self.preferencesUiManager.defaults_read_form()
  8866. self.options.update(self.defaults)
  8867. def toggle_shell(self):
  8868. """
  8869. Toggle shell: if is visible close it, if it is closed then open it
  8870. :return: None
  8871. """
  8872. self.defaults.report_usage("toggle_shell()")
  8873. if self.ui.shell_dock.isVisible():
  8874. self.ui.shell_dock.hide()
  8875. self.plotcanvas.native.setFocus()
  8876. else:
  8877. self.ui.shell_dock.show()
  8878. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8879. # self.shell._edit.setFocus()
  8880. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8881. # HACK - simulate a mouse click - alternative
  8882. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8883. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8884. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8885. # no_km)
  8886. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8887. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8888. # no_km)
  8889. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8890. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8891. """
  8892. Shows a message on the FlatCAM Shell
  8893. :param msg: Message to display.
  8894. :param show: Opens the shell.
  8895. :param error: Shows the message as an error.
  8896. :param warning: Shows the message as an warning.
  8897. :param success: Shows the message as an success.
  8898. :param selected: Indicate that something was selected on canvas
  8899. :return: None
  8900. """
  8901. if show:
  8902. self.ui.shell_dock.show()
  8903. try:
  8904. if error:
  8905. self.shell.append_error(msg + "\n")
  8906. elif warning:
  8907. self.shell.append_warning(msg + "\n")
  8908. elif success:
  8909. self.shell.append_success(msg + "\n")
  8910. elif selected:
  8911. self.shell.append_selected(msg + "\n")
  8912. else:
  8913. self.shell.append_output(msg + "\n")
  8914. except AttributeError:
  8915. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8916. class ArgsThread(QtCore.QObject):
  8917. open_signal = pyqtSignal(list)
  8918. start = pyqtSignal()
  8919. stop = pyqtSignal()
  8920. if sys.platform == 'win32':
  8921. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8922. else:
  8923. address = ('/tmp/testipc', 'AF_UNIX')
  8924. def __init__(self):
  8925. super(ArgsThread, self).__init__()
  8926. self.listener = None
  8927. self.thread_exit = False
  8928. self.start.connect(self.run)
  8929. self.stop.connect(self.close_listener)
  8930. def my_loop(self, address):
  8931. try:
  8932. self.listener = Listener(*address)
  8933. while self.thread_exit is False:
  8934. conn = self.listener.accept()
  8935. self.serve(conn)
  8936. except socket.error:
  8937. try:
  8938. conn = Client(*address)
  8939. conn.send(sys.argv)
  8940. conn.send('close')
  8941. # close the current instance only if there are args
  8942. if len(sys.argv) > 1:
  8943. try:
  8944. self.listener.close()
  8945. except Exception:
  8946. pass
  8947. sys.exit()
  8948. except ConnectionRefusedError:
  8949. if sys.platform == 'win32':
  8950. pass
  8951. else:
  8952. os.system('rm /tmp/testipc')
  8953. self.listener = Listener(*address)
  8954. while True:
  8955. conn = self.listener.accept()
  8956. self.serve(conn)
  8957. def serve(self, conn):
  8958. while self.thread_exit is False:
  8959. msg = conn.recv()
  8960. if msg == 'close':
  8961. break
  8962. self.open_signal.emit(msg)
  8963. conn.close()
  8964. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8965. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8966. @pyqtSlot()
  8967. def run(self):
  8968. self.my_loop(self.address)
  8969. @pyqtSlot()
  8970. def close_listener(self):
  8971. self.thread_exit = True
  8972. self.listener.close()
  8973. # end of file