FlatCAMApp.py 482 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864
  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. App.log.info("FlatCAM Starting...")
  229. self.main_thread = QtWidgets.QApplication.instance().thread()
  230. # ############################################################################################################
  231. # ################# Setup the listening thread for another instance launching with args ######################
  232. # ############################################################################################################
  233. if sys.platform == 'win32' or sys.platform == 'linux':
  234. # make sure the thread is stored by using a self. otherwise it's garbage collected
  235. self.th = QtCore.QThread()
  236. self.th.start(priority=QtCore.QThread.LowestPriority)
  237. self.new_launch = ArgsThread()
  238. self.new_launch.open_signal[list].connect(self.on_startup_args)
  239. self.new_launch.moveToThread(self.th)
  240. self.new_launch.start.emit()
  241. # ############################################################################################################
  242. # # ######################################## OS-specific #####################################################
  243. # ############################################################################################################
  244. portable = False
  245. # Folder for user settings.
  246. if sys.platform == 'win32':
  247. if platform.architecture()[0] == '32bit':
  248. App.log.debug("Win32!")
  249. else:
  250. App.log.debug("Win64!")
  251. # #######################################################################################################
  252. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  253. # #######################################################################################################
  254. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  255. try:
  256. with open(config_file, 'r'):
  257. pass
  258. except FileNotFoundError:
  259. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  260. try:
  261. with open(config_file, 'r') as f:
  262. try:
  263. for line in f:
  264. param = str(line).replace('\n', '').rpartition('=')
  265. if param[0] == 'portable':
  266. try:
  267. portable = eval(param[2])
  268. except NameError:
  269. portable = False
  270. if param[0] == 'headless':
  271. if param[2].lower() == 'true':
  272. self.cmd_line_headless = 1
  273. else:
  274. self.cmd_line_headless = None
  275. except Exception as e:
  276. log.debug('App.__init__() -->%s' % str(e))
  277. return
  278. except FileNotFoundError as e:
  279. log.debug(str(e))
  280. pass
  281. if portable is False:
  282. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  283. else:
  284. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  285. self.os = 'windows'
  286. else: # Linux/Unix/MacOS
  287. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  288. self.os = 'unix'
  289. # ############################################################################################################
  290. # ################################# Setup folders and files ##################################################
  291. # ############################################################################################################
  292. if not os.path.exists(self.data_path):
  293. os.makedirs(self.data_path)
  294. App.log.debug('Created data folder: ' + self.data_path)
  295. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  296. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  297. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  298. if not os.path.exists(self.preprocessorpaths):
  299. os.makedirs(self.preprocessorpaths)
  300. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  301. # create geo_tools_db.FlatDB file if there is none
  302. try:
  303. f = open(self.data_path + '/geo_tools_db.FlatDB')
  304. f.close()
  305. except IOError:
  306. App.log.debug('Creating empty geo_tool_db.FlatDB')
  307. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  308. json.dump({}, f)
  309. f.close()
  310. # create current_defaults.FlatConfig file if there is none
  311. try:
  312. f = open(self.data_path + '/current_defaults.FlatConfig')
  313. f.close()
  314. except IOError:
  315. App.log.debug('Creating empty current_defaults.FlatConfig')
  316. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  317. json.dump({}, f)
  318. f.close()
  319. # Write factory_defaults.FlatConfig file to disk
  320. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  321. # create a recent files json file if there is none
  322. try:
  323. f = open(self.data_path + '/recent.json')
  324. f.close()
  325. except IOError:
  326. App.log.debug('Creating empty recent.json')
  327. f = open(self.data_path + '/recent.json', 'w')
  328. json.dump([], f)
  329. f.close()
  330. # create a recent projects json file if there is none
  331. try:
  332. fp = open(self.data_path + '/recent_projects.json')
  333. fp.close()
  334. except IOError:
  335. App.log.debug('Creating empty recent_projects.json')
  336. fp = open(self.data_path + '/recent_projects.json', 'w')
  337. json.dump([], fp)
  338. fp.close()
  339. # Application directory. CHDIR to it. Otherwise, trying to load
  340. # GUI icons will fail as their path is relative.
  341. # This will fail under cx_freeze ...
  342. self.app_home = os.path.dirname(os.path.realpath(__file__))
  343. App.log.debug("Application path is " + self.app_home)
  344. App.log.debug("Started in " + os.getcwd())
  345. # cx_freeze workaround
  346. if os.path.isfile(self.app_home):
  347. self.app_home = os.path.dirname(self.app_home)
  348. os.chdir(self.app_home)
  349. # ############################################################################################################
  350. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  351. # ############################################################################################################
  352. self.defaults = FlatCAMDefaults()
  353. self.defaults["root_folder_path"] = self.app_home
  354. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  355. if user_defaults:
  356. self.defaults.load(filename=current_defaults_path)
  357. if self.defaults['units'] == 'MM':
  358. self.decimals = int(self.defaults['decimals_metric'])
  359. else:
  360. self.decimals = int(self.defaults['decimals_inch'])
  361. if self.defaults["global_gray_icons"] is False:
  362. self.resource_location = 'assets/resources'
  363. else:
  364. self.resource_location = 'assets/resources/dark_resources'
  365. self.current_units = self.defaults['units']
  366. # ###########################################################################################################
  367. # #################################### SETUP OBJECT CLASSES #################################################
  368. # ###########################################################################################################
  369. self.setup_obj_classes()
  370. # ###########################################################################################################
  371. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  372. # ###########################################################################################################
  373. self.pool = Pool()
  374. # ###########################################################################################################
  375. # ###################################### Setting the Splash Screen ##########################################
  376. # ###########################################################################################################
  377. splash_settings = QSettings("Open Source", "FlatCAM")
  378. if splash_settings.contains("splash_screen"):
  379. show_splash = splash_settings.value("splash_screen")
  380. else:
  381. splash_settings.setValue('splash_screen', 1)
  382. # This will write the setting to the platform specific storage.
  383. del splash_settings
  384. show_splash = 1
  385. if show_splash and self.cmd_line_headless != 1:
  386. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  387. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  388. # self.splash.setMask(splash_pix.mask())
  389. # move splashscreen to the current monitor
  390. desktop = QtWidgets.QApplication.desktop()
  391. screen = desktop.screenNumber(QtGui.QCursor.pos())
  392. current_screen_center = desktop.availableGeometry(screen).center()
  393. self.splash.move(current_screen_center - self.splash.rect().center())
  394. self.splash.show()
  395. self.splash.showMessage(_("FlatCAM is initializing ..."),
  396. alignment=Qt.AlignBottom | Qt.AlignLeft,
  397. color=QtGui.QColor("gray"))
  398. else:
  399. show_splash = 0
  400. # ###########################################################################################################
  401. # ######################################### Initialize GUI ##################################################
  402. # ###########################################################################################################
  403. # FlatCAM colors used in plotting
  404. self.FC_light_green = '#BBF268BF'
  405. self.FC_dark_green = '#006E20BF'
  406. self.FC_light_blue = '#a5a5ffbf'
  407. self.FC_dark_blue = '#0000ffbf'
  408. QtCore.QObject.__init__(self)
  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 position label
  4404. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4405. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4406. # Set the relative position label
  4407. dx = location[0] - float(self.rel_point1[0])
  4408. dy = location[1] - float(self.rel_point1[1])
  4409. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4410. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4411. self.inform.emit('[success] %s' % _("Done."))
  4412. return location
  4413. def on_locate(self, obj, fit_center=True):
  4414. """
  4415. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4416. :param obj: The object on which to locate certain points
  4417. :param fit_center: If to fit view. Boolean.
  4418. :return: A point location. (x, y) tuple.
  4419. """
  4420. self.defaults.report_usage("on_locate()")
  4421. if obj is None:
  4422. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4423. return 'fail'
  4424. class DialogBoxChoice(QtWidgets.QDialog):
  4425. def __init__(self, title=None, icon=None, choice='bl'):
  4426. """
  4427. :param title: string with the window title
  4428. """
  4429. super(DialogBoxChoice, self).__init__()
  4430. self.ok = False
  4431. self.setWindowIcon(icon)
  4432. self.setWindowTitle(str(title))
  4433. self.form = QtWidgets.QFormLayout(self)
  4434. self.ref_radio = RadioSet([
  4435. {"label": _("Bottom-Left"), "value": "bl"},
  4436. {"label": _("Top-Left"), "value": "tl"},
  4437. {"label": _("Bottom-Right"), "value": "br"},
  4438. {"label": _("Top-Right"), "value": "tr"},
  4439. {"label": _("Center"), "value": "c"}
  4440. ], orientation='vertical', stretch=False)
  4441. self.ref_radio.set_value(choice)
  4442. self.form.addRow(self.ref_radio)
  4443. self.button_box = QtWidgets.QDialogButtonBox(
  4444. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4445. Qt.Horizontal, parent=self)
  4446. self.form.addRow(self.button_box)
  4447. self.button_box.accepted.connect(self.accept)
  4448. self.button_box.rejected.connect(self.reject)
  4449. if self.exec_() == QtWidgets.QDialog.Accepted:
  4450. self.ok = True
  4451. self.location_point = self.ref_radio.get_value()
  4452. else:
  4453. self.ok = False
  4454. self.location_point = None
  4455. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4456. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4457. choice=self.defaults['global_locate_pt'])
  4458. if dia_box.ok is True:
  4459. try:
  4460. location_point = dia_box.location_point
  4461. self.defaults['global_locate_pt'] = dia_box.location_point
  4462. except Exception:
  4463. return
  4464. else:
  4465. return
  4466. loc_b = obj.bounds()
  4467. if location_point == 'bl':
  4468. location = (loc_b[0], loc_b[1])
  4469. elif location_point == 'tl':
  4470. location = (loc_b[0], loc_b[3])
  4471. elif location_point == 'br':
  4472. location = (loc_b[2], loc_b[1])
  4473. elif location_point == 'tr':
  4474. location = (loc_b[2], loc_b[3])
  4475. else:
  4476. # center
  4477. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4478. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4479. location = (cx, cy)
  4480. self.locate_signal.emit(location, location_point)
  4481. if fit_center:
  4482. self.plotcanvas.fit_center(loc=location)
  4483. cursor = QtGui.QCursor()
  4484. if self.is_legacy is False:
  4485. # I don't know where those differences come from but they are constant for the current
  4486. # execution of the application and they are multiples of a value around 0.0263mm.
  4487. # In a random way sometimes they are more sometimes they are less
  4488. # if units == 'MM':
  4489. # cal_factor = 0.0263
  4490. # else:
  4491. # cal_factor = 0.0263 / 25.4
  4492. cal_location = (location[0], location[1])
  4493. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4494. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4495. j_pos = (
  4496. int(canvas_origin.x() + round(jump_loc[0])),
  4497. int(canvas_origin.y() + round(jump_loc[1]))
  4498. )
  4499. cursor.setPos(j_pos[0], j_pos[1])
  4500. else:
  4501. # find the canvas origin which is in the top left corner
  4502. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4503. # determine the coordinates for the lowest left point of the canvas
  4504. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4505. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4506. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4507. # canvas) and the point (width, height) is in the top-right location
  4508. loc = self.plotcanvas.axes.transData.transform_point(location)
  4509. j_pos = (
  4510. int(x0 + loc[0]),
  4511. int(y0 - loc[1])
  4512. )
  4513. cursor.setPos(j_pos[0], j_pos[1])
  4514. self.plotcanvas.mouse = [location[0], location[1]]
  4515. if self.defaults["global_cursor_color_enabled"] is True:
  4516. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4517. else:
  4518. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4519. if self.grid_status():
  4520. # Update cursor
  4521. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4522. symbol='++', edge_color=self.cursor_color_3D,
  4523. edge_width=self.defaults["global_cursor_width"],
  4524. size=self.defaults["global_cursor_size"])
  4525. # Set the position label
  4526. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4527. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4528. # Set the relative position label
  4529. self.dx = location[0] - float(self.rel_point1[0])
  4530. self.dy = location[1] - float(self.rel_point1[1])
  4531. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4532. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4533. self.inform.emit('[success] %s' % _("Done."))
  4534. return location
  4535. def on_copy_command(self):
  4536. """
  4537. Will copy a selection of objects, creating new objects.
  4538. :return:
  4539. """
  4540. self.defaults.report_usage("on_copy_command()")
  4541. def initialize(obj_init, app):
  4542. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4543. try:
  4544. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4545. except AttributeError:
  4546. pass
  4547. try:
  4548. obj_init.apertures = deepcopy(obj.apertures)
  4549. except AttributeError:
  4550. pass
  4551. try:
  4552. if obj.tools:
  4553. obj_init.tools = deepcopy(obj.tools)
  4554. except Exception as err:
  4555. log.debug("App.on_copy_command() --> %s" % str(err))
  4556. try:
  4557. obj_init.source_file = deepcopy(obj.source_file)
  4558. except (AttributeError, TypeError):
  4559. pass
  4560. def initialize_excellon(obj_init, app):
  4561. obj_init.source_file = deepcopy(obj.source_file)
  4562. obj_init.tools = deepcopy(obj.tools)
  4563. # drills are offset, so they need to be deep copied
  4564. obj_init.drills = deepcopy(obj.drills)
  4565. # slots are offset, so they need to be deep copied
  4566. obj_init.slots = deepcopy(obj.slots)
  4567. obj_init.create_geometry()
  4568. def initialize_script(obj_init, app_obj):
  4569. obj_init.source_file = deepcopy(obj.source_file)
  4570. def initialize_document(obj_init, app_obj):
  4571. obj_init.source_file = deepcopy(obj.source_file)
  4572. for obj in self.collection.get_selected():
  4573. obj_name = obj.options["name"]
  4574. try:
  4575. if isinstance(obj, ExcellonObject):
  4576. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4577. elif isinstance(obj, GerberObject):
  4578. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4579. elif isinstance(obj, GeometryObject):
  4580. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4581. elif isinstance(obj, ScriptObject):
  4582. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4583. elif isinstance(obj, DocumentObject):
  4584. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4585. except Exception as e:
  4586. return "Operation failed: %s" % str(e)
  4587. def on_copy_object2(self, custom_name):
  4588. def initialize_geometry(obj_init, app):
  4589. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4590. try:
  4591. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4592. except AttributeError:
  4593. pass
  4594. try:
  4595. obj_init.apertures = deepcopy(obj.apertures)
  4596. except AttributeError:
  4597. pass
  4598. try:
  4599. if obj.tools:
  4600. obj_init.tools = deepcopy(obj.tools)
  4601. except Exception as ee:
  4602. log.debug("on_copy_object2() --> %s" % str(ee))
  4603. def initialize_gerber(obj_init, app):
  4604. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4605. obj_init.apertures = deepcopy(obj.apertures)
  4606. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4607. def initialize_excellon(obj_init, app):
  4608. obj_init.tools = deepcopy(obj.tools)
  4609. # drills are offset, so they need to be deep copied
  4610. obj_init.drills = deepcopy(obj.drills)
  4611. # slots are offset, so they need to be deep copied
  4612. obj_init.slots = deepcopy(obj.slots)
  4613. obj_init.create_geometry()
  4614. for obj in self.collection.get_selected():
  4615. obj_name = obj.options["name"]
  4616. try:
  4617. if isinstance(obj, ExcellonObject):
  4618. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4619. elif isinstance(obj, GerberObject):
  4620. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4621. elif isinstance(obj, GeometryObject):
  4622. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4623. except Exception as er:
  4624. return "Operation failed: %s" % str(er)
  4625. def on_rename_object(self, text):
  4626. """
  4627. Will rename an object.
  4628. :param text: New name for the object.
  4629. :return:
  4630. """
  4631. self.defaults.report_usage("on_rename_object()")
  4632. named_obj = self.collection.get_active()
  4633. for obj in named_obj:
  4634. if obj is list:
  4635. self.on_rename_object(text)
  4636. else:
  4637. try:
  4638. obj.options['name'] = text
  4639. except Exception as e:
  4640. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4641. def convert_any2geo(self):
  4642. """
  4643. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4644. :return:
  4645. """
  4646. self.defaults.report_usage("convert_any2geo()")
  4647. def initialize(obj_init, app):
  4648. obj_init.solid_geometry = obj.solid_geometry
  4649. try:
  4650. obj_init.follow_geometry = obj.follow_geometry
  4651. except AttributeError:
  4652. pass
  4653. try:
  4654. obj_init.apertures = obj.apertures
  4655. except AttributeError:
  4656. pass
  4657. try:
  4658. if obj.tools:
  4659. obj_init.tools = obj.tools
  4660. except AttributeError:
  4661. pass
  4662. def initialize_excellon(obj_init, app):
  4663. # objs = self.collection.get_selected()
  4664. # GeometryObject.merge(objs, obj)
  4665. solid_geo = []
  4666. for tool in obj.tools:
  4667. for geo in obj.tools[tool]['solid_geometry']:
  4668. solid_geo.append(geo)
  4669. obj_init.solid_geometry = deepcopy(solid_geo)
  4670. if not self.collection.get_selected():
  4671. log.warning("App.convert_any2geo --> No object selected")
  4672. self.inform.emit('[WARNING_NOTCL] %s' %
  4673. _("No object is selected. Select an object and try again."))
  4674. return
  4675. for obj in self.collection.get_selected():
  4676. obj_name = obj.options["name"]
  4677. try:
  4678. if isinstance(obj, ExcellonObject):
  4679. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4680. else:
  4681. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4682. except Exception as e:
  4683. return "Operation failed: %s" % str(e)
  4684. def convert_any2gerber(self):
  4685. """
  4686. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4687. :return:
  4688. """
  4689. self.defaults.report_usage("convert_any2gerber()")
  4690. def initialize_geometry(obj_init, app):
  4691. apertures = {}
  4692. apid = 0
  4693. apertures[str(apid)] = {}
  4694. apertures[str(apid)]['geometry'] = []
  4695. for obj_orig in obj.solid_geometry:
  4696. new_elem = {}
  4697. new_elem['solid'] = obj_orig
  4698. try:
  4699. new_elem['follow'] = obj_orig.exterior
  4700. except AttributeError:
  4701. pass
  4702. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4703. apertures[str(apid)]['size'] = 0.0
  4704. apertures[str(apid)]['type'] = 'C'
  4705. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4706. obj_init.apertures = deepcopy(apertures)
  4707. def initialize_excellon(obj_init, app):
  4708. apertures = {}
  4709. apid = 10
  4710. for tool in obj.tools:
  4711. apertures[str(apid)] = {}
  4712. apertures[str(apid)]['geometry'] = []
  4713. for geo in obj.tools[tool]['solid_geometry']:
  4714. new_el = {}
  4715. new_el['solid'] = geo
  4716. new_el['follow'] = geo.exterior
  4717. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4718. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4719. apertures[str(apid)]['type'] = 'C'
  4720. apid += 1
  4721. # create solid_geometry
  4722. solid_geometry = []
  4723. for apid in apertures:
  4724. for geo_el in apertures[apid]['geometry']:
  4725. solid_geometry.append(geo_el['solid'])
  4726. solid_geometry = MultiPolygon(solid_geometry)
  4727. solid_geometry = solid_geometry.buffer(0.0000001)
  4728. obj_init.solid_geometry = deepcopy(solid_geometry)
  4729. obj_init.apertures = deepcopy(apertures)
  4730. # clear the working objects (perhaps not necessary due of Python GC)
  4731. apertures.clear()
  4732. if not self.collection.get_selected():
  4733. log.warning("App.convert_any2gerber --> No object selected")
  4734. self.inform.emit('[WARNING_NOTCL] %s' %
  4735. _("No object is selected. Select an object and try again."))
  4736. return
  4737. for obj in self.collection.get_selected():
  4738. obj_name = obj.options["name"]
  4739. try:
  4740. if isinstance(obj, ExcellonObject):
  4741. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4742. elif isinstance(obj, GeometryObject):
  4743. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4744. else:
  4745. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4746. except Exception as e:
  4747. return "Operation failed: %s" % str(e)
  4748. def abort_all_tasks(self):
  4749. """
  4750. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4751. on the first possible occasion.
  4752. :return:
  4753. """
  4754. if self.abort_flag is False:
  4755. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4756. self.abort_flag = True
  4757. self.cleanup.emit()
  4758. def app_is_idle(self):
  4759. if self.abort_flag:
  4760. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4761. self.abort_flag = False
  4762. def on_selectall(self):
  4763. """
  4764. Will draw a selection box shape around the selected objects.
  4765. :return:
  4766. """
  4767. self.defaults.report_usage("on_selectall()")
  4768. # delete the possible selection box around a possible selected object
  4769. self.delete_selection_shape()
  4770. for name in self.collection.get_names():
  4771. self.collection.set_active(name)
  4772. curr_sel_obj = self.collection.get_by_name(name)
  4773. # create the selection box around the selected object
  4774. if self.defaults['global_selection_shape'] is True:
  4775. self.draw_selection_shape(curr_sel_obj)
  4776. def on_preferences(self):
  4777. """
  4778. Adds the Preferences in a Tab in Plot Area
  4779. :return:
  4780. """
  4781. # add the tab if it was closed
  4782. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4783. # delete the absolute and relative position and messages in the infobar
  4784. self.ui.position_label.setText("")
  4785. self.ui.rel_position_label.setText("")
  4786. # Switch plot_area to preferences page
  4787. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4788. # self.ui.show()
  4789. # detect changes in the preferences
  4790. for idx in range(self.ui.pref_tab_area.count()):
  4791. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4792. try:
  4793. try:
  4794. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4795. except (TypeError, AttributeError):
  4796. pass
  4797. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4798. except AttributeError:
  4799. pass
  4800. try:
  4801. try:
  4802. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4803. except (TypeError, AttributeError):
  4804. pass
  4805. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4806. except AttributeError:
  4807. pass
  4808. try:
  4809. try:
  4810. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4811. except (TypeError, AttributeError):
  4812. pass
  4813. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4814. except AttributeError:
  4815. pass
  4816. try:
  4817. try:
  4818. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4819. except (TypeError, AttributeError):
  4820. pass
  4821. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4822. except AttributeError:
  4823. pass
  4824. try:
  4825. try:
  4826. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4827. except (TypeError, AttributeError):
  4828. pass
  4829. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4830. except AttributeError:
  4831. pass
  4832. def on_tools_database(self, source='app'):
  4833. """
  4834. Adds the Tools Database in a Tab in Plot Area.
  4835. :return:
  4836. """
  4837. for idx in range(self.ui.plot_tab_area.count()):
  4838. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4839. # there can be only one instance of Tools Database at one time
  4840. return
  4841. if source == 'app':
  4842. self.tools_db_tab = ToolsDB2(
  4843. app=self,
  4844. parent=self.ui,
  4845. callback_on_edited=self.on_tools_db_edited,
  4846. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4847. )
  4848. elif source == 'ncc':
  4849. self.tools_db_tab = ToolsDB2(
  4850. app=self,
  4851. parent=self.ui,
  4852. callback_on_edited=self.on_tools_db_edited,
  4853. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4854. )
  4855. elif source == 'paint':
  4856. self.tools_db_tab = ToolsDB2(
  4857. app=self,
  4858. parent=self.ui,
  4859. callback_on_edited=self.on_tools_db_edited,
  4860. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4861. )
  4862. # add the tab if it was closed
  4863. try:
  4864. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4865. self.tools_db_tab.setObjectName("database_tab")
  4866. except Exception as e:
  4867. log.debug("App.on_tools_database() --> %s" % str(e))
  4868. return
  4869. # delete the absolute and relative position and messages in the infobar
  4870. self.ui.position_label.setText("")
  4871. self.ui.rel_position_label.setText("")
  4872. # Switch plot_area to preferences page
  4873. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4874. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4875. self.tools_db_tab.ui_connect()
  4876. def on_tools_db_edited(self):
  4877. """
  4878. Executed whenever a tool is edited in Tools Database.
  4879. Will color the text of the Tools Database tab to Red color.
  4880. :return:
  4881. """
  4882. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4883. for idx in range(self.ui.plot_tab_area.count()):
  4884. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4885. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4886. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4887. self.tools_db_changed_flag = True
  4888. def on_geometry_tool_add_from_db_executed(self, tool):
  4889. """
  4890. Here add the tool from DB in the selected geometry object.
  4891. :return:
  4892. """
  4893. tool_from_db = deepcopy(tool)
  4894. obj = self.collection.get_active()
  4895. if isinstance(obj, GeometryObject):
  4896. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4897. # close the tab and delete it
  4898. for idx in range(self.ui.plot_tab_area.count()):
  4899. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4900. wdg = self.ui.plot_tab_area.widget(idx)
  4901. wdg.deleteLater()
  4902. self.ui.plot_tab_area.removeTab(idx)
  4903. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4904. else:
  4905. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4906. def on_plot_area_tab_closed(self, tab_obj_name):
  4907. """
  4908. Executed whenever a QTab is closed in the Plot Area.
  4909. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4910. :return:
  4911. """
  4912. if tab_obj_name == "preferences_tab":
  4913. self.preferencesUiManager.on_close_preferences_tab()
  4914. elif tab_obj_name == "database_tab":
  4915. # disconnect the signals from the table widget in tab
  4916. self.tools_db_tab.ui_disconnect()
  4917. if self.tools_db_changed_flag is True:
  4918. msgbox = QtWidgets.QMessageBox()
  4919. msgbox.setText(_("One or more Tools are edited.\n"
  4920. "Do you want to update the Tools Database?"))
  4921. msgbox.setWindowTitle(_("Save Tools Database"))
  4922. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4923. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4924. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4925. msgbox.setDefaultButton(bt_yes)
  4926. msgbox.exec_()
  4927. response = msgbox.clickedButton()
  4928. if response == bt_yes:
  4929. self.tools_db_tab.on_save_tools_db()
  4930. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4931. else:
  4932. self.tools_db_changed_flag = False
  4933. self.inform.emit('')
  4934. return
  4935. self.tools_db_tab.deleteLater()
  4936. elif tab_obj_name == "text_editor_tab":
  4937. self.toggle_codeeditor = False
  4938. elif tab_obj_name == "bookmarks_tab":
  4939. self.book_dialog_tab.rebuild_actions()
  4940. self.book_dialog_tab.deleteLater()
  4941. else:
  4942. return
  4943. # def on_plotarea_tab_closed(self, tab_idx):
  4944. # """
  4945. #
  4946. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4947. # :return:
  4948. # """
  4949. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4950. #
  4951. # if widget is not None:
  4952. # widget.deleteLater()
  4953. # self.ui.plot_tab_area.removeTab(tab_idx)
  4954. def on_flipy(self):
  4955. """
  4956. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4957. :return:
  4958. """
  4959. self.defaults.report_usage("on_flipy()")
  4960. obj_list = self.collection.get_selected()
  4961. xminlist = []
  4962. yminlist = []
  4963. xmaxlist = []
  4964. ymaxlist = []
  4965. if not obj_list:
  4966. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4967. else:
  4968. try:
  4969. # first get a bounding box to fit all
  4970. for obj in obj_list:
  4971. xmin, ymin, xmax, ymax = obj.bounds()
  4972. xminlist.append(xmin)
  4973. yminlist.append(ymin)
  4974. xmaxlist.append(xmax)
  4975. ymaxlist.append(ymax)
  4976. # get the minimum x,y and maximum x,y for all objects selected
  4977. xminimal = min(xminlist)
  4978. yminimal = min(yminlist)
  4979. xmaximal = max(xmaxlist)
  4980. ymaximal = max(ymaxlist)
  4981. px = 0.5 * (xminimal + xmaximal)
  4982. py = 0.5 * (yminimal + ymaximal)
  4983. # execute mirroring
  4984. for obj in obj_list:
  4985. obj.mirror('X', [px, py])
  4986. obj.plot()
  4987. self.object_changed.emit(obj)
  4988. self.inform.emit('[success] %s' %
  4989. _("Flip on Y axis done."))
  4990. except Exception as e:
  4991. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4992. return
  4993. def on_flipx(self):
  4994. """
  4995. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4996. :return:
  4997. """
  4998. self.defaults.report_usage("on_flipx()")
  4999. obj_list = self.collection.get_selected()
  5000. xminlist = []
  5001. yminlist = []
  5002. xmaxlist = []
  5003. ymaxlist = []
  5004. if not obj_list:
  5005. self.inform.emit('[WARNING_NOTCL] %s' %
  5006. _("No object selected to Flip on X axis."))
  5007. else:
  5008. try:
  5009. # first get a bounding box to fit all
  5010. for obj in obj_list:
  5011. xmin, ymin, xmax, ymax = obj.bounds()
  5012. xminlist.append(xmin)
  5013. yminlist.append(ymin)
  5014. xmaxlist.append(xmax)
  5015. ymaxlist.append(ymax)
  5016. # get the minimum x,y and maximum x,y for all objects selected
  5017. xminimal = min(xminlist)
  5018. yminimal = min(yminlist)
  5019. xmaximal = max(xmaxlist)
  5020. ymaximal = max(ymaxlist)
  5021. px = 0.5 * (xminimal + xmaximal)
  5022. py = 0.5 * (yminimal + ymaximal)
  5023. # execute mirroring
  5024. for obj in obj_list:
  5025. obj.mirror('Y', [px, py])
  5026. obj.plot()
  5027. self.object_changed.emit(obj)
  5028. self.inform.emit('[success] %s' %
  5029. _("Flip on X axis done."))
  5030. except Exception as e:
  5031. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5032. return
  5033. def on_rotate(self, silent=False, preset=None):
  5034. """
  5035. Executed when Options -> Rotate Selection menu entry is clicked.
  5036. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5037. :param preset: A value to be used as predefined angle for rotation.
  5038. :return:
  5039. """
  5040. self.defaults.report_usage("on_rotate()")
  5041. obj_list = self.collection.get_selected()
  5042. xminlist = []
  5043. yminlist = []
  5044. xmaxlist = []
  5045. ymaxlist = []
  5046. if not obj_list:
  5047. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5048. else:
  5049. if silent is False:
  5050. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5051. min=-360, max=360, decimals=4,
  5052. init_val=float(self.defaults['tools_transform_rotate']))
  5053. num, ok = rotatebox.get_value()
  5054. else:
  5055. num = preset
  5056. ok = True
  5057. if ok:
  5058. try:
  5059. # first get a bounding box to fit all
  5060. for obj in obj_list:
  5061. xmin, ymin, xmax, ymax = obj.bounds()
  5062. xminlist.append(xmin)
  5063. yminlist.append(ymin)
  5064. xmaxlist.append(xmax)
  5065. ymaxlist.append(ymax)
  5066. # get the minimum x,y and maximum x,y for all objects selected
  5067. xminimal = min(xminlist)
  5068. yminimal = min(yminlist)
  5069. xmaximal = max(xmaxlist)
  5070. ymaximal = max(ymaxlist)
  5071. px = 0.5 * (xminimal + xmaximal)
  5072. py = 0.5 * (yminimal + ymaximal)
  5073. for sel_obj in obj_list:
  5074. sel_obj.rotate(-float(num), point=(px, py))
  5075. sel_obj.plot()
  5076. self.object_changed.emit(sel_obj)
  5077. self.inform.emit('[success] %s' %
  5078. _("Rotation done."))
  5079. except Exception as e:
  5080. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5081. return
  5082. def on_skewx(self):
  5083. """
  5084. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5085. :return:
  5086. """
  5087. self.defaults.report_usage("on_skewx()")
  5088. obj_list = self.collection.get_selected()
  5089. xminlist = []
  5090. yminlist = []
  5091. if not obj_list:
  5092. self.inform.emit('[WARNING_NOTCL] %s' %
  5093. _("No object selected to Skew/Shear on X axis."))
  5094. else:
  5095. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5096. min=-360, max=360, decimals=4,
  5097. init_val=float(self.defaults['tools_transform_skew_x']))
  5098. num, ok = skewxbox.get_value()
  5099. if ok:
  5100. # first get a bounding box to fit all
  5101. for obj in obj_list:
  5102. xmin, ymin, xmax, ymax = obj.bounds()
  5103. xminlist.append(xmin)
  5104. yminlist.append(ymin)
  5105. # get the minimum x,y and maximum x,y for all objects selected
  5106. xminimal = min(xminlist)
  5107. yminimal = min(yminlist)
  5108. for obj in obj_list:
  5109. obj.skew(num, 0, point=(xminimal, yminimal))
  5110. obj.plot()
  5111. self.object_changed.emit(obj)
  5112. self.inform.emit('[success] %s' %
  5113. _("Skew on X axis done."))
  5114. def on_skewy(self):
  5115. """
  5116. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5117. :return:
  5118. """
  5119. self.defaults.report_usage("on_skewy()")
  5120. obj_list = self.collection.get_selected()
  5121. xminlist = []
  5122. yminlist = []
  5123. if not obj_list:
  5124. self.inform.emit('[WARNING_NOTCL] %s' %
  5125. _("No object selected to Skew/Shear on Y axis."))
  5126. else:
  5127. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5128. min=-360, max=360, decimals=4,
  5129. init_val=float(self.defaults['tools_transform_skew_y']))
  5130. num, ok = skewybox.get_value()
  5131. if ok:
  5132. # first get a bounding box to fit all
  5133. for obj in obj_list:
  5134. xmin, ymin, xmax, ymax = obj.bounds()
  5135. xminlist.append(xmin)
  5136. yminlist.append(ymin)
  5137. # get the minimum x,y and maximum x,y for all objects selected
  5138. xminimal = min(xminlist)
  5139. yminimal = min(yminlist)
  5140. for obj in obj_list:
  5141. obj.skew(0, num, point=(xminimal, yminimal))
  5142. obj.plot()
  5143. self.object_changed.emit(obj)
  5144. self.inform.emit('[success] %s' %
  5145. _("Skew on Y axis done."))
  5146. def on_plots_updated(self):
  5147. """
  5148. Callback used to report when the plots have changed.
  5149. Adjust axes and zooms to fit.
  5150. :return: None
  5151. """
  5152. if self.is_legacy is False:
  5153. self.plotcanvas.update()
  5154. else:
  5155. self.plotcanvas.auto_adjust_axes()
  5156. self.on_zoom_fit(None)
  5157. self.collection.update_view()
  5158. # self.inform.emit(_("Plots updated ..."))
  5159. def on_toolbar_replot(self):
  5160. """
  5161. Callback for toolbar button. Re-plots all objects.
  5162. :return: None
  5163. """
  5164. self.defaults.report_usage("on_toolbar_replot")
  5165. self.log.debug("on_toolbar_replot()")
  5166. try:
  5167. self.collection.get_active().read_form()
  5168. except AttributeError:
  5169. self.log.debug("on_toolbar_replot(): AttributeError")
  5170. pass
  5171. self.plot_all()
  5172. def on_row_activated(self, index):
  5173. if index.isValid():
  5174. if index.internalPointer().parent_item != self.collection.root_item:
  5175. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5176. self.collection.on_item_activated(index)
  5177. def on_row_selected(self, obj_name):
  5178. """
  5179. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5180. It mean we clicked outside of the items and deselected all
  5181. :param obj_name:
  5182. :return:
  5183. """
  5184. if obj_name == 'none':
  5185. for act in self.ui.menuobjects.actions():
  5186. act.setChecked(False)
  5187. return
  5188. # get the name of the selected objects and add them to a list
  5189. name_list = []
  5190. for obj in self.collection.get_selected():
  5191. name_list.append(obj.options['name'])
  5192. # set all actions as unchecked but the ones selected make them checked
  5193. for act in self.ui.menuobjects.actions():
  5194. act.setChecked(False)
  5195. if act.text() in name_list:
  5196. act.setChecked(True)
  5197. def on_collection_updated(self, obj, state, old_name):
  5198. """
  5199. Create a menu from the object loaded in the collection.
  5200. :param obj: object that was changed (added, deleted, renamed)
  5201. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5202. :param old_name: the old name of the object before the action that triggered this slot happened
  5203. :return: None
  5204. """
  5205. icon_files = {
  5206. "gerber": self.resource_location + "/flatcam_icon16.png",
  5207. "excellon": self.resource_location + "/drill16.png",
  5208. "cncjob": self.resource_location + "/cnc16.png",
  5209. "geometry": self.resource_location + "/geometry16.png",
  5210. "script": self.resource_location + "/script_new16.png",
  5211. "document": self.resource_location + "/notes16_1.png"
  5212. }
  5213. if state == 'append':
  5214. for act in self.ui.menuobjects.actions():
  5215. try:
  5216. act.triggered.disconnect()
  5217. except TypeError:
  5218. pass
  5219. self.ui.menuobjects.clear()
  5220. gerber_list = []
  5221. exc_list = []
  5222. cncjob_list = []
  5223. geo_list = []
  5224. script_list = []
  5225. doc_list = []
  5226. for name in self.collection.get_names():
  5227. obj_named = self.collection.get_by_name(name)
  5228. if obj_named.kind == 'gerber':
  5229. gerber_list.append(name)
  5230. elif obj_named.kind == 'excellon':
  5231. exc_list.append(name)
  5232. elif obj_named.kind == 'cncjob':
  5233. cncjob_list.append(name)
  5234. elif obj_named.kind == 'geometry':
  5235. geo_list.append(name)
  5236. elif obj_named.kind == 'script':
  5237. script_list.append(name)
  5238. elif obj_named.kind == 'document':
  5239. doc_list.append(name)
  5240. def add_act(o_name):
  5241. obj_for_icon = self.collection.get_by_name(o_name)
  5242. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5243. add_action.setCheckable(True)
  5244. add_action.setText(o_name)
  5245. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5246. add_action.triggered.connect(
  5247. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5248. self.collection.set_inactive(o_name))
  5249. self.ui.menuobjects.addAction(add_action)
  5250. for name in gerber_list:
  5251. add_act(name)
  5252. self.ui.menuobjects.addSeparator()
  5253. for name in exc_list:
  5254. add_act(name)
  5255. self.ui.menuobjects.addSeparator()
  5256. for name in cncjob_list:
  5257. add_act(name)
  5258. self.ui.menuobjects.addSeparator()
  5259. for name in geo_list:
  5260. add_act(name)
  5261. self.ui.menuobjects.addSeparator()
  5262. for name in script_list:
  5263. add_act(name)
  5264. self.ui.menuobjects.addSeparator()
  5265. for name in doc_list:
  5266. add_act(name)
  5267. self.ui.menuobjects.addSeparator()
  5268. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5269. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5270. _('Select All')
  5271. )
  5272. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5273. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5274. _('Deselect All')
  5275. )
  5276. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5277. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5278. elif state == 'delete':
  5279. for act in self.ui.menuobjects.actions():
  5280. if act.text() == obj.options['name']:
  5281. try:
  5282. act.triggered.disconnect()
  5283. except TypeError:
  5284. pass
  5285. self.ui.menuobjects.removeAction(act)
  5286. break
  5287. elif state == 'rename':
  5288. for act in self.ui.menuobjects.actions():
  5289. if act.text() == old_name:
  5290. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5291. add_action.setText(obj.options['name'])
  5292. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5293. add_action.triggered.connect(
  5294. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5295. self.collection.set_inactive(obj.options['name']))
  5296. self.ui.menuobjects.insertAction(act, add_action)
  5297. try:
  5298. act.triggered.disconnect()
  5299. except TypeError:
  5300. pass
  5301. self.ui.menuobjects.removeAction(act)
  5302. break
  5303. elif state == 'delete_all':
  5304. for act in self.ui.menuobjects.actions():
  5305. try:
  5306. act.triggered.disconnect()
  5307. except TypeError:
  5308. pass
  5309. self.ui.menuobjects.clear()
  5310. self.ui.menuobjects.addSeparator()
  5311. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5312. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5313. _('Select All')
  5314. )
  5315. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5316. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5317. _('Deselect All')
  5318. )
  5319. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5320. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5321. def on_objects_selection(self, on_off):
  5322. obj_list = self.collection.get_names()
  5323. if on_off is True:
  5324. self.collection.set_all_active()
  5325. for act in self.ui.menuobjects.actions():
  5326. try:
  5327. act.setChecked(True)
  5328. except Exception:
  5329. pass
  5330. if obj_list:
  5331. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5332. else:
  5333. self.collection.set_all_inactive()
  5334. for act in self.ui.menuobjects.actions():
  5335. try:
  5336. act.setChecked(False)
  5337. except Exception:
  5338. pass
  5339. if obj_list:
  5340. self.inform.emit('%s' % _("Objects selection is cleared."))
  5341. else:
  5342. self.inform.emit('')
  5343. def grid_status(self):
  5344. if self.ui.grid_snap_btn.isChecked():
  5345. return True
  5346. else:
  5347. return False
  5348. def populate_cmenu_grids(self):
  5349. units = self.defaults['units'].lower()
  5350. # for act in self.ui.cmenu_gridmenu.actions():
  5351. # act.triggered.disconnect()
  5352. self.ui.cmenu_gridmenu.clear()
  5353. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5354. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5355. _("Grid On/Off"))
  5356. grid_toggle.setCheckable(True)
  5357. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5358. self.ui.cmenu_gridmenu.addSeparator()
  5359. for grid in sorted_list:
  5360. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5361. "%s" % str(grid))
  5362. action.triggered.connect(self.set_grid)
  5363. self.ui.cmenu_gridmenu.addSeparator()
  5364. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5365. _("Add"))
  5366. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5367. _("Delete"))
  5368. grid_add.triggered.connect(self.on_grid_add)
  5369. grid_delete.triggered.connect(self.on_grid_delete)
  5370. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5371. def set_grid(self):
  5372. menu_action = self.sender()
  5373. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5374. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5375. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5376. def on_grid_add(self):
  5377. # ## Current application units in lower Case
  5378. units = self.defaults['units'].lower()
  5379. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5380. text=_('Enter a Grid Value:'),
  5381. min=0.0000, max=99.9999, decimals=4)
  5382. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5383. val, ok = grid_add_popup.get_value()
  5384. if ok:
  5385. if float(val) == 0:
  5386. self.inform.emit('[WARNING_NOTCL] %s' %
  5387. _("Please enter a grid value with non-zero value, in Float format."))
  5388. return
  5389. else:
  5390. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5391. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5392. self.inform.emit('[success] %s...' %
  5393. _("New Grid added"))
  5394. else:
  5395. self.inform.emit('[WARNING_NOTCL] %s...' %
  5396. _("Grid already exists"))
  5397. else:
  5398. self.inform.emit('[WARNING_NOTCL] %s...' %
  5399. _("Adding New Grid cancelled"))
  5400. def on_grid_delete(self):
  5401. # ## Current application units in lower Case
  5402. units = self.defaults['units'].lower()
  5403. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5404. text='Enter a Grid Value:',
  5405. min=0.0000, max=99.9999, decimals=4)
  5406. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5407. val, ok = grid_del_popup.get_value()
  5408. if ok:
  5409. if float(val) == 0:
  5410. self.inform.emit('[WARNING_NOTCL] %s' %
  5411. _("Please enter a grid value with non-zero value, in Float format."))
  5412. return
  5413. else:
  5414. try:
  5415. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5416. except ValueError:
  5417. self.inform.emit('[ERROR_NOTCL]%s...' %
  5418. _(" Grid Value does not exist"))
  5419. return
  5420. self.inform.emit('[success] %s...' %
  5421. _("Grid Value deleted"))
  5422. else:
  5423. self.inform.emit('[WARNING_NOTCL] %s...' %
  5424. _("Delete Grid value cancelled"))
  5425. def on_shortcut_list(self):
  5426. self.defaults.report_usage("on_shortcut_list()")
  5427. # add the tab if it was closed
  5428. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5429. # delete the absolute and relative position and messages in the infobar
  5430. self.ui.position_label.setText("")
  5431. self.ui.rel_position_label.setText("")
  5432. # Switch plot_area to preferences page
  5433. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5434. # self.ui.show()
  5435. def on_select_tab(self, name):
  5436. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5437. if self.ui.splitter.sizes()[0] == 0:
  5438. self.ui.splitter.setSizes([1, 1])
  5439. else:
  5440. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5441. self.ui.splitter.setSizes([0, 1])
  5442. if name == 'project':
  5443. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5444. elif name == 'selected':
  5445. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5446. elif name == 'tool':
  5447. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5448. def on_copy_name(self):
  5449. self.defaults.report_usage("on_copy_name()")
  5450. obj = self.collection.get_active()
  5451. try:
  5452. name = obj.options["name"]
  5453. except AttributeError:
  5454. log.debug("on_copy_name() --> No object selected to copy it's name")
  5455. self.inform.emit('[WARNING_NOTCL]%s' %
  5456. _(" No object selected to copy it's name"))
  5457. return
  5458. self.clipboard.setText(name)
  5459. self.inform.emit(_("Name copied on clipboard ..."))
  5460. def on_mouse_click_over_plot(self, event):
  5461. """
  5462. Default actions are:
  5463. :param event: Contains information about the event, like which button
  5464. was clicked, the pixel coordinates and the axes coordinates.
  5465. :return: None
  5466. """
  5467. self.pos = []
  5468. if self.is_legacy is False:
  5469. event_pos = event.pos
  5470. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5471. # # Set the mouse button for panning
  5472. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5473. else:
  5474. event_pos = (event.xdata, event.ydata)
  5475. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5476. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5477. # So it can receive key presses
  5478. self.plotcanvas.native.setFocus()
  5479. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5480. if self.grid_status():
  5481. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5482. else:
  5483. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5484. try:
  5485. if event.button == 1:
  5486. # Reset here the relative coordinates so there is a new reference on the click position
  5487. if self.rel_point1 is None:
  5488. self.rel_point1 = self.pos
  5489. else:
  5490. self.rel_point2 = copy(self.rel_point1)
  5491. self.rel_point1 = self.pos
  5492. self.on_mouse_move_over_plot(event, origin_click=True)
  5493. except Exception as e:
  5494. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5495. def on_mouse_double_click_over_plot(self, event):
  5496. if event.button == 1:
  5497. self.doubleclick = True
  5498. def on_mouse_move_over_plot(self, event, origin_click=None):
  5499. """
  5500. Callback for the mouse motion event over the plot.
  5501. :param event: Contains information about the event.
  5502. :param origin_click
  5503. :return: None
  5504. """
  5505. if self.is_legacy is False:
  5506. event_pos = event.pos
  5507. if self.defaults["global_pan_button"] == '2':
  5508. pan_button = 2
  5509. else:
  5510. pan_button = 3
  5511. self.event_is_dragging = event.is_dragging
  5512. else:
  5513. event_pos = (event.xdata, event.ydata)
  5514. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5515. if self.defaults["global_pan_button"] == '2':
  5516. pan_button = 3
  5517. else:
  5518. pan_button = 2
  5519. self.event_is_dragging = self.plotcanvas.is_dragging
  5520. # So it can receive key presses but not when the Tcl Shell is active
  5521. if not self.ui.shell_dock.isVisible():
  5522. if not self.plotcanvas.native.hasFocus():
  5523. self.plotcanvas.native.setFocus()
  5524. self.pos_jump = event_pos
  5525. self.ui.popMenu.mouse_is_panning = False
  5526. if origin_click is None:
  5527. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5528. if event.button == pan_button and self.event_is_dragging == 1:
  5529. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5530. if self.ui.popMenu.popup_active:
  5531. self.ui.popMenu.popup_active = False
  5532. return
  5533. self.ui.popMenu.mouse_is_panning = True
  5534. return
  5535. if self.rel_point1 is not None:
  5536. try: # May fail in case mouse not within axes
  5537. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5538. if self.grid_status():
  5539. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5540. # Update cursor
  5541. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5542. symbol='++', edge_color=self.cursor_color_3D,
  5543. edge_width=self.defaults["global_cursor_width"],
  5544. size=self.defaults["global_cursor_size"])
  5545. else:
  5546. pos = (pos_canvas[0], pos_canvas[1])
  5547. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5548. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5549. self.dx = pos[0] - float(self.rel_point1[0])
  5550. self.dy = pos[1] - float(self.rel_point1[1])
  5551. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5552. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5553. self.mouse = [pos[0], pos[1]]
  5554. # if the mouse is moved and the LMB is clicked then the action is a selection
  5555. if self.event_is_dragging == 1 and event.button == 1:
  5556. self.delete_selection_shape()
  5557. if self.dx < 0:
  5558. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5559. face_color=self.defaults['global_alt_sel_fill'])
  5560. self.selection_type = False
  5561. elif self.dx >= 0:
  5562. self.draw_moving_selection_shape(self.pos, pos)
  5563. self.selection_type = True
  5564. else:
  5565. self.selection_type = None
  5566. else:
  5567. self.selection_type = None
  5568. # hover effect - enabled in Preferences -> General -> GUI Settings
  5569. if self.defaults['global_hover']:
  5570. for obj in self.collection.get_list():
  5571. try:
  5572. # select the object(s) only if it is enabled (plotted)
  5573. if obj.options['plot']:
  5574. if obj not in self.collection.get_selected():
  5575. poly_obj = Polygon(
  5576. [(obj.options['xmin'], obj.options['ymin']),
  5577. (obj.options['xmax'], obj.options['ymin']),
  5578. (obj.options['xmax'], obj.options['ymax']),
  5579. (obj.options['xmin'], obj.options['ymax'])]
  5580. )
  5581. if Point(pos).within(poly_obj):
  5582. if obj.isHovering is False:
  5583. obj.isHovering = True
  5584. obj.notHovering = True
  5585. # create the selection box around the selected object
  5586. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5587. else:
  5588. if obj.notHovering is True:
  5589. obj.notHovering = False
  5590. obj.isHovering = False
  5591. self.delete_hover_shape()
  5592. except Exception:
  5593. # the Exception here will happen if we try to select on screen and we have an
  5594. # newly (and empty) just created Geometry or Excellon object that do not have the
  5595. # xmin, xmax, ymin, ymax options.
  5596. # In this case poly_obj creation (see above) will fail
  5597. pass
  5598. except Exception:
  5599. self.ui.position_label.setText("")
  5600. self.ui.rel_position_label.setText("")
  5601. self.mouse = None
  5602. def on_mouse_click_release_over_plot(self, event):
  5603. """
  5604. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5605. and has been registered in ''self.__init__()''.
  5606. :param event: contains information about the event.
  5607. :return:
  5608. """
  5609. if self.is_legacy is False:
  5610. event_pos = event.pos
  5611. right_button = 2
  5612. else:
  5613. event_pos = (event.xdata, event.ydata)
  5614. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5615. right_button = 3
  5616. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5617. if self.grid_status():
  5618. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5619. else:
  5620. pos = (pos_canvas[0], pos_canvas[1])
  5621. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5622. # canvas menu
  5623. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5624. self.ui.popMenu.mouse_is_panning = False
  5625. self.cursor = QtGui.QCursor()
  5626. self.populate_cmenu_grids()
  5627. self.ui.popMenu.popup(self.cursor.pos())
  5628. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5629. # selection and then select a type of selection ("enclosing" or "touching")
  5630. if event.button == 1: # left click
  5631. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5632. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5633. if modifiers == QtCore.Qt.ShiftModifier:
  5634. # do not auto open the Project Tab
  5635. self.click_noproject = True
  5636. self.clipboard.setText(
  5637. self.defaults["global_point_clipboard_format"] %
  5638. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5639. )
  5640. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5641. return
  5642. if self.doubleclick is True:
  5643. self.doubleclick = False
  5644. if self.collection.get_selected():
  5645. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5646. if self.ui.splitter.sizes()[0] == 0:
  5647. self.ui.splitter.setSizes([1, 1])
  5648. try:
  5649. # delete the selection shape(S) as it may be in the way
  5650. self.delete_selection_shape()
  5651. self.delete_hover_shape()
  5652. except Exception as e:
  5653. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5654. return
  5655. else:
  5656. # WORKAROUND for LEGACY MODE
  5657. if self.is_legacy is True:
  5658. # if there is no move on canvas then we have no dragging selection
  5659. if self.dx == 0 or self.dy == 0:
  5660. self.selection_type = None
  5661. if self.selection_type is not None:
  5662. try:
  5663. self.selection_area_handler(self.pos, pos, self.selection_type)
  5664. self.selection_type = None
  5665. except Exception as e:
  5666. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5667. return
  5668. else:
  5669. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5670. if key_modifier == QtCore.Qt.ShiftModifier:
  5671. mod_key = 'Shift'
  5672. elif key_modifier == QtCore.Qt.ControlModifier:
  5673. mod_key = 'Control'
  5674. else:
  5675. mod_key = None
  5676. try:
  5677. if self.command_active is None:
  5678. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5679. # deselect, and if it's not selected then it will be selected
  5680. # If there is no active command (self.command_active is None) then we check if we clicked
  5681. # on a object by checking the bounding limits against mouse click position
  5682. if mod_key == self.defaults["global_mselect_key"]:
  5683. self.select_objects(key='multisel')
  5684. else:
  5685. # If there is no active command (self.command_active is None) then we check if
  5686. # we clicked on a object by checking the bounding limits against mouse click position
  5687. self.select_objects()
  5688. self.delete_hover_shape()
  5689. except Exception as e:
  5690. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5691. return
  5692. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5693. """
  5694. :param start_pos: mouse position when the selection LMB click was done
  5695. :param end_pos: mouse position when the left mouse button is released
  5696. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5697. :return:
  5698. """
  5699. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5700. # delete previous selection shape
  5701. self.delete_selection_shape()
  5702. # make all objects inactive
  5703. self.collection.set_all_inactive()
  5704. for obj in self.collection.get_list():
  5705. try:
  5706. # select the object(s) only if it is enabled (plotted)
  5707. if obj.options['plot']:
  5708. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5709. (obj.options['xmax'], obj.options['ymin']),
  5710. (obj.options['xmax'], obj.options['ymax']),
  5711. (obj.options['xmin'], obj.options['ymax'])])
  5712. if sel_type is True:
  5713. if poly_obj.within(poly_selection):
  5714. # create the selection box around the selected object
  5715. if self.defaults['global_selection_shape'] is True:
  5716. self.draw_selection_shape(obj)
  5717. self.collection.set_active(obj.options['name'])
  5718. else:
  5719. if poly_selection.intersects(poly_obj):
  5720. # create the selection box around the selected object
  5721. if self.defaults['global_selection_shape'] is True:
  5722. self.draw_selection_shape(obj)
  5723. self.collection.set_active(obj.options['name'])
  5724. obj.selection_shape_drawn = True
  5725. except Exception as e:
  5726. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5727. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5728. # In this case poly_obj creation (see above) will fail
  5729. log.debug("App.selection_area_handler() --> %s" % str(e))
  5730. def select_objects(self, key=None):
  5731. """
  5732. Will select objects clicked on canvas
  5733. :param key: for future use in cumulative selection
  5734. :return:
  5735. """
  5736. # list where we store the overlapped objects under our mouse left click position
  5737. if key is None:
  5738. self.objects_under_the_click_list = []
  5739. # Populate the list with the overlapped objects on the click position
  5740. curr_x, curr_y = self.pos
  5741. for obj in self.all_objects_list:
  5742. # ScriptObject and DocumentObject objects can't be selected
  5743. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5744. continue
  5745. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5746. continue
  5747. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5748. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5749. if obj.options['name'] not in self.objects_under_the_click_list:
  5750. if obj.options['plot']:
  5751. # add objects to the objects_under_the_click list only if the object is plotted
  5752. # (active and not disabled)
  5753. self.objects_under_the_click_list.append(obj.options['name'])
  5754. try:
  5755. if self.objects_under_the_click_list:
  5756. curr_sel_obj = self.collection.get_active()
  5757. # case when there is only an object under the click and we toggle it
  5758. if len(self.objects_under_the_click_list) == 1:
  5759. if curr_sel_obj is None:
  5760. self.collection.set_active(self.objects_under_the_click_list[0])
  5761. curr_sel_obj = self.collection.get_active()
  5762. # create the selection box around the selected object
  5763. if self.defaults['global_selection_shape'] is True:
  5764. self.draw_selection_shape(curr_sel_obj)
  5765. curr_sel_obj.selection_shape_drawn = True
  5766. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5767. self.on_objects_selection(False)
  5768. self.delete_selection_shape()
  5769. curr_sel_obj.selection_shape_drawn = False
  5770. self.collection.set_active(self.objects_under_the_click_list[0])
  5771. curr_sel_obj = self.collection.get_active()
  5772. # create the selection box around the selected object
  5773. if self.defaults['global_selection_shape'] is True:
  5774. self.draw_selection_shape(curr_sel_obj)
  5775. curr_sel_obj.selection_shape_drawn = True
  5776. self.selected_message(curr_sel_obj=curr_sel_obj)
  5777. elif curr_sel_obj.selection_shape_drawn is False:
  5778. if self.defaults['global_selection_shape'] is True:
  5779. self.draw_selection_shape(curr_sel_obj)
  5780. curr_sel_obj.selection_shape_drawn = True
  5781. else:
  5782. self.on_objects_selection(False)
  5783. self.delete_selection_shape()
  5784. if self.call_source != 'app':
  5785. self.call_source = 'app'
  5786. self.selected_message(curr_sel_obj=curr_sel_obj)
  5787. else:
  5788. # If there is no selected object
  5789. # make active the first element of the overlapped objects list
  5790. if self.collection.get_active() is None:
  5791. self.collection.set_active(self.objects_under_the_click_list[0])
  5792. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5793. name_sel_obj = self.collection.get_active().options['name']
  5794. # In case that there is a selected object but it is not in the overlapped object list
  5795. # make that object inactive and activate the first element in the overlapped object list
  5796. if name_sel_obj not in self.objects_under_the_click_list:
  5797. self.collection.set_inactive(name_sel_obj)
  5798. name_sel_obj = self.objects_under_the_click_list[0]
  5799. self.collection.set_active(name_sel_obj)
  5800. else:
  5801. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5802. self.collection.set_all_inactive()
  5803. self.collection.set_active(
  5804. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5805. curr_sel_obj = self.collection.get_active()
  5806. # delete the possible selection box around a possible selected object
  5807. self.delete_selection_shape()
  5808. curr_sel_obj.selection_shape_drawn = False
  5809. # create the selection box around the selected object
  5810. if self.defaults['global_selection_shape'] is True:
  5811. self.draw_selection_shape(curr_sel_obj)
  5812. curr_sel_obj.selection_shape_drawn = True
  5813. self.selected_message(curr_sel_obj=curr_sel_obj)
  5814. else:
  5815. # deselect everything
  5816. self.on_objects_selection(False)
  5817. # delete the possible selection box around a possible selected object
  5818. self.delete_selection_shape()
  5819. for o in self.collection.get_list():
  5820. o.selection_shape_drawn = False
  5821. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5822. # only when working on App
  5823. if self.call_source == 'app':
  5824. if self.click_noproject is False:
  5825. # if the Tool Tab is in focus don't change focus to Project Tab
  5826. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5827. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5828. else:
  5829. # restore auto open the Project Tab
  5830. self.click_noproject = False
  5831. # delete any text in the status bar, implicitly the last object name that was selected
  5832. # self.inform.emit("")
  5833. else:
  5834. self.call_source = 'app'
  5835. except Exception as e:
  5836. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5837. def selected_message(self, curr_sel_obj):
  5838. if curr_sel_obj:
  5839. if curr_sel_obj.kind == 'gerber':
  5840. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5841. color='green',
  5842. name=str(curr_sel_obj.options['name']),
  5843. tx=_("selected"))
  5844. )
  5845. elif curr_sel_obj.kind == 'excellon':
  5846. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5847. color='brown',
  5848. name=str(curr_sel_obj.options['name']),
  5849. tx=_("selected"))
  5850. )
  5851. elif curr_sel_obj.kind == 'cncjob':
  5852. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5853. color='blue',
  5854. name=str(curr_sel_obj.options['name']),
  5855. tx=_("selected"))
  5856. )
  5857. elif curr_sel_obj.kind == 'geometry':
  5858. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5859. color='red',
  5860. name=str(curr_sel_obj.options['name']),
  5861. tx=_("selected"))
  5862. )
  5863. def delete_hover_shape(self):
  5864. self.hover_shapes.clear()
  5865. self.hover_shapes.redraw()
  5866. def draw_hover_shape(self, sel_obj, color=None):
  5867. """
  5868. :param sel_obj: The object for which the hover shape must be drawn
  5869. :param color: The color of the hover shape
  5870. :return: None
  5871. """
  5872. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5873. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5874. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5875. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5876. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5877. if self.defaults['units'].upper() == 'MM':
  5878. hover_rect = hover_rect.buffer(-0.1)
  5879. hover_rect = hover_rect.buffer(0.2)
  5880. else:
  5881. hover_rect = hover_rect.buffer(-0.00393)
  5882. hover_rect = hover_rect.buffer(0.00787)
  5883. # if color:
  5884. # face = Color(color)
  5885. # face.alpha = 0.2
  5886. # outline = Color(color, alpha=0.8)
  5887. # else:
  5888. # face = Color(self.defaults['global_sel_fill'])
  5889. # face.alpha = 0.2
  5890. # outline = self.defaults['global_sel_line']
  5891. if color:
  5892. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5893. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5894. else:
  5895. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5896. outline = self.defaults['global_sel_line']
  5897. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5898. if self.is_legacy is True:
  5899. self.hover_shapes.redraw()
  5900. def delete_selection_shape(self):
  5901. self.move_tool.sel_shapes.clear()
  5902. self.move_tool.sel_shapes.redraw()
  5903. def draw_selection_shape(self, sel_obj, color=None):
  5904. """
  5905. Will draw a selection shape around the selected object.
  5906. :param sel_obj: The object for which the selection shape must be drawn
  5907. :param color: The color for the selection shape.
  5908. :return: None
  5909. """
  5910. if sel_obj is None:
  5911. return
  5912. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5913. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5914. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5915. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5916. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5917. if self.defaults['units'].upper() == 'MM':
  5918. sel_rect = sel_rect.buffer(-0.1)
  5919. sel_rect = sel_rect.buffer(0.2)
  5920. else:
  5921. sel_rect = sel_rect.buffer(-0.00393)
  5922. sel_rect = sel_rect.buffer(0.00787)
  5923. if color:
  5924. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5925. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5926. else:
  5927. if self.is_legacy is False:
  5928. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5929. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5930. else:
  5931. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5932. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5933. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5934. color=outline,
  5935. face_color=face,
  5936. update=True,
  5937. layer=0,
  5938. tolerance=None))
  5939. if self.is_legacy is True:
  5940. self.move_tool.sel_shapes.redraw()
  5941. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5942. """
  5943. Will draw a selection shape when dragging mouse on canvas.
  5944. :param old_coords: Old coordinates
  5945. :param coords: New coordinates
  5946. :param kwargs: Keyword arguments
  5947. :return:
  5948. """
  5949. if 'color' in kwargs:
  5950. color = kwargs['color']
  5951. else:
  5952. color = self.defaults['global_sel_line']
  5953. if 'face_color' in kwargs:
  5954. face_color = kwargs['face_color']
  5955. else:
  5956. face_color = self.defaults['global_sel_fill']
  5957. if 'face_alpha' in kwargs:
  5958. face_alpha = kwargs['face_alpha']
  5959. else:
  5960. face_alpha = 0.3
  5961. x0, y0 = old_coords
  5962. x1, y1 = coords
  5963. pt1 = (x0, y0)
  5964. pt2 = (x1, y0)
  5965. pt3 = (x1, y1)
  5966. pt4 = (x0, y1)
  5967. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5968. # color_t = Color(face_color)
  5969. # color_t.alpha = face_alpha
  5970. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5971. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5972. layer=0, tolerance=None)
  5973. if self.is_legacy is True:
  5974. self.move_tool.sel_shapes.redraw()
  5975. def on_file_new_click(self):
  5976. """
  5977. Callback for menu item File -> New.
  5978. Executed on clicking the Menu -> File -> New Project
  5979. :return:
  5980. """
  5981. if self.collection.get_list() and self.should_we_save:
  5982. msgbox = QtWidgets.QMessageBox()
  5983. # msgbox.setText("<B>Save changes ...</B>")
  5984. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5985. "Creating a New project will delete them.\n"
  5986. "Do you want to Save the project?"))
  5987. msgbox.setWindowTitle(_("Save changes"))
  5988. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5989. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5990. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5991. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5992. msgbox.setDefaultButton(bt_yes)
  5993. msgbox.exec_()
  5994. response = msgbox.clickedButton()
  5995. if response == bt_yes:
  5996. self.on_file_saveprojectas()
  5997. elif response == bt_cancel:
  5998. return
  5999. elif response == bt_no:
  6000. self.on_file_new()
  6001. else:
  6002. self.on_file_new()
  6003. self.inform.emit('[success] %s...' % _("New Project created"))
  6004. def on_file_new(self, cli=None):
  6005. """
  6006. Returns the application to its startup state. This method is thread-safe.
  6007. :param cli: Boolean. If True this method was run from command line
  6008. :return: None
  6009. """
  6010. self.defaults.report_usage("on_file_new")
  6011. # Remove everything from memory
  6012. App.log.debug("on_file_new()")
  6013. # close any editor that might be open
  6014. if self.call_source != 'app':
  6015. self.editor2object(cleanup=True)
  6016. # ## EDITOR section
  6017. self.geo_editor = FlatCAMGeoEditor(self)
  6018. self.exc_editor = FlatCAMExcEditor(self)
  6019. self.grb_editor = FlatCAMGrbEditor(self)
  6020. # Clear pool
  6021. self.clear_pool()
  6022. for obj in self.collection.get_list():
  6023. # delete shapes left drawn from mark shape_collections, if any
  6024. if isinstance(obj, GerberObject):
  6025. try:
  6026. for el in obj.mark_shapes:
  6027. obj.mark_shapes[el].clear(update=True)
  6028. obj.mark_shapes[el].enabled = False
  6029. del el
  6030. except AttributeError:
  6031. pass
  6032. # also delete annotation shapes, if any
  6033. elif isinstance(obj, CNCJobObject):
  6034. try:
  6035. obj.text_col.enabled = False
  6036. del obj.text_col
  6037. obj.annotation.clear(update=True)
  6038. del obj.annotation
  6039. except AttributeError:
  6040. pass
  6041. # delete the exclusion areas
  6042. self.exc_areas.clear_shapes()
  6043. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6044. self.shell.init_tcl()
  6045. # delete any selection shape on canvas
  6046. self.delete_selection_shape()
  6047. # delete all FlatCAM objects
  6048. self.collection.delete_all()
  6049. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  6050. self.setup_component_editor()
  6051. # Clear project filename
  6052. self.project_filename = None
  6053. # Load the application defaults
  6054. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6055. # Re-fresh project options
  6056. self.on_options_app2project()
  6057. # Init FlatCAMTools
  6058. self.init_tools()
  6059. # Try to close all tabs in the PlotArea but only if the GUI is active (CLI is None)
  6060. if cli is None:
  6061. # we need to go in reverse because once we remove a tab then the index changes
  6062. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  6063. # and so on. Therefore the deletion should be done in reverse
  6064. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  6065. for index in range(wdg_count, -1, -1):
  6066. try:
  6067. self.ui.plot_tab_area.closeTab(index)
  6068. except Exception as e:
  6069. log.debug("App.on_file_new() --> %s" % str(e))
  6070. # # And then add again the Plot Area
  6071. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  6072. self.ui.plot_tab_area.protectTab(0)
  6073. # take the focus of the Notebook on Project Tab.
  6074. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6075. self.set_ui_title(name=_("New Project - Not saved"))
  6076. def obj_properties(self):
  6077. """
  6078. Will launch the object Properties Tool
  6079. :return:
  6080. """
  6081. self.defaults.report_usage("obj_properties()")
  6082. self.properties_tool.run(toggle=False)
  6083. def on_project_context_save(self):
  6084. """
  6085. Wrapper, will save the object function of it's type
  6086. :return:
  6087. """
  6088. obj = self.collection.get_active()
  6089. if type(obj) == GeometryObject:
  6090. self.on_file_exportdxf()
  6091. elif type(obj) == ExcellonObject:
  6092. self.on_file_saveexcellon()
  6093. elif type(obj) == CNCJobObject:
  6094. obj.on_exportgcode_button_click()
  6095. elif type(obj) == GerberObject:
  6096. self.on_file_savegerber()
  6097. elif type(obj) == ScriptObject:
  6098. self.on_file_savescript()
  6099. elif type(obj) == DocumentObject:
  6100. self.on_file_savedocument()
  6101. def obj_move(self):
  6102. """
  6103. Callback for the Move menu entry in various Context Menu's.
  6104. :return:
  6105. """
  6106. self.defaults.report_usage("obj_move()")
  6107. self.move_tool.run(toggle=False)
  6108. def on_fileopengerber(self, signal, name=None):
  6109. """
  6110. File menu callback for opening a Gerber.
  6111. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6112. :param name:
  6113. :return: None
  6114. """
  6115. self.defaults.report_usage("on_fileopengerber")
  6116. App.log.debug("on_fileopengerber()")
  6117. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6118. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6119. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6120. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6121. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6122. "*.mil);;" \
  6123. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6124. "Allegro Files (*.art);;" \
  6125. "Mentor Files (*.pho *.gdo);;" \
  6126. "All Files (*.*)"
  6127. if name is None:
  6128. try:
  6129. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6130. directory=self.get_last_folder(),
  6131. filter=_filter_)
  6132. except TypeError:
  6133. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6134. filenames = [str(filename) for filename in filenames]
  6135. else:
  6136. filenames = [name]
  6137. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6138. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6139. _("Opening Gerber file.")),
  6140. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6141. color=QtGui.QColor("gray"))
  6142. if len(filenames) == 0:
  6143. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6144. else:
  6145. for filename in filenames:
  6146. if filename != '':
  6147. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6148. def on_fileopenexcellon(self, signal, name=None):
  6149. """
  6150. File menu callback for opening an Excellon file.
  6151. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6152. :param name:
  6153. :return: None
  6154. """
  6155. self.defaults.report_usage("on_fileopenexcellon")
  6156. App.log.debug("on_fileopenexcellon()")
  6157. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6158. "All Files (*.*)"
  6159. if name is None:
  6160. try:
  6161. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6162. directory=self.get_last_folder(),
  6163. filter=_filter_)
  6164. except TypeError:
  6165. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6166. filenames = [str(filename) for filename in filenames]
  6167. else:
  6168. filenames = [str(name)]
  6169. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6170. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6171. _("Opening Excellon file.")),
  6172. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6173. color=QtGui.QColor("gray"))
  6174. if len(filenames) == 0:
  6175. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6176. else:
  6177. for filename in filenames:
  6178. if filename != '':
  6179. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6180. def on_fileopengcode(self, signal, name=None):
  6181. """
  6182. File menu call back for opening gcode.
  6183. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6184. :param name:
  6185. :return:
  6186. """
  6187. self.defaults.report_usage("on_fileopengcode")
  6188. App.log.debug("on_fileopengcode()")
  6189. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6190. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6191. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6192. "All Files (*.*)"
  6193. if name is None:
  6194. try:
  6195. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6196. directory=self.get_last_folder(),
  6197. filter=_filter_)
  6198. except TypeError:
  6199. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6200. filenames = [str(filename) for filename in filenames]
  6201. else:
  6202. filenames = [name]
  6203. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6204. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6205. _("Opening G-Code file.")),
  6206. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6207. color=QtGui.QColor("gray"))
  6208. if len(filenames) == 0:
  6209. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6210. else:
  6211. for filename in filenames:
  6212. if filename != '':
  6213. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6214. def on_file_openproject(self, signal):
  6215. """
  6216. File menu callback for opening a project.
  6217. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6218. :return: None
  6219. """
  6220. self.defaults.report_usage("on_file_openproject")
  6221. App.log.debug("on_file_openproject()")
  6222. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6223. try:
  6224. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6225. directory=self.get_last_folder(), filter=_filter_)
  6226. except TypeError:
  6227. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6228. # The Qt methods above will return a QString which can cause problems later.
  6229. # So far json.dump() will fail to serialize it.
  6230. # TODO: Improve the serialization methods and remove this fix.
  6231. filename = str(filename)
  6232. if filename == "":
  6233. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6234. else:
  6235. # self.worker_task.emit({'fcn': self.open_project,
  6236. # 'params': [filename]})
  6237. # The above was failing because open_project() is not
  6238. # thread safe. The new_project()
  6239. self.open_project(filename)
  6240. def on_fileopenhpgl2(self, signal, name=None):
  6241. """
  6242. File menu callback for opening a HPGL2.
  6243. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6244. :param name:
  6245. :return: None
  6246. """
  6247. self.defaults.report_usage("on_fileopenhpgl2")
  6248. App.log.debug("on_fileopenhpgl2()")
  6249. _filter_ = "HPGL2 Files (*.plt);;" \
  6250. "All Files (*.*)"
  6251. if name is None:
  6252. try:
  6253. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6254. directory=self.get_last_folder(),
  6255. filter=_filter_)
  6256. except TypeError:
  6257. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6258. filenames = [str(filename) for filename in filenames]
  6259. else:
  6260. filenames = [name]
  6261. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6262. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6263. _("Opening HPGL2 file.")),
  6264. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6265. color=QtGui.QColor("gray"))
  6266. if len(filenames) == 0:
  6267. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6268. else:
  6269. for filename in filenames:
  6270. if filename != '':
  6271. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6272. def on_file_openconfig(self, signal):
  6273. """
  6274. File menu callback for opening a config file.
  6275. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6276. :return: None
  6277. """
  6278. self.defaults.report_usage("on_file_openconfig")
  6279. App.log.debug("on_file_openconfig()")
  6280. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6281. try:
  6282. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6283. directory=self.data_path, filter=_filter_)
  6284. except TypeError:
  6285. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6286. filter=_filter_)
  6287. if filename == "":
  6288. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6289. else:
  6290. self.open_config_file(filename)
  6291. def on_file_exportsvg(self):
  6292. """
  6293. Callback for menu item File->Export SVG.
  6294. :return: None
  6295. """
  6296. self.defaults.report_usage("on_file_exportsvg")
  6297. App.log.debug("on_file_exportsvg()")
  6298. obj = self.collection.get_active()
  6299. if obj is None:
  6300. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6301. msg = _("Please Select a Geometry object to export")
  6302. msgbox = QtWidgets.QMessageBox()
  6303. msgbox.setInformativeText(msg)
  6304. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6305. msgbox.setDefaultButton(bt_ok)
  6306. msgbox.exec_()
  6307. return
  6308. # Check for more compatible types and add as required
  6309. if (not isinstance(obj, GeometryObject)
  6310. and not isinstance(obj, GerberObject)
  6311. and not isinstance(obj, CNCJobObject)
  6312. and not isinstance(obj, ExcellonObject)):
  6313. msg = '[ERROR_NOTCL] %s' % \
  6314. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6315. msgbox = QtWidgets.QMessageBox()
  6316. msgbox.setInformativeText(msg)
  6317. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6318. msgbox.setDefaultButton(bt_ok)
  6319. msgbox.exec_()
  6320. return
  6321. name = obj.options["name"]
  6322. _filter = "SVG File (*.svg);;All Files (*.*)"
  6323. try:
  6324. filename, _f = FCFileSaveDialog.get_saved_filename(
  6325. caption=_("Export SVG"),
  6326. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6327. filter=_filter)
  6328. except TypeError:
  6329. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6330. filename = str(filename)
  6331. if filename == "":
  6332. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6333. return
  6334. else:
  6335. self.export_svg(name, filename)
  6336. if self.defaults["global_open_style"] is False:
  6337. self.file_opened.emit("SVG", filename)
  6338. self.file_saved.emit("SVG", filename)
  6339. def on_file_exportpng(self):
  6340. self.defaults.report_usage("on_file_exportpng")
  6341. App.log.debug("on_file_exportpng()")
  6342. self.date = str(datetime.today()).rpartition('.')[0]
  6343. self.date = ''.join(c for c in self.date if c not in ':-')
  6344. self.date = self.date.replace(' ', '_')
  6345. if self.is_legacy is False:
  6346. image = _screenshot()
  6347. data = np.asarray(image)
  6348. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6349. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6350. return
  6351. filter_ = "PNG File (*.png);;All Files (*.*)"
  6352. try:
  6353. filename, _f = FCFileSaveDialog.get_saved_filename(
  6354. caption=_("Export PNG Image"),
  6355. directory=self.get_last_save_folder() + '/png_' + self.date,
  6356. filter=filter_)
  6357. except TypeError:
  6358. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6359. filename = str(filename)
  6360. if filename == "":
  6361. self.inform.emit(_("Cancelled."))
  6362. return
  6363. else:
  6364. if self.is_legacy is False:
  6365. write_png(filename, data)
  6366. else:
  6367. self.plotcanvas.figure.savefig(filename)
  6368. if self.defaults["global_open_style"] is False:
  6369. self.file_opened.emit("png", filename)
  6370. self.file_saved.emit("png", filename)
  6371. def on_file_savegerber(self):
  6372. """
  6373. Callback for menu item in Project context menu.
  6374. :return: None
  6375. """
  6376. self.defaults.report_usage("on_file_savegerber")
  6377. App.log.debug("on_file_savegerber()")
  6378. obj = self.collection.get_active()
  6379. if obj is None:
  6380. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6381. return
  6382. # Check for more compatible types and add as required
  6383. if not isinstance(obj, GerberObject):
  6384. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6385. return
  6386. name = self.collection.get_active().options["name"]
  6387. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6388. try:
  6389. filename, _f = FCFileSaveDialog.get_saved_filename(
  6390. caption="Save Gerber source file",
  6391. directory=self.get_last_save_folder() + '/' + name,
  6392. filter=_filter)
  6393. except TypeError:
  6394. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6395. filename = str(filename)
  6396. if filename == "":
  6397. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6398. return
  6399. else:
  6400. self.save_source_file(name, filename)
  6401. if self.defaults["global_open_style"] is False:
  6402. self.file_opened.emit("Gerber", filename)
  6403. self.file_saved.emit("Gerber", filename)
  6404. def on_file_savescript(self):
  6405. """
  6406. Callback for menu item in Project context menu.
  6407. :return: None
  6408. """
  6409. self.defaults.report_usage("on_file_savescript")
  6410. App.log.debug("on_file_savescript()")
  6411. obj = self.collection.get_active()
  6412. if obj is None:
  6413. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6414. return
  6415. # Check for more compatible types and add as required
  6416. if not isinstance(obj, ScriptObject):
  6417. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6418. return
  6419. name = self.collection.get_active().options["name"]
  6420. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6421. try:
  6422. filename, _f = FCFileSaveDialog.get_saved_filename(
  6423. caption="Save Script source file",
  6424. directory=self.get_last_save_folder() + '/' + name,
  6425. filter=_filter)
  6426. except TypeError:
  6427. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6428. filename = str(filename)
  6429. if filename == "":
  6430. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6431. return
  6432. else:
  6433. self.save_source_file(name, filename)
  6434. if self.defaults["global_open_style"] is False:
  6435. self.file_opened.emit("Script", filename)
  6436. self.file_saved.emit("Script", filename)
  6437. def on_file_savedocument(self):
  6438. """
  6439. Callback for menu item in Project context menu.
  6440. :return: None
  6441. """
  6442. self.defaults.report_usage("on_file_savedocument")
  6443. App.log.debug("on_file_savedocument()")
  6444. obj = self.collection.get_active()
  6445. if obj is None:
  6446. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6447. return
  6448. # Check for more compatible types and add as required
  6449. if not isinstance(obj, ScriptObject):
  6450. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6451. return
  6452. name = self.collection.get_active().options["name"]
  6453. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6454. try:
  6455. filename, _f = FCFileSaveDialog.get_saved_filename(
  6456. caption="Save Document source file",
  6457. directory=self.get_last_save_folder() + '/' + name,
  6458. filter=_filter)
  6459. except TypeError:
  6460. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6461. filename = str(filename)
  6462. if filename == "":
  6463. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6464. return
  6465. else:
  6466. self.save_source_file(name, filename)
  6467. if self.defaults["global_open_style"] is False:
  6468. self.file_opened.emit("Document", filename)
  6469. self.file_saved.emit("Document", filename)
  6470. def on_file_saveexcellon(self):
  6471. """
  6472. Callback for menu item in project context menu.
  6473. :return: None
  6474. """
  6475. self.defaults.report_usage("on_file_saveexcellon")
  6476. App.log.debug("on_file_saveexcellon()")
  6477. obj = self.collection.get_active()
  6478. if obj is None:
  6479. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6480. return
  6481. # Check for more compatible types and add as required
  6482. if not isinstance(obj, ExcellonObject):
  6483. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6484. return
  6485. name = self.collection.get_active().options["name"]
  6486. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6487. try:
  6488. filename, _f = FCFileSaveDialog.get_saved_filename(
  6489. caption=_("Save Excellon source file"),
  6490. directory=self.get_last_save_folder() + '/' + name,
  6491. filter=_filter)
  6492. except TypeError:
  6493. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6494. filename = str(filename)
  6495. if filename == "":
  6496. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6497. return
  6498. else:
  6499. self.save_source_file(name, filename)
  6500. if self.defaults["global_open_style"] is False:
  6501. self.file_opened.emit("Excellon", filename)
  6502. self.file_saved.emit("Excellon", filename)
  6503. def on_file_exportexcellon(self):
  6504. """
  6505. Callback for menu item File->Export->Excellon.
  6506. :return: None
  6507. """
  6508. self.defaults.report_usage("on_file_exportexcellon")
  6509. App.log.debug("on_file_exportexcellon()")
  6510. obj = self.collection.get_active()
  6511. if obj is None:
  6512. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6513. return
  6514. # Check for more compatible types and add as required
  6515. if not isinstance(obj, ExcellonObject):
  6516. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6517. return
  6518. name = self.collection.get_active().options["name"]
  6519. _filter = self.defaults["excellon_save_filters"]
  6520. try:
  6521. filename, _f = FCFileSaveDialog.get_saved_filename(
  6522. caption=_("Export Excellon"),
  6523. directory=self.get_last_save_folder() + '/' + name,
  6524. filter=_filter)
  6525. except TypeError:
  6526. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6527. filename = str(filename)
  6528. if filename == "":
  6529. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6530. return
  6531. else:
  6532. used_extension = filename.rpartition('.')[2]
  6533. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6534. self.export_excellon(name, filename)
  6535. if self.defaults["global_open_style"] is False:
  6536. self.file_opened.emit("Excellon", filename)
  6537. self.file_saved.emit("Excellon", filename)
  6538. def on_file_exportgerber(self):
  6539. """
  6540. Callback for menu item File->Export->Gerber.
  6541. :return: None
  6542. """
  6543. self.defaults.report_usage("on_file_exportgerber")
  6544. App.log.debug("on_file_exportgerber()")
  6545. obj = self.collection.get_active()
  6546. if obj is None:
  6547. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6548. return
  6549. # Check for more compatible types and add as required
  6550. if not isinstance(obj, GerberObject):
  6551. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6552. return
  6553. name = self.collection.get_active().options["name"]
  6554. _filter_ = self.defaults['gerber_save_filters']
  6555. try:
  6556. filename, _f = FCFileSaveDialog.get_saved_filename(
  6557. caption=_("Export Gerber"),
  6558. directory=self.get_last_save_folder() + '/' + name,
  6559. filter=_filter_)
  6560. except TypeError:
  6561. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6562. filename = str(filename)
  6563. if filename == "":
  6564. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6565. return
  6566. else:
  6567. used_extension = filename.rpartition('.')[2]
  6568. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6569. self.export_gerber(name, filename)
  6570. if self.defaults["global_open_style"] is False:
  6571. self.file_opened.emit("Gerber", filename)
  6572. self.file_saved.emit("Gerber", filename)
  6573. def on_file_exportdxf(self):
  6574. """
  6575. Callback for menu item File->Export DXF.
  6576. :return: None
  6577. """
  6578. self.defaults.report_usage("on_file_exportdxf")
  6579. App.log.debug("on_file_exportdxf()")
  6580. obj = self.collection.get_active()
  6581. if obj is None:
  6582. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6583. msg = _("Please Select a Geometry object to export")
  6584. msgbox = QtWidgets.QMessageBox()
  6585. msgbox.setInformativeText(msg)
  6586. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6587. msgbox.setDefaultButton(bt_ok)
  6588. msgbox.exec_()
  6589. return
  6590. # Check for more compatible types and add as required
  6591. if not isinstance(obj, GeometryObject):
  6592. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6593. msgbox = QtWidgets.QMessageBox()
  6594. msgbox.setInformativeText(msg)
  6595. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6596. msgbox.setDefaultButton(bt_ok)
  6597. msgbox.exec_()
  6598. return
  6599. name = self.collection.get_active().options["name"]
  6600. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6601. try:
  6602. filename, _f = FCFileSaveDialog.get_saved_filename(
  6603. caption=_("Export DXF"),
  6604. directory=self.get_last_save_folder() + '/' + name,
  6605. filter=_filter_)
  6606. except TypeError:
  6607. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6608. filename = str(filename)
  6609. if filename == "":
  6610. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6611. return
  6612. else:
  6613. self.export_dxf(name, filename)
  6614. if self.defaults["global_open_style"] is False:
  6615. self.file_opened.emit("DXF", filename)
  6616. self.file_saved.emit("DXF", filename)
  6617. def on_file_importsvg(self, type_of_obj):
  6618. """
  6619. Callback for menu item File->Import SVG.
  6620. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6621. :type type_of_obj: str
  6622. :return: None
  6623. """
  6624. self.defaults.report_usage("on_file_importsvg")
  6625. App.log.debug("on_file_importsvg()")
  6626. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6627. try:
  6628. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6629. directory=self.get_last_folder(), filter=_filter_)
  6630. except TypeError:
  6631. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6632. filter=_filter_)
  6633. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6634. type_of_obj = "geometry"
  6635. filenames = [str(filename) for filename in filenames]
  6636. if len(filenames) == 0:
  6637. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6638. else:
  6639. for filename in filenames:
  6640. if filename != '':
  6641. self.worker_task.emit({'fcn': self.import_svg,
  6642. 'params': [filename, type_of_obj]})
  6643. def on_file_importdxf(self, type_of_obj):
  6644. """
  6645. Callback for menu item File->Import DXF.
  6646. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6647. :type type_of_obj: str
  6648. :return: None
  6649. """
  6650. self.defaults.report_usage("on_file_importdxf")
  6651. App.log.debug("on_file_importdxf()")
  6652. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6653. try:
  6654. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6655. directory=self.get_last_folder(),
  6656. filter=_filter_)
  6657. except TypeError:
  6658. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6659. filter=_filter_)
  6660. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6661. type_of_obj = "geometry"
  6662. filenames = [str(filename) for filename in filenames]
  6663. if len(filenames) == 0:
  6664. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6665. else:
  6666. for filename in filenames:
  6667. if filename != '':
  6668. self.worker_task.emit({'fcn': self.import_dxf,
  6669. 'params': [filename, type_of_obj]})
  6670. # ###############################################################################################################
  6671. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6672. # ###############################################################################################################
  6673. def init_code_editor(self, name):
  6674. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6675. # add the tab if it was closed
  6676. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6677. self.text_editor_tab.setObjectName('text_editor_tab')
  6678. # delete the absolute and relative position and messages in the infobar
  6679. self.ui.position_label.setText("")
  6680. self.ui.rel_position_label.setText("")
  6681. # first clear previous text in text editor (if any)
  6682. self.text_editor_tab.code_editor.clear()
  6683. self.text_editor_tab.code_editor.setReadOnly(False)
  6684. self.toggle_codeeditor = True
  6685. self.text_editor_tab.code_editor.completer_enable = False
  6686. self.text_editor_tab.buttonRun.hide()
  6687. # make sure to keep a reference to the code editor
  6688. self.reference_code_editor = self.text_editor_tab.code_editor
  6689. # Switch plot_area to CNCJob tab
  6690. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6691. def on_view_source(self):
  6692. """
  6693. Called when the user wants to see the source file of the selected object
  6694. :return:
  6695. """
  6696. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6697. self.proc_container.view.set_busy(_("Loading..."))
  6698. try:
  6699. obj = self.collection.get_active()
  6700. except Exception as e:
  6701. log.debug("App.on_view_source() --> %s" % str(e))
  6702. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6703. return 'fail'
  6704. if obj is None:
  6705. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6706. return 'fail'
  6707. flt = "All Files (*.*)"
  6708. if obj.kind == 'gerber':
  6709. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6710. elif obj.kind == 'excellon':
  6711. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6712. elif obj.kind == 'cncjob':
  6713. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6714. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6715. # add the tab if it was closed
  6716. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6717. self.source_editor_tab.setObjectName('source_editor_tab')
  6718. # delete the absolute and relative position and messages in the infobar
  6719. self.ui.position_label.setText("")
  6720. self.ui.rel_position_label.setText("")
  6721. # first clear previous text in text editor (if any)
  6722. self.source_editor_tab.code_editor.clear()
  6723. self.source_editor_tab.code_editor.setReadOnly(False)
  6724. self.source_editor_tab.code_editor.completer_enable = False
  6725. self.source_editor_tab.buttonRun.hide()
  6726. # Switch plot_area to CNCJob tab
  6727. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6728. try:
  6729. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6730. except TypeError:
  6731. pass
  6732. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6733. try:
  6734. self.source_editor_tab.buttonSave.clicked.disconnect()
  6735. except TypeError:
  6736. pass
  6737. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6738. # then append the text from GCode to the text editor
  6739. if obj.kind == 'cncjob':
  6740. try:
  6741. file = obj.export_gcode(
  6742. preamble=self.defaults["cncjob_prepend"],
  6743. postamble=self.defaults["cncjob_append"],
  6744. to_file=True)
  6745. if file == 'fail':
  6746. return 'fail'
  6747. except AttributeError:
  6748. self.inform.emit('[WARNING_NOTCL] %s' %
  6749. _("There is no selected object for which to see it's source file code."))
  6750. return 'fail'
  6751. else:
  6752. try:
  6753. file = StringIO(obj.source_file)
  6754. except (AttributeError, TypeError):
  6755. self.inform.emit('[WARNING_NOTCL] %s' %
  6756. _("There is no selected object for which to see it's source file code."))
  6757. return 'fail'
  6758. self.source_editor_tab.t_frame.hide()
  6759. try:
  6760. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6761. # for line in file:
  6762. # QtWidgets.QApplication.processEvents()
  6763. # proc_line = str(line).strip('\n')
  6764. # self.source_editor_tab.code_editor.append(proc_line)
  6765. except Exception as e:
  6766. log.debug('App.on_view_source() -->%s' % str(e))
  6767. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6768. return
  6769. self.source_editor_tab.handleTextChanged()
  6770. self.source_editor_tab.t_frame.show()
  6771. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6772. self.proc_container.view.set_idle()
  6773. # self.ui.show()
  6774. def on_toggle_code_editor(self):
  6775. self.defaults.report_usage("on_toggle_code_editor()")
  6776. if self.toggle_codeeditor is False:
  6777. self.init_code_editor(name=_("Code Editor"))
  6778. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6779. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6780. self.text_editor_tab.buttonSave.clicked.disconnect()
  6781. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6782. else:
  6783. for idx in range(self.ui.plot_tab_area.count()):
  6784. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6785. self.ui.plot_tab_area.closeTab(idx)
  6786. break
  6787. self.toggle_codeeditor = False
  6788. def on_code_editor_close(self):
  6789. self.toggle_codeeditor = False
  6790. def goto_text_line(self):
  6791. """
  6792. Will scroll a text to the specified text line.
  6793. :return: None
  6794. """
  6795. dia_box = Dialog_box(title=_("Go to Line ..."),
  6796. label=_("Line:"),
  6797. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6798. initial_text='')
  6799. try:
  6800. line = int(dia_box.location) - 1
  6801. except (ValueError, TypeError):
  6802. line = 0
  6803. if dia_box.ok:
  6804. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6805. # at the top of the window
  6806. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6807. # get the document() of the TextEditor
  6808. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6809. # create a Text Cursor based on the searched line
  6810. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6811. # set cursor of the code editor with the cursor at the searcehd line
  6812. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6813. def on_filenewscript(self, silent=False):
  6814. """
  6815. Will create a new script file and open it in the Code Editor
  6816. :param silent: if True will not display status messages
  6817. :param name: if specified will be the name of the new script
  6818. :param text: pass a source file to the newly created script to be loaded in it
  6819. :return: None
  6820. """
  6821. if silent is False:
  6822. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6823. # delete the absolute and relative position and messages in the infobar
  6824. self.ui.position_label.setText("")
  6825. self.ui.rel_position_label.setText("")
  6826. self.new_script_object()
  6827. # script_text = script_obj.source_file
  6828. #
  6829. # self.proc_container.view.set_busy(_("Loading..."))
  6830. # script_obj.script_editor_tab.t_frame.hide()
  6831. #
  6832. # script_obj.script_editor_tab.t_frame.show()
  6833. # self.proc_container.view.set_idle()
  6834. def on_fileopenscript(self, name=None, silent=False):
  6835. """
  6836. Will open a Tcl script file into the Code Editor
  6837. :param silent: if True will not display status messages
  6838. :param name: name of a Tcl script file to open
  6839. :return: None
  6840. """
  6841. self.defaults.report_usage("on_fileopenscript")
  6842. App.log.debug("on_fileopenscript()")
  6843. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6844. "All Files (*.*)"
  6845. if name:
  6846. filenames = [name]
  6847. else:
  6848. try:
  6849. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6850. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6851. except TypeError:
  6852. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6853. if len(filenames) == 0:
  6854. if silent is False:
  6855. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6856. else:
  6857. for filename in filenames:
  6858. if filename != '':
  6859. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6860. def on_fileopenscript_example(self, name=None, silent=False):
  6861. """
  6862. Will open a Tcl script file into the Code Editor
  6863. :param silent: if True will not display status messages
  6864. :param name: name of a Tcl script file to open
  6865. :return:
  6866. """
  6867. self.defaults.report_usage("on_fileopenscript_example")
  6868. log.debug("on_fileopenscript_example()")
  6869. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6870. "All Files (*.*)"
  6871. # test if the app was frozen and choose the path for the configuration file
  6872. if getattr(sys, "frozen", False) is True:
  6873. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6874. else:
  6875. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6876. if name:
  6877. filenames = [name]
  6878. else:
  6879. try:
  6880. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6881. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6882. except TypeError:
  6883. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6884. if len(filenames) == 0:
  6885. if silent is False:
  6886. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6887. else:
  6888. for filename in filenames:
  6889. if filename != '':
  6890. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6891. def on_filerunscript(self, name=None, silent=False):
  6892. """
  6893. File menu callback for loading and running a TCL script.
  6894. :param silent: if True will not display status messages
  6895. :param name: name of a Tcl script file to be run by FlatCAM
  6896. :return: None
  6897. """
  6898. self.defaults.report_usage("on_filerunscript")
  6899. App.log.debug("on_file_runscript()")
  6900. if name:
  6901. filename = name
  6902. if self.cmd_line_headless != 1:
  6903. self.splash.showMessage('%s: %ssec\n%s' %
  6904. (_("Canvas initialization started.\n"
  6905. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6906. _("Executing ScriptObject file.")
  6907. ),
  6908. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6909. color=QtGui.QColor("gray"))
  6910. else:
  6911. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6912. "All Files (*.*)"
  6913. try:
  6914. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6915. directory=self.get_last_folder(), filter=_filter_)
  6916. except TypeError:
  6917. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6918. # The Qt methods above will return a QString which can cause problems later.
  6919. # So far json.dump() will fail to serialize it.
  6920. filename = str(filename)
  6921. if filename == "":
  6922. if silent is False:
  6923. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6924. else:
  6925. if self.cmd_line_headless != 1:
  6926. if self.ui.shell_dock.isHidden():
  6927. self.ui.shell_dock.show()
  6928. try:
  6929. with open(filename, "r") as tcl_script:
  6930. cmd_line_shellfile_content = tcl_script.read()
  6931. if self.cmd_line_headless != 1:
  6932. self.shell.exec_command(cmd_line_shellfile_content)
  6933. else:
  6934. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6935. if silent is False:
  6936. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6937. except Exception as e:
  6938. log.debug("App.on_filerunscript() -> %s" % str(e))
  6939. sys.exit(2)
  6940. def on_file_saveproject(self, silent=False):
  6941. """
  6942. Callback for menu item File->Save Project. Saves the project to
  6943. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6944. if set to None. The project is saved by calling ``self.save_project()``.
  6945. :param silent: if True will not display status messages
  6946. :return: None
  6947. """
  6948. self.defaults.report_usage("on_file_saveproject")
  6949. if self.project_filename is None:
  6950. self.on_file_saveprojectas()
  6951. else:
  6952. self.worker_task.emit({'fcn': self.save_project,
  6953. 'params': [self.project_filename, silent]})
  6954. if self.defaults["global_open_style"] is False:
  6955. self.file_opened.emit("project", self.project_filename)
  6956. self.file_saved.emit("project", self.project_filename)
  6957. self.set_ui_title(name=self.project_filename)
  6958. self.should_we_save = False
  6959. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6960. """
  6961. Callback for menu item File->Save Project As... Opens a file
  6962. chooser and saves the project to the given file via
  6963. ``self.save_project()``.
  6964. :param make_copy if to be create a copy of the project; boolean
  6965. :param use_thread: if to be run in a separate thread; boolean
  6966. :param quit_action: if to be followed by quiting the application; boolean
  6967. :return: None
  6968. """
  6969. self.defaults.report_usage("on_file_saveprojectas")
  6970. self.date = str(datetime.today()).rpartition('.')[0]
  6971. self.date = ''.join(c for c in self.date if c not in ':-')
  6972. self.date = self.date.replace(' ', '_')
  6973. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6974. try:
  6975. filename, _f = FCFileSaveDialog.get_saved_filename(
  6976. caption=_("Save Project As ..."),
  6977. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6978. proj=_("Project")),
  6979. filter=filter_
  6980. )
  6981. except TypeError:
  6982. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6983. filename = str(filename)
  6984. if filename == '':
  6985. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6986. return
  6987. if use_thread is True:
  6988. self.worker_task.emit({'fcn': self.save_project,
  6989. 'params': [filename, quit_action]})
  6990. else:
  6991. self.save_project(filename, quit_action)
  6992. # self.save_project(filename)
  6993. if self.defaults["global_open_style"] is False:
  6994. self.file_opened.emit("project", filename)
  6995. self.file_saved.emit("project", filename)
  6996. if not make_copy:
  6997. self.project_filename = filename
  6998. self.set_ui_title(name=self.project_filename)
  6999. self.should_we_save = False
  7000. def on_file_save_objects_pdf(self, use_thread=True):
  7001. self.date = str(datetime.today()).rpartition('.')[0]
  7002. self.date = ''.join(c for c in self.date if c not in ':-')
  7003. self.date = self.date.replace(' ', '_')
  7004. try:
  7005. obj_selection = self.collection.get_selected()
  7006. if len(obj_selection) == 1:
  7007. obj_name = str(obj_selection[0].options['name'])
  7008. else:
  7009. obj_name = _("FlatCAM objects print")
  7010. except AttributeError as err:
  7011. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7012. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7013. return
  7014. if not obj_selection:
  7015. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7016. return
  7017. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7018. try:
  7019. filename, _f = FCFileSaveDialog.get_saved_filename(
  7020. caption=_("Save Object as PDF ..."),
  7021. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7022. obj_name=obj_name,
  7023. date=self.date),
  7024. filter=filter_
  7025. )
  7026. except TypeError:
  7027. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7028. filename = str(filename)
  7029. if filename == '':
  7030. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7031. return
  7032. if use_thread is True:
  7033. self.proc_container.new(_("Printing PDF ... Please wait."))
  7034. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7035. else:
  7036. self.save_pdf(filename, obj_selection)
  7037. # self.save_project(filename)
  7038. if self.defaults["global_open_style"] is False:
  7039. self.file_opened.emit("pdf", filename)
  7040. self.file_saved.emit("pdf", filename)
  7041. def save_pdf(self, file_name, obj_selection):
  7042. p_size = self.defaults['global_workspaceT']
  7043. orientation = self.defaults['global_workspace_orientation']
  7044. color = 'black'
  7045. transparency_level = 1.0
  7046. self.pagesize = {}
  7047. self.pagesize.update(
  7048. {
  7049. 'Bounds': None,
  7050. 'A0': (841 * mm, 1189 * mm),
  7051. 'A1': (594 * mm, 841 * mm),
  7052. 'A2': (420 * mm, 594 * mm),
  7053. 'A3': (297 * mm, 420 * mm),
  7054. 'A4': (210 * mm, 297 * mm),
  7055. 'A5': (148 * mm, 210 * mm),
  7056. 'A6': (105 * mm, 148 * mm),
  7057. 'A7': (74 * mm, 105 * mm),
  7058. 'A8': (52 * mm, 74 * mm),
  7059. 'A9': (37 * mm, 52 * mm),
  7060. 'A10': (26 * mm, 37 * mm),
  7061. 'B0': (1000 * mm, 1414 * mm),
  7062. 'B1': (707 * mm, 1000 * mm),
  7063. 'B2': (500 * mm, 707 * mm),
  7064. 'B3': (353 * mm, 500 * mm),
  7065. 'B4': (250 * mm, 353 * mm),
  7066. 'B5': (176 * mm, 250 * mm),
  7067. 'B6': (125 * mm, 176 * mm),
  7068. 'B7': (88 * mm, 125 * mm),
  7069. 'B8': (62 * mm, 88 * mm),
  7070. 'B9': (44 * mm, 62 * mm),
  7071. 'B10': (31 * mm, 44 * mm),
  7072. 'C0': (917 * mm, 1297 * mm),
  7073. 'C1': (648 * mm, 917 * mm),
  7074. 'C2': (458 * mm, 648 * mm),
  7075. 'C3': (324 * mm, 458 * mm),
  7076. 'C4': (229 * mm, 324 * mm),
  7077. 'C5': (162 * mm, 229 * mm),
  7078. 'C6': (114 * mm, 162 * mm),
  7079. 'C7': (81 * mm, 114 * mm),
  7080. 'C8': (57 * mm, 81 * mm),
  7081. 'C9': (40 * mm, 57 * mm),
  7082. 'C10': (28 * mm, 40 * mm),
  7083. # American paper sizes
  7084. 'LETTER': (8.5 * inch, 11 * inch),
  7085. 'LEGAL': (8.5 * inch, 14 * inch),
  7086. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7087. # From https://en.wikipedia.org/wiki/Paper_size
  7088. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7089. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7090. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7091. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7092. 'LEDGER': (17 * inch, 11 * inch),
  7093. }
  7094. )
  7095. exported_svg = []
  7096. for obj in obj_selection:
  7097. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7098. scale_factor_x=None, scale_factor_y=None,
  7099. skew_factor_x=None, skew_factor_y=None,
  7100. mirror=None)
  7101. if obj.kind.lower() == 'gerber':
  7102. # color = self.defaults["gerber_plot_fill"][:-2]
  7103. color = obj.fill_color[:-2]
  7104. elif obj.kind.lower() == 'excellon':
  7105. color = '#C40000'
  7106. elif obj.kind.lower() == 'geometry':
  7107. color = self.defaults["global_draw_color"]
  7108. # Change the attributes of the exported SVG
  7109. # We don't need stroke-width
  7110. # We set opacity to maximum
  7111. # We set the colour to WHITE
  7112. root = ET.fromstring(svg_obj)
  7113. for child in root:
  7114. child.set('fill', str(color))
  7115. child.set('opacity', str(transparency_level))
  7116. child.set('stroke', str(color))
  7117. exported_svg.append(ET.tostring(root))
  7118. xmin = Inf
  7119. ymin = Inf
  7120. xmax = -Inf
  7121. ymax = -Inf
  7122. for obj in obj_selection:
  7123. try:
  7124. gxmin, gymin, gxmax, gymax = obj.bounds()
  7125. xmin = min([xmin, gxmin])
  7126. ymin = min([ymin, gymin])
  7127. xmax = max([xmax, gxmax])
  7128. ymax = max([ymax, gymax])
  7129. except Exception as e:
  7130. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7131. # Determine bounding area for svg export
  7132. bounds = [xmin, ymin, xmax, ymax]
  7133. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7134. # This contain the measure units
  7135. uom = obj_selection[0].units.lower()
  7136. # Define a boundary around SVG of about 1.0mm (~39mils)
  7137. if uom in "mm":
  7138. boundary = 1.0
  7139. else:
  7140. boundary = 0.0393701
  7141. # Convert everything to strings for use in the xml doc
  7142. svgwidth = str(size[0] + (2 * boundary))
  7143. svgheight = str(size[1] + (2 * boundary))
  7144. minx = str(bounds[0] - boundary)
  7145. miny = str(bounds[1] + boundary + size[1])
  7146. # Add a SVG Header and footer to the svg output from shapely
  7147. # The transform flips the Y Axis so that everything renders
  7148. # properly within svg apps such as inkscape
  7149. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7150. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7151. svg_header += 'width="' + svgwidth + uom + '" '
  7152. svg_header += 'height="' + svgheight + uom + '" '
  7153. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7154. svg_header += '>'
  7155. svg_header += '<g transform="scale(1,-1)">'
  7156. svg_footer = '</g> </svg>'
  7157. svg_elem = str(svg_header)
  7158. for svg_item in exported_svg:
  7159. svg_elem += str(svg_item)
  7160. svg_elem += str(svg_footer)
  7161. # Parse the xml through a xml parser just to add line feeds
  7162. # and to make it look more pretty for the output
  7163. doc = parse_xml_string(svg_elem)
  7164. doc_final = doc.toprettyxml()
  7165. try:
  7166. if self.defaults['units'].upper() == 'IN':
  7167. unit = inch
  7168. else:
  7169. unit = mm
  7170. doc_final = StringIO(doc_final)
  7171. drawing = svg2rlg(doc_final)
  7172. if p_size == 'Bounds':
  7173. renderPDF.drawToFile(drawing, file_name)
  7174. else:
  7175. if orientation == 'p':
  7176. page_size = portrait(self.pagesize[p_size])
  7177. else:
  7178. page_size = landscape(self.pagesize[p_size])
  7179. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7180. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7181. renderPDF.draw(drawing, my_canvas, 0, 0)
  7182. my_canvas.save()
  7183. except Exception as e:
  7184. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7185. return 'fail'
  7186. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7187. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7188. """
  7189. Exports a Geometry Object to an SVG file.
  7190. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7191. :param filename: Path to the SVG file to save to.
  7192. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7193. :return:
  7194. """
  7195. self.defaults.report_usage("export_svg()")
  7196. if filename is None:
  7197. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7198. is not None else self.defaults["global_last_folder"]
  7199. self.log.debug("export_svg()")
  7200. try:
  7201. obj = self.collection.get_by_name(str(obj_name))
  7202. except Exception:
  7203. # TODO: The return behavior has not been established... should raise exception?
  7204. return "Could not retrieve object: %s" % obj_name
  7205. with self.proc_container.new(_("Exporting SVG")) as proc:
  7206. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7207. # Determine bounding area for svg export
  7208. bounds = obj.bounds()
  7209. size = obj.size()
  7210. # Convert everything to strings for use in the xml doc
  7211. svgwidth = str(size[0])
  7212. svgheight = str(size[1])
  7213. minx = str(bounds[0])
  7214. miny = str(bounds[1] - size[1])
  7215. uom = obj.units.lower()
  7216. # Add a SVG Header and footer to the svg output from shapely
  7217. # The transform flips the Y Axis so that everything renders
  7218. # properly within svg apps such as inkscape
  7219. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7220. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7221. svg_header += 'width="' + svgwidth + uom + '" '
  7222. svg_header += 'height="' + svgheight + uom + '" '
  7223. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7224. svg_header += '<g transform="scale(1,-1)">'
  7225. svg_footer = '</g> </svg>'
  7226. svg_elem = svg_header + exported_svg + svg_footer
  7227. # Parse the xml through a xml parser just to add line feeds
  7228. # and to make it look more pretty for the output
  7229. svgcode = parse_xml_string(svg_elem)
  7230. svgcode = svgcode.toprettyxml()
  7231. try:
  7232. with open(filename, 'w') as fp:
  7233. fp.write(svgcode)
  7234. except PermissionError:
  7235. self.inform.emit('[WARNING] %s' %
  7236. _("Permission denied, saving not possible.\n"
  7237. "Most likely another app is holding the file open and not accessible."))
  7238. return 'fail'
  7239. if self.defaults["global_open_style"] is False:
  7240. self.file_opened.emit("SVG", filename)
  7241. self.file_saved.emit("SVG", filename)
  7242. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7243. def save_source_file(self, obj_name, filename, use_thread=True):
  7244. """
  7245. Exports a FlatCAM Object to an Gerber/Excellon file.
  7246. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7247. :param filename: Path to the Gerber file to save to.
  7248. :param use_thread: if to be run in a separate thread
  7249. :return:
  7250. """
  7251. self.defaults.report_usage("save source file()")
  7252. if filename is None:
  7253. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7254. is not None else self.defaults["global_last_folder"]
  7255. self.log.debug("save source file()")
  7256. obj = self.collection.get_by_name(obj_name)
  7257. file_string = StringIO(obj.source_file)
  7258. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7259. if file_string.getvalue() == '':
  7260. self.inform.emit('[ERROR_NOTCL] %s' %
  7261. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7262. return 'fail'
  7263. try:
  7264. with open(filename, 'w') as file:
  7265. file.writelines('G04*\n')
  7266. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7267. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7268. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7269. file.writelines('G04 Created on : %s*\n' % time_string)
  7270. for line in file_string:
  7271. file.writelines(line)
  7272. except PermissionError:
  7273. self.inform.emit('[WARNING] %s' %
  7274. _("Permission denied, saving not possible.\n"
  7275. "Most likely another app is holding the file open and not accessible."))
  7276. return 'fail'
  7277. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7278. """
  7279. Exports a Excellon Object to an Excellon file.
  7280. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7281. :param filename: Path to the Excellon file to save to.
  7282. :param local_use:
  7283. :param use_thread: if to be run in a separate thread
  7284. :return:
  7285. """
  7286. self.defaults.report_usage("export_excellon()")
  7287. if filename is None:
  7288. if self.defaults["global_last_save_folder"]:
  7289. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7290. else:
  7291. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7292. self.log.debug("export_excellon()")
  7293. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7294. self.defaults["excellon_exp_decimals"]
  7295. )
  7296. if local_use is None:
  7297. try:
  7298. obj = self.collection.get_by_name(str(obj_name))
  7299. except Exception:
  7300. return "Could not retrieve object: %s" % obj_name
  7301. else:
  7302. obj = local_use
  7303. if not isinstance(obj, ExcellonObject):
  7304. self.inform.emit('[ERROR_NOTCL] %s' %
  7305. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7306. return
  7307. # updated units
  7308. eunits = self.defaults["excellon_exp_units"]
  7309. ewhole = self.defaults["excellon_exp_integer"]
  7310. efract = self.defaults["excellon_exp_decimals"]
  7311. ezeros = self.defaults["excellon_exp_zeros"]
  7312. eformat = self.defaults["excellon_exp_format"]
  7313. slot_type = self.defaults["excellon_exp_slot_type"]
  7314. fc_units = self.defaults['units'].upper()
  7315. if fc_units == 'MM':
  7316. factor = 1 if eunits == 'METRIC' else 0.03937
  7317. else:
  7318. factor = 25.4 if eunits == 'METRIC' else 1
  7319. def make_excellon():
  7320. try:
  7321. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7322. header = 'M48\n'
  7323. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7324. (str(self.version), str(self.version_date))
  7325. header += ';Filename: %s' % str(obj_name) + '\n'
  7326. header += ';Created on : %s' % time_str + '\n'
  7327. if eformat == 'dec':
  7328. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7329. header += eunits + '\n'
  7330. for tool in obj.tools:
  7331. if eunits == 'METRIC':
  7332. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7333. tool=str(tool),
  7334. dec=2)
  7335. else:
  7336. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7337. tool=str(tool),
  7338. dec=4)
  7339. else:
  7340. if ezeros == 'LZ':
  7341. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7342. form='ndec', e_zeros='LZ', factor=factor,
  7343. slot_type=slot_type)
  7344. header += '%s,%s\n' % (eunits, 'LZ')
  7345. header += format_exc
  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. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7357. form='ndec', e_zeros='TZ', factor=factor,
  7358. slot_type=slot_type)
  7359. header += '%s,%s\n' % (eunits, 'TZ')
  7360. header += format_exc
  7361. for tool in obj.tools:
  7362. if eunits == 'METRIC':
  7363. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7364. tool=str(tool),
  7365. dec=2)
  7366. else:
  7367. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7368. tool=str(tool),
  7369. dec=4)
  7370. header += '%\n'
  7371. footer = 'M30\n'
  7372. exported_excellon = header
  7373. exported_excellon += excellon_code
  7374. exported_excellon += footer
  7375. if local_use is None:
  7376. try:
  7377. with open(filename, 'w') as fp:
  7378. fp.write(exported_excellon)
  7379. except PermissionError:
  7380. self.inform.emit('[WARNING] %s' %
  7381. _("Permission denied, saving not possible.\n"
  7382. "Most likely another app is holding the file open and not accessible."))
  7383. return 'fail'
  7384. if self.defaults["global_open_style"] is False:
  7385. self.file_opened.emit("Excellon", filename)
  7386. self.file_saved.emit("Excellon", filename)
  7387. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7388. else:
  7389. return exported_excellon
  7390. except Exception as e:
  7391. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7392. return 'fail'
  7393. if use_thread is True:
  7394. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7395. def job_thread_exc(app_obj):
  7396. ret = make_excellon()
  7397. if ret == 'fail':
  7398. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7399. return
  7400. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7401. else:
  7402. eret = make_excellon()
  7403. if eret == 'fail':
  7404. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7405. return 'fail'
  7406. if local_use is not None:
  7407. return eret
  7408. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7409. """
  7410. Exports a Gerber Object to an Gerber file.
  7411. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7412. :param filename: Path to the Gerber file to save to.
  7413. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7414. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7415. :param use_thread: if to be run in a separate thread
  7416. :return:
  7417. """
  7418. self.defaults.report_usage("export_gerber()")
  7419. if filename is None:
  7420. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7421. is not None else self.defaults["global_last_folder"]
  7422. self.log.debug("export_gerber()")
  7423. if local_use is None:
  7424. try:
  7425. obj = self.collection.get_by_name(str(obj_name))
  7426. except Exception:
  7427. return "Could not retrieve object: %s" % obj_name
  7428. else:
  7429. obj = local_use
  7430. # updated units
  7431. gunits = self.defaults["gerber_exp_units"]
  7432. gwhole = self.defaults["gerber_exp_integer"]
  7433. gfract = self.defaults["gerber_exp_decimals"]
  7434. gzeros = self.defaults["gerber_exp_zeros"]
  7435. fc_units = self.defaults['units'].upper()
  7436. if fc_units == 'MM':
  7437. factor = 1 if gunits == 'MM' else 0.03937
  7438. else:
  7439. factor = 25.4 if gunits == 'MM' else 1
  7440. def make_gerber():
  7441. try:
  7442. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7443. header = 'G04*\n'
  7444. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7445. (str(self.version), str(self.version_date))
  7446. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7447. header += 'G04 Created on : %s*' % time_str + '\n'
  7448. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7449. header += "%MO{units}*%\n".format(units=gunits)
  7450. for apid in obj.apertures:
  7451. if obj.apertures[apid]['type'] == 'C':
  7452. header += "%ADD{apid}{type},{size}*%\n".format(
  7453. apid=str(apid),
  7454. type='C',
  7455. size=(factor * obj.apertures[apid]['size'])
  7456. )
  7457. elif obj.apertures[apid]['type'] == 'R':
  7458. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7459. apid=str(apid),
  7460. type='R',
  7461. width=(factor * obj.apertures[apid]['width']),
  7462. height=(factor * obj.apertures[apid]['height'])
  7463. )
  7464. elif obj.apertures[apid]['type'] == 'O':
  7465. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7466. apid=str(apid),
  7467. type='O',
  7468. width=(factor * obj.apertures[apid]['width']),
  7469. height=(factor * obj.apertures[apid]['height'])
  7470. )
  7471. header += '\n'
  7472. # obsolete units but some software may need it
  7473. if gunits == 'IN':
  7474. header += 'G70*\n'
  7475. else:
  7476. header += 'G71*\n'
  7477. # Absolute Mode
  7478. header += 'G90*\n'
  7479. header += 'G01*\n'
  7480. # positive polarity
  7481. header += '%LPD*%\n'
  7482. footer = 'M02*\n'
  7483. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7484. exported_gerber = header
  7485. exported_gerber += gerber_code
  7486. exported_gerber += footer
  7487. if local_use is None:
  7488. try:
  7489. with open(filename, 'w') as fp:
  7490. fp.write(exported_gerber)
  7491. except PermissionError:
  7492. self.inform.emit('[WARNING] %s' %
  7493. _("Permission denied, saving not possible.\n"
  7494. "Most likely another app is holding the file open and not accessible."))
  7495. return 'fail'
  7496. if self.defaults["global_open_style"] is False:
  7497. self.file_opened.emit("Gerber", filename)
  7498. self.file_saved.emit("Gerber", filename)
  7499. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7500. else:
  7501. return exported_gerber
  7502. except Exception as e:
  7503. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7504. return 'fail'
  7505. if use_thread is True:
  7506. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7507. def job_thread_grb(app_obj):
  7508. ret = make_gerber()
  7509. if ret == 'fail':
  7510. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7511. return
  7512. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7513. else:
  7514. gret = make_gerber()
  7515. if gret == 'fail':
  7516. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7517. return 'fail'
  7518. if local_use is not None:
  7519. return gret
  7520. def export_dxf(self, obj_name, filename, use_thread=True):
  7521. """
  7522. Exports a Geometry Object to an DXF file.
  7523. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7524. :param filename: Path to the DXF file to save to.
  7525. :param use_thread: if to be run in a separate thread
  7526. :return:
  7527. """
  7528. self.defaults.report_usage("export_dxf()")
  7529. if filename is None:
  7530. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7531. is not None else self.defaults["global_last_folder"]
  7532. self.log.debug("export_dxf()")
  7533. try:
  7534. obj = self.collection.get_by_name(str(obj_name))
  7535. except Exception:
  7536. # TODO: The return behavior has not been established... should raise exception?
  7537. return "Could not retrieve object: %s" % obj_name
  7538. def make_dxf():
  7539. try:
  7540. dxf_code = obj.export_dxf()
  7541. dxf_code.saveas(filename)
  7542. if self.defaults["global_open_style"] is False:
  7543. self.file_opened.emit("DXF", filename)
  7544. self.file_saved.emit("DXF", filename)
  7545. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7546. except Exception:
  7547. return 'fail'
  7548. if use_thread is True:
  7549. with self.proc_container.new(_("Exporting DXF")) as proc:
  7550. def job_thread_exc(app_obj):
  7551. ret_dxf_val = make_dxf()
  7552. if ret_dxf_val == 'fail':
  7553. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7554. return
  7555. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7556. else:
  7557. ret = make_dxf()
  7558. if ret == 'fail':
  7559. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7560. return
  7561. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7562. """
  7563. Adds a new Geometry Object to the projects and populates
  7564. it with shapes extracted from the SVG file.
  7565. :param plot: If True then the resulting object will be plotted on canvas
  7566. :param filename: Path to the SVG file.
  7567. :param geo_type: Type of FlatCAM object that will be created from SVG
  7568. :param outname: The name given to the resulting FlatCAM object
  7569. :return:
  7570. """
  7571. self.defaults.report_usage("import_svg()")
  7572. log.debug("App.import_svg()")
  7573. obj_type = ""
  7574. if geo_type is None or geo_type == "geometry":
  7575. obj_type = "geometry"
  7576. elif geo_type == "gerber":
  7577. obj_type = "gerber"
  7578. else:
  7579. self.inform.emit('[ERROR_NOTCL] %s' %
  7580. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7581. return
  7582. units = self.defaults['units'].upper()
  7583. def obj_init(geo_obj, app_obj):
  7584. geo_obj.import_svg(filename, obj_type, units=units)
  7585. geo_obj.multigeo = False
  7586. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7587. with self.proc_container.new(_("Importing SVG")) as proc:
  7588. # Object name
  7589. name = outname or filename.split('/')[-1].split('\\')[-1]
  7590. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7591. if ret == 'fail':
  7592. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7593. return 'fail'
  7594. # Register recent file
  7595. self.file_opened.emit("svg", filename)
  7596. # GUI feedback
  7597. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7598. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7599. """
  7600. Adds a new Geometry Object to the projects and populates
  7601. it with shapes extracted from the DXF file.
  7602. :param filename: Path to the DXF file.
  7603. :param geo_type: Type of FlatCAM object that will be created from DXF
  7604. :param outname: Name for the imported Geometry
  7605. :param plot: If True then the resulting object will be plotted on canvas
  7606. :return:
  7607. """
  7608. self.defaults.report_usage("import_dxf()")
  7609. obj_type = ""
  7610. if geo_type is None or geo_type == "geometry":
  7611. obj_type = "geometry"
  7612. elif geo_type == "gerber":
  7613. obj_type = geo_type
  7614. else:
  7615. self.inform.emit('[ERROR_NOTCL] %s' %
  7616. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7617. return
  7618. units = self.defaults['units'].upper()
  7619. def obj_init(geo_obj, app_obj):
  7620. geo_obj.import_dxf(filename, obj_type, units=units)
  7621. geo_obj.multigeo = False
  7622. with self.proc_container.new(_("Importing DXF")):
  7623. # Object name
  7624. name = outname or filename.split('/')[-1].split('\\')[-1]
  7625. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7626. if ret == 'fail':
  7627. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7628. return 'fail'
  7629. # Register recent file
  7630. self.file_opened.emit("dxf", filename)
  7631. # GUI feedback
  7632. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7633. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7634. """
  7635. Opens a Gerber file, parses it and creates a new object for
  7636. it in the program. Thread-safe.
  7637. :param outname: Name of the resulting object. None causes the
  7638. name to be that of the file. Str.
  7639. :param filename: Gerber file filename
  7640. :type filename: str
  7641. :param plot: boolean, to plot or not the resulting object
  7642. :param from_tcl: True if run from Tcl Shell
  7643. :return: None
  7644. """
  7645. # How the object should be initialized
  7646. def obj_init(gerber_obj, app_obj):
  7647. assert isinstance(gerber_obj, GerberObject), \
  7648. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7649. # Opening the file happens here
  7650. try:
  7651. gerber_obj.parse_file(filename)
  7652. except IOError:
  7653. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7654. return "fail"
  7655. except ParseError as err:
  7656. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7657. app_obj.log.error(str(err))
  7658. return "fail"
  7659. except Exception as e:
  7660. log.debug("App.open_gerber() --> %s" % str(e))
  7661. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7662. msg += traceback.format_exc()
  7663. app_obj.inform.emit(msg)
  7664. return "fail"
  7665. if gerber_obj.is_empty():
  7666. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7667. _("Object is not Gerber file or empty. Aborting object creation."))
  7668. return "fail"
  7669. App.log.debug("open_gerber()")
  7670. with self.proc_container.new(_("Opening Gerber")):
  7671. # Object name
  7672. name = outname or filename.split('/')[-1].split('\\')[-1]
  7673. # # ## Object creation # ##
  7674. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7675. if ret_val == 'fail':
  7676. if from_tcl:
  7677. filename = self.defaults['global_tcl_path'] + '/' + name
  7678. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7679. if ret_val == 'fail':
  7680. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7681. return 'fail'
  7682. # Register recent file
  7683. self.file_opened.emit("gerber", filename)
  7684. # GUI feedback
  7685. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7686. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7687. """
  7688. Opens an Excellon file, parses it and creates a new object for
  7689. it in the program. Thread-safe.
  7690. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7691. :param filename: Excellon file filename
  7692. :type filename: str
  7693. :param plot: boolean, to plot or not the resulting object
  7694. :param from_tcl: True if run from Tcl Shell
  7695. :return: None
  7696. """
  7697. App.log.debug("open_excellon()")
  7698. # How the object should be initialized
  7699. def obj_init(excellon_obj, app_obj):
  7700. try:
  7701. ret = excellon_obj.parse_file(filename=filename)
  7702. if ret == "fail":
  7703. log.debug("Excellon parsing failed.")
  7704. self.inform.emit('[ERROR_NOTCL] %s' %
  7705. _("This is not Excellon file."))
  7706. return "fail"
  7707. except IOError:
  7708. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7709. (_("Cannot open file"), filename))
  7710. log.debug("Could not open Excellon object.")
  7711. return "fail"
  7712. except Exception:
  7713. msg = '[ERROR_NOTCL] %s' % \
  7714. _("An internal error has occurred. See shell.\n")
  7715. msg += traceback.format_exc()
  7716. app_obj.inform.emit(msg)
  7717. return "fail"
  7718. ret = excellon_obj.create_geometry()
  7719. if ret == 'fail':
  7720. log.debug("Could not create geometry for Excellon object.")
  7721. return "fail"
  7722. for tool in excellon_obj.tools:
  7723. if excellon_obj.tools[tool]['solid_geometry']:
  7724. return
  7725. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7726. return "fail"
  7727. with self.proc_container.new(_("Opening Excellon.")):
  7728. # Object name
  7729. name = outname or filename.split('/')[-1].split('\\')[-1]
  7730. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7731. if ret_val == 'fail':
  7732. if from_tcl:
  7733. filename = self.defaults['global_tcl_path'] + '/' + name
  7734. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7735. if ret_val == 'fail':
  7736. self.inform.emit('[ERROR_NOTCL] %s' %
  7737. _('Open Excellon file failed. Probable not an Excellon file.'))
  7738. return
  7739. # Register recent file
  7740. self.file_opened.emit("excellon", filename)
  7741. # GUI feedback
  7742. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7743. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7744. """
  7745. Opens a G-gcode file, parses it and creates a new object for
  7746. it in the program. Thread-safe.
  7747. :param filename: G-code file filename
  7748. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7749. :param force_parsing:
  7750. :param plot: If True plot the object on canvas
  7751. :param from_tcl: True if run from Tcl Shell
  7752. :return: None
  7753. """
  7754. App.log.debug("open_gcode()")
  7755. # How the object should be initialized
  7756. def obj_init(job_obj, app_obj_):
  7757. """
  7758. :param job_obj: the resulting object
  7759. :type app_obj_: App
  7760. """
  7761. assert isinstance(app_obj_, App), \
  7762. "Initializer expected App, got %s" % type(app_obj_)
  7763. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7764. try:
  7765. f = open(filename)
  7766. gcode = f.read()
  7767. f.close()
  7768. except IOError:
  7769. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7770. return "fail"
  7771. job_obj.gcode = gcode
  7772. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7773. if gcode_ret == "fail":
  7774. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7775. return "fail"
  7776. job_obj.create_geometry()
  7777. with self.proc_container.new(_("Opening G-Code.")):
  7778. # Object name
  7779. name = outname or filename.split('/')[-1].split('\\')[-1]
  7780. # New object creation and file processing
  7781. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7782. if ret_val == 'fail':
  7783. if from_tcl:
  7784. filename = self.defaults['global_tcl_path'] + '/' + name
  7785. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7786. if ret_val == 'fail':
  7787. self.inform.emit('[ERROR_NOTCL] %s' %
  7788. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7789. "Try to load it from File menu.\n "
  7790. "Attempting to create a FlatCAM CNCJob Object from "
  7791. "G-Code file failed during processing"))
  7792. return "fail"
  7793. # Register recent file
  7794. self.file_opened.emit("cncjob", filename)
  7795. # GUI feedback
  7796. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7797. def open_hpgl2(self, filename, outname=None):
  7798. """
  7799. Opens a HPGL2 file, parses it and creates a new object for
  7800. it in the program. Thread-safe.
  7801. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7802. :param filename: HPGL2 file filename
  7803. :return: None
  7804. """
  7805. filename = filename
  7806. # How the object should be initialized
  7807. def obj_init(geo_obj, app_obj):
  7808. assert isinstance(geo_obj, GeometryObject), \
  7809. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7810. # Opening the file happens here
  7811. obj = HPGL2(self)
  7812. try:
  7813. HPGL2.parse_file(obj, filename)
  7814. except IOError:
  7815. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7816. return "fail"
  7817. except ParseError as err:
  7818. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7819. app_obj.log.error(str(err))
  7820. return "fail"
  7821. except Exception as e:
  7822. log.debug("App.open_hpgl2() --> %s" % str(e))
  7823. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7824. msg += traceback.format_exc()
  7825. app_obj.inform.emit(msg)
  7826. return "fail"
  7827. geo_obj.multigeo = True
  7828. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7829. geo_obj.tools = deepcopy(obj.tools)
  7830. geo_obj.source_file = deepcopy(obj.source_file)
  7831. del obj
  7832. if not geo_obj.solid_geometry:
  7833. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7834. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7835. return "fail"
  7836. App.log.debug("open_hpgl2()")
  7837. with self.proc_container.new(_("Opening HPGL2")):
  7838. # Object name
  7839. name = outname or filename.split('/')[-1].split('\\')[-1]
  7840. # # ## Object creation # ##
  7841. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7842. if ret == 'fail':
  7843. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7844. return 'fail'
  7845. # Register recent file
  7846. self.file_opened.emit("geometry", filename)
  7847. # GUI feedback
  7848. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7849. def open_script(self, filename, outname=None, silent=False):
  7850. """
  7851. Opens a Script file, parses it and creates a new object for
  7852. it in the program. Thread-safe.
  7853. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7854. :param filename: Script file filename
  7855. :param silent: If True there will be no messages printed to StatusBar
  7856. :return: None
  7857. """
  7858. def obj_init(script_obj, app_obj):
  7859. assert isinstance(script_obj, ScriptObject), \
  7860. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7861. if silent is False:
  7862. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7863. try:
  7864. script_obj.parse_file(filename)
  7865. except IOError:
  7866. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7867. return "fail"
  7868. except ParseError as err:
  7869. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7870. app_obj.log.error(str(err))
  7871. return "fail"
  7872. except Exception as e:
  7873. log.debug("App.open_script() -> %s" % str(e))
  7874. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7875. msg += traceback.format_exc()
  7876. app_obj.inform.emit(msg)
  7877. return "fail"
  7878. App.log.debug("open_script()")
  7879. with self.proc_container.new(_("Opening TCL Script...")):
  7880. # Object name
  7881. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7882. # Object creation
  7883. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7884. if ret_val == 'fail':
  7885. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7886. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7887. if ret_val == 'fail':
  7888. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7889. return 'fail'
  7890. # Register recent file
  7891. self.file_opened.emit("script", filename)
  7892. # GUI feedback
  7893. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7894. def open_config_file(self, filename, run_from_arg=None):
  7895. """
  7896. Loads a config file from the specified file.
  7897. :param filename: Name of the file from which to load.
  7898. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7899. :return: None
  7900. """
  7901. App.log.debug("Opening config file: " + filename)
  7902. if run_from_arg:
  7903. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7904. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7905. _("Opening FlatCAM Config file.")),
  7906. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7907. color=QtGui.QColor("gray"))
  7908. # # add the tab if it was closed
  7909. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7910. # # first clear previous text in text editor (if any)
  7911. # self.ui.text_editor_tab.code_editor.clear()
  7912. #
  7913. # # Switch plot_area to CNCJob tab
  7914. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7915. # close the Code editor if already open
  7916. if self.toggle_codeeditor:
  7917. self.on_toggle_code_editor()
  7918. self.on_toggle_code_editor()
  7919. try:
  7920. if filename:
  7921. f = QtCore.QFile(filename)
  7922. if f.open(QtCore.QIODevice.ReadOnly):
  7923. stream = QtCore.QTextStream(f)
  7924. code_edited = stream.readAll()
  7925. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7926. f.close()
  7927. except IOError:
  7928. App.log.error("Failed to open config file: %s" % filename)
  7929. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7930. (_("Failed to open config file"), filename))
  7931. return
  7932. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7933. """
  7934. Loads a project from the specified file.
  7935. 1) Loads and parses file
  7936. 2) Registers the file as recently opened.
  7937. 3) Calls on_file_new()
  7938. 4) Updates options
  7939. 5) Calls new_object() with the object's from_dict() as init method.
  7940. 6) Calls plot_all() if plot=True
  7941. :param filename: Name of the file from which to load.
  7942. :param run_from_arg: True if run for arguments
  7943. :param plot: If True plot all objects in the project
  7944. :param cli: Run from command line
  7945. :param from_tcl: True if run from Tcl Sehll
  7946. :return: None
  7947. """
  7948. App.log.debug("Opening project: " + filename)
  7949. # block autosaving while a project is loaded
  7950. self.block_autosave = True
  7951. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7952. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7953. if cli is None:
  7954. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7955. if run_from_arg:
  7956. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7957. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7958. _("Opening FlatCAM Project file.")),
  7959. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7960. color=QtGui.QColor("gray"))
  7961. # Open and parse an uncompressed Project file
  7962. try:
  7963. f = open(filename, 'r')
  7964. except IOError:
  7965. if from_tcl:
  7966. name = filename.split('/')[-1].split('\\')[-1]
  7967. filename = self.defaults['global_tcl_path'] + '/' + name
  7968. try:
  7969. f = open(filename, 'r')
  7970. except IOError:
  7971. log.error("Failed to open project file: %s" % filename)
  7972. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7973. return
  7974. else:
  7975. log.error("Failed to open project file: %s" % filename)
  7976. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7977. return
  7978. try:
  7979. d = json.load(f, object_hook=dict2obj)
  7980. except Exception as e:
  7981. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7982. (filename, str(e)))
  7983. f.close()
  7984. # Open and parse a compressed Project file
  7985. try:
  7986. with lzma.open(filename) as f:
  7987. file_content = f.read().decode('utf-8')
  7988. d = json.loads(file_content, object_hook=dict2obj)
  7989. except Exception as e:
  7990. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7991. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7992. return
  7993. # Clear the current project
  7994. # # NOT THREAD SAFE # ##
  7995. if run_from_arg is True:
  7996. pass
  7997. elif cli is True:
  7998. self.delete_selection_shape()
  7999. else:
  8000. self.on_file_new()
  8001. # Project options
  8002. self.options.update(d['options'])
  8003. self.project_filename = filename
  8004. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8005. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8006. if cli is None:
  8007. self.set_screen_units(self.options["units"])
  8008. # Re create objects
  8009. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8010. for obj in d['objs']:
  8011. try:
  8012. def obj_init(obj_inst, app_inst):
  8013. obj_inst.from_dict(obj)
  8014. App.log.debug("Recreating from opened project an %s object: %s" %
  8015. (obj['kind'].capitalize(), obj['options']['name']))
  8016. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8017. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8018. if cli is None:
  8019. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8020. obj['kind'].upper(),
  8021. obj['options']['name']
  8022. )
  8023. )
  8024. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8025. except Exception as e:
  8026. print('App.open_project() --> ' + str(e))
  8027. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8028. self.should_we_save = False
  8029. self.file_opened.emit("project", filename)
  8030. # restore autosaving after a project was loaded
  8031. self.block_autosave = False
  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=self.project_filename)
  8036. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8037. def plot_all(self, fit_view=True, use_thread=True):
  8038. """
  8039. Re-generates all plots from all objects.
  8040. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8041. :param use_thread: if True will use threading for plotting the objects
  8042. :return: None
  8043. """
  8044. self.log.debug("Plot_all()")
  8045. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8046. for plot_obj in self.collection.get_list():
  8047. def worker_task(obj):
  8048. with self.proc_container.new("Plotting"):
  8049. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8050. if fit_view is True:
  8051. self.object_plotted.emit(obj)
  8052. if use_thread is True:
  8053. # Send to worker
  8054. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8055. else:
  8056. worker_task(plot_obj)
  8057. def register_folder(self, filename):
  8058. """
  8059. Register the last folder used by the app to open something
  8060. :param filename: the last folder is extracted from the filename
  8061. :return: None
  8062. """
  8063. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8064. def register_save_folder(self, filename):
  8065. """
  8066. Register the last folder used by the app to save something
  8067. :param filename: the last folder is extracted from the filename
  8068. :return: None
  8069. """
  8070. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8071. # def set_progress_bar(self, percentage, text=""):
  8072. # """
  8073. # Set a progress bar to a value (percentage)
  8074. #
  8075. # :param percentage: Value set to the progressbar
  8076. # :param text: Not used
  8077. # :return: None
  8078. # """
  8079. # self.ui.progress_bar.setValue(int(percentage))
  8080. def setup_recent_items(self):
  8081. """
  8082. Setup a dictionary with the recent files accessed, organized by type
  8083. :return:
  8084. """
  8085. icons = {
  8086. "gerber": self.resource_location + "/flatcam_icon16.png",
  8087. "excellon": self.resource_location + "/drill16.png",
  8088. 'geometry': self.resource_location + "/geometry16.png",
  8089. "cncjob": self.resource_location + "/cnc16.png",
  8090. "script": self.resource_location + "/script_new24.png",
  8091. "document": self.resource_location + "/notes16_1.png",
  8092. "project": self.resource_location + "/project16.png",
  8093. "svg": self.resource_location + "/geometry16.png",
  8094. "dxf": self.resource_location + "/dxf16.png",
  8095. "pdf": self.resource_location + "/pdf32.png",
  8096. "image": self.resource_location + "/image16.png"
  8097. }
  8098. try:
  8099. image_opener = self.image_tool.import_image
  8100. except AttributeError:
  8101. image_opener = None
  8102. openers = {
  8103. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8104. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8105. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8106. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8107. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8108. "document": None,
  8109. 'project': self.open_project,
  8110. 'svg': self.import_svg,
  8111. 'dxf': self.import_dxf,
  8112. 'image': image_opener,
  8113. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8114. }
  8115. # Open recent file for files
  8116. try:
  8117. f = open(self.data_path + '/recent.json')
  8118. except IOError:
  8119. App.log.error("Failed to load recent item list.")
  8120. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8121. return
  8122. try:
  8123. self.recent = json.load(f)
  8124. except json.errors.JSONDecodeError:
  8125. App.log.error("Failed to parse recent item list.")
  8126. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8127. f.close()
  8128. return
  8129. f.close()
  8130. # Open recent file for projects
  8131. try:
  8132. fp = open(self.data_path + '/recent_projects.json')
  8133. except IOError:
  8134. App.log.error("Failed to load recent project item list.")
  8135. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8136. return
  8137. try:
  8138. self.recent_projects = json.load(fp)
  8139. except json.errors.JSONDecodeError:
  8140. App.log.error("Failed to parse recent project item list.")
  8141. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8142. fp.close()
  8143. return
  8144. fp.close()
  8145. # Closure needed to create callbacks in a loop.
  8146. # Otherwise late binding occurs.
  8147. def make_callback(func, fname):
  8148. def opener():
  8149. func(fname)
  8150. return opener
  8151. def reset_recent_files():
  8152. # Reset menu
  8153. self.ui.recent.clear()
  8154. self.recent = []
  8155. try:
  8156. ff = open(self.data_path + '/recent.json', 'w')
  8157. except IOError:
  8158. App.log.error("Failed to open recent items file for writing.")
  8159. return
  8160. json.dump(self.recent, ff)
  8161. def reset_recent_projects():
  8162. # Reset menu
  8163. self.ui.recent_projects.clear()
  8164. self.recent_projects = []
  8165. try:
  8166. frp = open(self.data_path + '/recent_projects.json', 'w')
  8167. except IOError:
  8168. App.log.error("Failed to open recent projects items file for writing.")
  8169. return
  8170. json.dump(self.recent, frp)
  8171. # Reset menu
  8172. self.ui.recent.clear()
  8173. self.ui.recent_projects.clear()
  8174. # Create menu items for projects
  8175. for recent in self.recent_projects:
  8176. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8177. if recent['kind'] == 'project':
  8178. try:
  8179. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8180. # Attach callback
  8181. o = make_callback(openers[recent["kind"]], recent['filename'])
  8182. action.triggered.connect(o)
  8183. self.ui.recent_projects.addAction(action)
  8184. except KeyError:
  8185. App.log.error("Unsupported file type: %s" % recent["kind"])
  8186. # Last action in Recent Files menu is one that Clear the content
  8187. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8188. (_("Clear Recent projects")), self)
  8189. clear_action_proj.triggered.connect(reset_recent_projects)
  8190. self.ui.recent_projects.addSeparator()
  8191. self.ui.recent_projects.addAction(clear_action_proj)
  8192. # Create menu items for files
  8193. for recent in self.recent:
  8194. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8195. if recent['kind'] != 'project':
  8196. try:
  8197. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8198. # Attach callback
  8199. o = make_callback(openers[recent["kind"]], recent['filename'])
  8200. action.triggered.connect(o)
  8201. self.ui.recent.addAction(action)
  8202. except KeyError:
  8203. App.log.error("Unsupported file type: %s" % recent["kind"])
  8204. # Last action in Recent Files menu is one that Clear the content
  8205. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8206. (_("Clear Recent files")), self)
  8207. clear_action.triggered.connect(reset_recent_files)
  8208. self.ui.recent.addSeparator()
  8209. self.ui.recent.addAction(clear_action)
  8210. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8211. # self.ui.menufilerecent.set_submenu(recent_menu)
  8212. # recent_menu.show_all()
  8213. # self.ui.recent.show()
  8214. self.log.debug("Recent items list has been populated.")
  8215. def setup_component_editor(self):
  8216. """
  8217. Default text for the Selected tab when is not taken by the Object UI.
  8218. :return:
  8219. """
  8220. # label = QtWidgets.QLabel("Choose an item from Project")
  8221. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8222. sel_title = QtWidgets.QTextEdit(
  8223. _('<b>Shortcut Key List</b>'))
  8224. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8225. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8226. f_settings = QSettings("Open Source", "FlatCAM")
  8227. if f_settings.contains("notebook_font_size"):
  8228. fsize = f_settings.value('notebook_font_size', type=int)
  8229. else:
  8230. fsize = 12
  8231. tsize = fsize + int(fsize / 2)
  8232. # selected_text = (_('''
  8233. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8234. # </p>
  8235. #
  8236. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8237. # The normal flow when working in FlatCAM is the following:</span></p>
  8238. #
  8239. # <ol>
  8240. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8241. # file into
  8242. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8243. # even dragging and dropping the files on the GUI.<br />
  8244. # <br />
  8245. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8246. # drop of the
  8247. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8248. # &nbsp;</li>
  8249. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8250. # and then
  8251. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8252. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8253. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8254. # <br />
  8255. # If the selection of the object is done on the canvas by single click instead, and the
  8256. # <strong>SELECTED TAB</strong>
  8257. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8258. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8259. # it even if it was out of focus.<br />
  8260. # <br />
  8261. # You can change the parameters in this screen and the flow direction is like this:<br />
  8262. # <br />
  8263. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8264. # <strong> Geometry Object
  8265. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8266. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8267. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8268. # </ol>
  8269. #
  8270. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8271. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8272. # <strong>F3</strong>.</span></p>
  8273. #
  8274. # ''').format(fsize=fsize, tsize=tsize))
  8275. selected_text = '''
  8276. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8277. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8278. {s1}</span></p>
  8279. <ol>
  8280. <li><span style="font-size:{fsize}px">{s2}<br />
  8281. <br />
  8282. {s3}</span><br />
  8283. &nbsp;</li>
  8284. <li><span style="font-size:{fsize}px">{s4}<br />
  8285. &nbsp;</li>
  8286. <br />
  8287. <li><span style="font-size:{fsize}px">{s5}<br />
  8288. &nbsp;</li>
  8289. <br />
  8290. <li><span style="font-size:{fsize}px">{s6}<br />
  8291. <br />
  8292. {s7}</span></li>
  8293. </ol>
  8294. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8295. '''.format(
  8296. title=_("Selected Tab - Choose an Item from Project Tab"),
  8297. subtitle=_("Details"),
  8298. s1=_("The normal flow when working in FlatCAM is the following:"),
  8299. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8300. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8301. "files on the GUI."),
  8302. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8303. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8304. "actions offered within the app."),
  8305. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8306. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8307. "SELECTED TAB will be updated with the object properties according to its kind: "
  8308. "Gerber, Excellon, Geometry or CNCJob object."),
  8309. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8310. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8311. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8312. "the SELECTED TAB and populate it even if it was out of focus."),
  8313. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8314. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8315. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8316. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8317. "(again, done in SELECTED TAB) --> Save GCode."),
  8318. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8319. "or through its own key shortcut: <b>F3</b>."),
  8320. tsize=tsize,
  8321. fsize=fsize
  8322. )
  8323. sel_title.setText(selected_text)
  8324. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8325. self.ui.selected_scroll_area.setWidget(sel_title)
  8326. def setup_obj_classes(self):
  8327. """
  8328. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8329. class.
  8330. :return: None
  8331. """
  8332. FlatCAMObj.app = self
  8333. ObjectCollection.app = self
  8334. Gerber.app = self
  8335. Excellon.app = self
  8336. Geometry.app = self
  8337. CNCjob.app = self
  8338. FCProcess.app = self
  8339. FCProcessContainer.app = self
  8340. OptionsGroupUI.app = self
  8341. def version_check(self):
  8342. """
  8343. Checks for the latest version of the program. Alerts the
  8344. user if theirs is outdated. This method is meant to be run
  8345. in a separate thread.
  8346. :return: None
  8347. """
  8348. self.log.debug("version_check()")
  8349. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8350. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8351. App.version_url,
  8352. str(self.defaults['global_serial']),
  8353. str(self.version),
  8354. str(self.os),
  8355. urllib.parse.urlencode(self.defaults["global_stats"])
  8356. )
  8357. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8358. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8359. # urllib.parse.urlencode(self.defaults["global_stats"])
  8360. else:
  8361. # no_stats dict; just so it won't break things on website
  8362. no_ststs_dict = {}
  8363. no_ststs_dict["global_ststs"] = {}
  8364. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8365. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8366. App.log.debug("Checking for updates @ %s" % full_url)
  8367. # ## Get the data
  8368. try:
  8369. f = urllib.request.urlopen(full_url)
  8370. except Exception:
  8371. # App.log.warning("Failed checking for latest version. Could not connect.")
  8372. self.log.warning("Failed checking for latest version. Could not connect.")
  8373. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8374. return
  8375. try:
  8376. data = json.load(f)
  8377. except Exception as e:
  8378. App.log.error("Could not parse information about latest version.")
  8379. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8380. App.log.debug("json.load(): %s" % str(e))
  8381. f.close()
  8382. return
  8383. f.close()
  8384. # ## Latest version?
  8385. if self.version >= data["version"]:
  8386. App.log.debug("FlatCAM is up to date!")
  8387. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8388. return
  8389. App.log.debug("Newer version available.")
  8390. self.message.emit(
  8391. _("Newer Version Available"),
  8392. '%s<br><br>><b>%s</b><br>%s' % (
  8393. _("There is a newer version of FlatCAM available for download:"),
  8394. str(data["name"]),
  8395. str(data["message"])
  8396. ),
  8397. _("info")
  8398. )
  8399. def on_plotcanvas_setup(self, container=None):
  8400. """
  8401. This is doing the setup for the plot area (canvas).
  8402. :param container: QT Widget where to install the canvas
  8403. :return: None
  8404. """
  8405. if container:
  8406. plot_container = container
  8407. else:
  8408. plot_container = self.ui.right_layout
  8409. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8410. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8411. self.is_legacy = True
  8412. self.defaults["global_graphic_engine"] = "2D"
  8413. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8414. else:
  8415. try:
  8416. self.plotcanvas = PlotCanvas(plot_container, self)
  8417. except Exception as er:
  8418. msg_txt = traceback.format_exc()
  8419. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8420. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8421. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8422. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8423. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8424. msg += msg_txt
  8425. self.inform.emit(msg)
  8426. return 'fail'
  8427. # So it can receive key presses
  8428. self.plotcanvas.native.setFocus()
  8429. if self.is_legacy is False:
  8430. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8431. # Set the mouse button for panning
  8432. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8433. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8434. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8435. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8436. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8437. # Keys over plot enabled
  8438. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8439. if self.defaults['global_cursor_type'] == 'small':
  8440. self.app_cursor = self.plotcanvas.new_cursor()
  8441. else:
  8442. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8443. if self.ui.grid_snap_btn.isChecked():
  8444. self.app_cursor.enabled = True
  8445. else:
  8446. self.app_cursor.enabled = False
  8447. if self.is_legacy is False:
  8448. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8449. else:
  8450. # will use the default Matplotlib axes
  8451. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8452. def on_zoom_fit(self, event):
  8453. """
  8454. Callback for zoom-fit request. This can be either from the corresponding
  8455. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8456. with axes limits from the geometry bounds of all objects.
  8457. :param event: Ignored.
  8458. :return: None
  8459. """
  8460. if self.is_legacy is False:
  8461. self.plotcanvas.fit_view()
  8462. else:
  8463. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8464. width = xmax - xmin
  8465. height = ymax - ymin
  8466. xmin -= 0.05 * width
  8467. xmax += 0.05 * width
  8468. ymin -= 0.05 * height
  8469. ymax += 0.05 * height
  8470. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8471. def on_zoom_in(self):
  8472. """
  8473. Callback for zoom-in request.
  8474. :return:
  8475. """
  8476. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8477. def on_zoom_out(self):
  8478. """
  8479. Callback for zoom-out request.
  8480. :return:
  8481. """
  8482. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8483. def disable_all_plots(self):
  8484. self.defaults.report_usage("disable_all_plots()")
  8485. self.disable_plots(self.collection.get_list())
  8486. self.inform.emit('[success] %s' %
  8487. _("All plots disabled."))
  8488. def disable_other_plots(self):
  8489. self.defaults.report_usage("disable_other_plots()")
  8490. self.disable_plots(self.collection.get_non_selected())
  8491. self.inform.emit('[success] %s' %
  8492. _("All non selected plots disabled."))
  8493. def enable_all_plots(self):
  8494. self.defaults.report_usage("enable_all_plots()")
  8495. self.enable_plots(self.collection.get_list())
  8496. self.inform.emit('[success] %s' %
  8497. _("All plots enabled."))
  8498. def on_enable_sel_plots(self):
  8499. log.debug("App.on_enable_sel_plot()")
  8500. object_list = self.collection.get_selected()
  8501. self.enable_plots(objects=object_list)
  8502. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8503. def on_disable_sel_plots(self):
  8504. log.debug("App.on_disable_sel_plot()")
  8505. # self.inform.emit(_("Disabling plots ..."))
  8506. object_list = self.collection.get_selected()
  8507. self.disable_plots(objects=object_list)
  8508. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8509. def enable_plots(self, objects):
  8510. """
  8511. Enable plots
  8512. :param objects: list of Objects to be enabled
  8513. :return:
  8514. """
  8515. log.debug("Enabling plots ...")
  8516. # self.inform.emit(_("Working ..."))
  8517. for obj in objects:
  8518. if obj.options['plot'] is False:
  8519. obj.options.set_change_callback(lambda x: None)
  8520. obj.options['plot'] = True
  8521. try:
  8522. # only the Gerber obj has on_plot_cb_click() method
  8523. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8524. # disable this cb while disconnected,
  8525. # in case the operation takes time the user is not allowed to change it
  8526. obj.ui.plot_cb.setDisabled(True)
  8527. except AttributeError:
  8528. pass
  8529. obj.set_form_item("plot")
  8530. try:
  8531. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8532. obj.ui.plot_cb.setDisabled(False)
  8533. except AttributeError:
  8534. pass
  8535. obj.options.set_change_callback(obj.on_options_change)
  8536. def worker_task(objs):
  8537. with self.proc_container.new(_("Enabling plots ...")):
  8538. for plot_obj in objs:
  8539. # obj.options['plot'] = True
  8540. if isinstance(plot_obj, CNCJobObject):
  8541. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8542. else:
  8543. plot_obj.plot(visible=True)
  8544. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8545. # self.plots_updated.emit()
  8546. def disable_plots(self, objects):
  8547. """
  8548. Disables plots
  8549. :param objects: list of Objects to be disabled
  8550. :return:
  8551. """
  8552. # if no objects selected then do nothing
  8553. if not self.collection.get_selected():
  8554. return
  8555. log.debug("Disabling plots ...")
  8556. # self.inform.emit(_("Working ..."))
  8557. for obj in objects:
  8558. if obj.options['plot'] is True:
  8559. obj.options.set_change_callback(lambda x: None)
  8560. obj.options['plot'] = False
  8561. try:
  8562. # only the Gerber obj has on_plot_cb_click() method
  8563. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8564. obj.ui.plot_cb.setDisabled(True)
  8565. except AttributeError:
  8566. pass
  8567. obj.set_form_item("plot")
  8568. try:
  8569. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8570. obj.ui.plot_cb.setDisabled(False)
  8571. except AttributeError:
  8572. pass
  8573. obj.options.set_change_callback(obj.on_options_change)
  8574. try:
  8575. self.delete_selection_shape()
  8576. except Exception as e:
  8577. log.debug("App.disable_plots() --> %s" % str(e))
  8578. # self.plots_updated.emit()
  8579. def worker_task(objs):
  8580. with self.proc_container.new(_("Disabling plots ...")):
  8581. for plot_obj in objs:
  8582. # obj.options['plot'] = True
  8583. if isinstance(plot_obj, CNCJobObject):
  8584. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8585. else:
  8586. plot_obj.plot(visible=False)
  8587. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8588. def toggle_plots(self, objects):
  8589. """
  8590. Toggle plots visibility
  8591. :param objects: list of Objects for which to be toggled the visibility
  8592. :return: None
  8593. """
  8594. # if no objects selected then do nothing
  8595. if not self.collection.get_selected():
  8596. return
  8597. log.debug("Toggling plots ...")
  8598. self.inform.emit(_("Working ..."))
  8599. for obj in objects:
  8600. if obj.options['plot'] is False:
  8601. obj.options['plot'] = True
  8602. else:
  8603. obj.options['plot'] = False
  8604. self.plots_updated.emit()
  8605. def clear_plots(self):
  8606. """
  8607. Clear the plots
  8608. :return: None
  8609. """
  8610. objects = self.collection.get_list()
  8611. for obj in objects:
  8612. obj.clear(obj == objects[-1])
  8613. # Clear pool to free memory
  8614. self.clear_pool()
  8615. def on_set_color_action_triggered(self):
  8616. """
  8617. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8618. :return:
  8619. """
  8620. new_color = self.defaults['gerber_plot_fill']
  8621. clicked_action = self.sender()
  8622. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8623. act_name = clicked_action.text()
  8624. sel_obj_list = self.collection.get_selected()
  8625. if not sel_obj_list:
  8626. return
  8627. # a default value, I just chose this one
  8628. alpha_level = 'BF'
  8629. for sel_obj in sel_obj_list:
  8630. if sel_obj.kind == 'excellon':
  8631. alpha_level = str(hex(
  8632. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8633. elif sel_obj.kind == 'gerber':
  8634. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8635. elif sel_obj.kind == 'geometry':
  8636. alpha_level = 'FF'
  8637. else:
  8638. log.debug(
  8639. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8640. continue
  8641. sel_obj.alpha_level = alpha_level
  8642. if act_name == _('Red'):
  8643. new_color = '#FF0000' + alpha_level
  8644. if act_name == _('Blue'):
  8645. new_color = '#0000FF' + alpha_level
  8646. if act_name == _('Yellow'):
  8647. new_color = '#FFDF00' + alpha_level
  8648. if act_name == _('Green'):
  8649. new_color = '#00FF00' + alpha_level
  8650. if act_name == _('Purple'):
  8651. new_color = '#FF00FF' + alpha_level
  8652. if act_name == _('Brown'):
  8653. new_color = '#A52A2A' + alpha_level
  8654. if act_name == _('White'):
  8655. new_color = '#FFFFFF' + alpha_level
  8656. if act_name == _('Black'):
  8657. new_color = '#000000' + alpha_level
  8658. if act_name == _('Custom'):
  8659. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8660. c_dialog = QtWidgets.QColorDialog()
  8661. plot_fill_color = c_dialog.getColor(initial=new_color)
  8662. if plot_fill_color.isValid() is False:
  8663. return
  8664. new_color = str(plot_fill_color.name()) + alpha_level
  8665. if act_name == _("Default"):
  8666. for sel_obj in sel_obj_list:
  8667. if sel_obj.kind == 'excellon':
  8668. new_color = self.defaults['excellon_plot_fill']
  8669. new_line_color = self.defaults['excellon_plot_line']
  8670. elif sel_obj.kind == 'gerber':
  8671. new_color = self.defaults['gerber_plot_fill']
  8672. new_line_color = self.defaults['gerber_plot_line']
  8673. elif sel_obj.kind == 'geometry':
  8674. new_color = self.defaults['geometry_plot_line']
  8675. new_line_color = self.defaults['geometry_plot_line']
  8676. else:
  8677. log.debug(
  8678. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8679. continue
  8680. sel_obj.fill_color = new_color
  8681. sel_obj.outline_color = new_line_color
  8682. sel_obj.shapes.redraw(
  8683. update_colors=(new_color, new_line_color)
  8684. )
  8685. return
  8686. if act_name == _("Opacity"):
  8687. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8688. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8689. if ok_button:
  8690. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8691. for sel_obj in sel_obj_list:
  8692. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8693. sel_obj.shapes.redraw(
  8694. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8695. )
  8696. return
  8697. new_line_color = color_variant(new_color[:7], 0.7)
  8698. if act_name == _("White"):
  8699. new_line_color = color_variant("#dedede", 0.7)
  8700. for sel_obj in sel_obj_list:
  8701. sel_obj.fill_color = new_color
  8702. sel_obj.outline_color = new_line_color
  8703. sel_obj.shapes.redraw(
  8704. update_colors=(new_color, new_line_color)
  8705. )
  8706. def generate_cnc_job(self, objects):
  8707. """
  8708. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8709. :param objects: Selected objects in the Project Tab
  8710. :return:
  8711. """
  8712. self.defaults.report_usage("generate_cnc_job()")
  8713. # for obj in objects:
  8714. # obj.generatecncjob()
  8715. for obj in objects:
  8716. obj.on_generatecnc_button_click()
  8717. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8718. """
  8719. Saves the current project to the specified file.
  8720. :param filename: Name of the file in which to save.
  8721. :type filename: str
  8722. :param quit_action: if the project saving will be followed by an app quit; boolean
  8723. :param silent: if True will not display status messages
  8724. :param from_tcl True is run from Tcl Shell
  8725. :return: None
  8726. """
  8727. self.log.debug("save_project()")
  8728. self.save_in_progress = True
  8729. with self.proc_container.new(_("Saving FlatCAM Project")):
  8730. # Capture the latest changes
  8731. # Current object
  8732. try:
  8733. current_object = self.collection.get_active()
  8734. if current_object:
  8735. current_object.read_form()
  8736. except Exception as e:
  8737. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8738. pass
  8739. # Serialize the whole project
  8740. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8741. "options": self.options,
  8742. "version": self.version}
  8743. if self.defaults["global_save_compressed"] is True:
  8744. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8745. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8746. # # Write
  8747. f.write(g)
  8748. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8749. else:
  8750. # Open file
  8751. try:
  8752. f = open(filename, 'w')
  8753. except IOError:
  8754. App.log.error("Failed to open file for saving: %s", filename)
  8755. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8756. return
  8757. # Write
  8758. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8759. f.close()
  8760. # verification of the saved project
  8761. # Open and parse
  8762. try:
  8763. saved_f = open(filename, 'r')
  8764. except IOError:
  8765. if silent is False:
  8766. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8767. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8768. return
  8769. try:
  8770. saved_d = json.load(saved_f, object_hook=dict2obj)
  8771. except Exception:
  8772. if silent is False:
  8773. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8774. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8775. f.close()
  8776. return
  8777. saved_f.close()
  8778. if silent is False:
  8779. if 'version' in saved_d:
  8780. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8781. else:
  8782. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8783. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8784. tb_settings = QSettings("Open Source", "FlatCAM")
  8785. lock_state = self.ui.lock_action.isChecked()
  8786. tb_settings.setValue('toolbar_lock', lock_state)
  8787. # This will write the setting to the platform specific storage.
  8788. del tb_settings
  8789. # if quit:
  8790. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8791. # t.start()
  8792. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8793. def start_delayed_quit(self, delay, filename, should_quit=None):
  8794. """
  8795. :param delay: period of checking if project file size is more than zero; in seconds
  8796. :param filename: the name of the project file to be checked periodically for size more than zero
  8797. :param should_quit: if the task finished will be followed by an app quit; boolean
  8798. :return:
  8799. """
  8800. to_quit = should_quit
  8801. self.save_timer = QtCore.QTimer()
  8802. self.save_timer.setInterval(delay)
  8803. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8804. self.save_timer.start()
  8805. def check_project_file_size(self, filename, should_quit=None):
  8806. """
  8807. :param filename: the name of the project file to be checked periodically for size more than zero
  8808. :param should_quit: will quit the app if True; boolean
  8809. :return:
  8810. """
  8811. try:
  8812. if os.stat(filename).st_size > 0:
  8813. self.save_in_progress = False
  8814. self.save_timer.stop()
  8815. if should_quit:
  8816. self.app_quit.emit()
  8817. except Exception:
  8818. traceback.print_exc()
  8819. def save_project_auto(self):
  8820. """
  8821. Called periodically to save the project.
  8822. 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
  8823. # progress.
  8824. :return:
  8825. """
  8826. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8827. self.on_file_saveproject()
  8828. def save_project_auto_update(self):
  8829. """
  8830. Update the auto save time interval value.
  8831. :return:
  8832. """
  8833. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8834. try:
  8835. if self.autosave_timer.isActive():
  8836. self.autosave_timer.stop()
  8837. except Exception:
  8838. pass
  8839. if self.defaults['global_autosave'] is True:
  8840. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8841. self.autosave_timer.start()
  8842. def on_options_app2project(self):
  8843. """
  8844. Callback for Options->Transfer Options->App=>Project. Copies options
  8845. from application defaults to project defaults.
  8846. :return: None
  8847. """
  8848. self.defaults.report_usage("on_options_app2project")
  8849. self.preferencesUiManager.defaults_read_form()
  8850. self.options.update(self.defaults)
  8851. def toggle_shell(self):
  8852. """
  8853. Toggle shell: if is visible close it, if it is closed then open it
  8854. :return: None
  8855. """
  8856. self.defaults.report_usage("toggle_shell()")
  8857. if self.ui.shell_dock.isVisible():
  8858. self.ui.shell_dock.hide()
  8859. self.plotcanvas.native.setFocus()
  8860. else:
  8861. self.ui.shell_dock.show()
  8862. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8863. # self.shell._edit.setFocus()
  8864. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8865. # HACK - simulate a mouse click - alternative
  8866. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8867. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8868. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8869. # no_km)
  8870. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8871. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8872. # no_km)
  8873. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8874. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8875. """
  8876. Shows a message on the FlatCAM Shell
  8877. :param msg: Message to display.
  8878. :param show: Opens the shell.
  8879. :param error: Shows the message as an error.
  8880. :param warning: Shows the message as an warning.
  8881. :param success: Shows the message as an success.
  8882. :param selected: Indicate that something was selected on canvas
  8883. :return: None
  8884. """
  8885. if show:
  8886. self.ui.shell_dock.show()
  8887. try:
  8888. if error:
  8889. self.shell.append_error(msg + "\n")
  8890. elif warning:
  8891. self.shell.append_warning(msg + "\n")
  8892. elif success:
  8893. self.shell.append_success(msg + "\n")
  8894. elif selected:
  8895. self.shell.append_selected(msg + "\n")
  8896. else:
  8897. self.shell.append_output(msg + "\n")
  8898. except AttributeError:
  8899. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8900. class ArgsThread(QtCore.QObject):
  8901. open_signal = pyqtSignal(list)
  8902. start = pyqtSignal()
  8903. stop = pyqtSignal()
  8904. if sys.platform == 'win32':
  8905. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8906. else:
  8907. address = ('/tmp/testipc', 'AF_UNIX')
  8908. def __init__(self):
  8909. super(ArgsThread, self).__init__()
  8910. self.listener = None
  8911. self.thread_exit = False
  8912. self.start.connect(self.run)
  8913. self.stop.connect(self.close_listener)
  8914. def my_loop(self, address):
  8915. try:
  8916. self.listener = Listener(*address)
  8917. while self.thread_exit is False:
  8918. conn = self.listener.accept()
  8919. self.serve(conn)
  8920. except socket.error:
  8921. try:
  8922. conn = Client(*address)
  8923. conn.send(sys.argv)
  8924. conn.send('close')
  8925. # close the current instance only if there are args
  8926. if len(sys.argv) > 1:
  8927. try:
  8928. self.listener.close()
  8929. except Exception:
  8930. pass
  8931. sys.exit()
  8932. except ConnectionRefusedError:
  8933. if sys.platform == 'win32':
  8934. pass
  8935. else:
  8936. os.system('rm /tmp/testipc')
  8937. self.listener = Listener(*address)
  8938. while True:
  8939. conn = self.listener.accept()
  8940. self.serve(conn)
  8941. def serve(self, conn):
  8942. while self.thread_exit is False:
  8943. msg = conn.recv()
  8944. if msg == 'close':
  8945. break
  8946. self.open_signal.emit(msg)
  8947. conn.close()
  8948. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8949. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8950. @pyqtSlot()
  8951. def run(self):
  8952. self.my_loop(self.address)
  8953. @pyqtSlot()
  8954. def close_listener(self):
  8955. self.thread_exit = True
  8956. self.listener.close()
  8957. # end of file