FlatCAMApp.py 487 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927
  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
  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. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  423. self.ui.final_save.connect(self.final_save)
  424. # restore the toolbar view
  425. self.restore_toolbar_view()
  426. # restore the GUI geometry
  427. self.restore_main_win_geom()
  428. # set FlatCAM units in the Status bar
  429. self.set_screen_units(self.defaults['units'])
  430. # ###########################################################################################################
  431. # ########################################### AUTOSAVE SETUP ################################################
  432. # ###########################################################################################################
  433. self.block_autosave = False
  434. self.autosave_timer = QtCore.QTimer(self)
  435. self.save_project_auto_update()
  436. self.autosave_timer.timeout.connect(self.save_project_auto)
  437. # ###########################################################################################################
  438. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  439. # ###########################################################################################################
  440. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  441. inform=self.inform)
  442. self.preferencesUiManager.defaults_write_form()
  443. # When the self.defaults dictionary changes will update the Preferences GUI forms
  444. self.defaults.set_change_callback(self.on_defaults_dict_change)
  445. # ###########################################################################################################
  446. # ##################################### FIRST RUN SECTION ###################################################
  447. # ################################ It's done only once after install #####################################
  448. # ###########################################################################################################
  449. if self.defaults["first_run"] is True:
  450. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  451. initial_lay = 'minimal'
  452. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  453. # Set the combobox in Preferences to the current layout
  454. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  455. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  456. # after the first run, this object should be False
  457. self.defaults["first_run"] = False
  458. self.preferencesUiManager.save_defaults(silent=True)
  459. # ###########################################################################################################
  460. # ############################################ Data #########################################################
  461. # ###########################################################################################################
  462. self.recent = []
  463. self.recent_projects = []
  464. self.clipboard = QtWidgets.QApplication.clipboard()
  465. self.project_filename = None
  466. self.toggle_units_ignore = False
  467. # ###########################################################################################################
  468. # #################################### LOAD PREPROCESSORS ###################################################
  469. # ###########################################################################################################
  470. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  471. # the preprocessor file
  472. self.preprocessors = load_preprocessors(self)
  473. # make sure that always the 'default' preprocessor is the first item in the dictionary
  474. if 'default' in self.preprocessors.keys():
  475. new_ppp_dict = {}
  476. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  477. default_pp = self.preprocessors.pop('default')
  478. new_ppp_dict['default'] = default_pp
  479. # then add the rest of the keys
  480. for name, val_class in self.preprocessors.items():
  481. new_ppp_dict[name] = val_class
  482. # and now put back the ordered dict with 'default' key first
  483. self.preprocessors = new_ppp_dict
  484. for name in list(self.preprocessors.keys()):
  485. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  486. if name.partition('_')[0] == 'Paste':
  487. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  488. continue
  489. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  490. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  491. if name == 'hpgl':
  492. continue
  493. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  494. # ###########################################################################################################
  495. # ########################################## LOAD LANGUAGES ################################################
  496. # ###########################################################################################################
  497. self.languages = fcTranslate.load_languages()
  498. for name in sorted(self.languages.values()):
  499. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  500. # ###########################################################################################################
  501. # ####################################### APPLY APP LANGUAGE ################################################
  502. # ###########################################################################################################
  503. ret_val = fcTranslate.apply_language('strings')
  504. if ret_val == "no language":
  505. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  506. log.debug("Could not find the Language files. The App strings are missing.")
  507. else:
  508. # make the current language the current selection on the language combobox
  509. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  510. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  511. # ###########################################################################################################
  512. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  513. # ###########################################################################################################
  514. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  515. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  516. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  517. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  518. self.defaults.propagate_defaults()
  519. # ###########################################################################################################
  520. # ######################################## UPDATE THE OPTIONS ###############################################
  521. # ###########################################################################################################
  522. self.options = LoudDict()
  523. # -----------------------------------------------------------------------------------------------------------
  524. # Update the self.options from the self.defaults
  525. # The self.defaults holds the application defaults while the self.options holds the object defaults
  526. # -----------------------------------------------------------------------------------------------------------
  527. # Copy app defaults to project options
  528. for def_key, def_val in self.defaults.items():
  529. self.options[def_key] = deepcopy(def_val)
  530. self.preferencesUiManager.show_preferences_gui()
  531. # ### End of Data ####
  532. # ###########################################################################################################
  533. # #################################### SETUP OBJECT COLLECTION ##############################################
  534. # ###########################################################################################################
  535. self.collection = ObjectCollection(self)
  536. self.ui.project_tab_layout.addWidget(self.collection.view)
  537. # ### Adjust tabs width ## ##
  538. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  539. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  540. self.collection.view.setMinimumWidth(290)
  541. self.log.debug("Finished creating Object Collection.")
  542. # ###########################################################################################################
  543. # ######################################## SETUP Plot Area ##################################################
  544. # ###########################################################################################################
  545. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  546. if self.defaults["global_graphic_engine"] == '3D':
  547. self.is_legacy = False
  548. else:
  549. self.is_legacy = True
  550. # Event signals disconnect id holders
  551. self.mp = None
  552. self.mm = None
  553. self.mr = None
  554. self.mdc = None
  555. self.mp_zc = None
  556. self.kp = None
  557. # Matplotlib axis
  558. self.axes = None
  559. if show_splash:
  560. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  561. "Canvas initialization started."),
  562. alignment=Qt.AlignBottom | Qt.AlignLeft,
  563. color=QtGui.QColor("gray"))
  564. start_plot_time = time.time() # debug
  565. self.plotcanvas = None
  566. self.app_cursor = None
  567. self.hover_shapes = None
  568. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  569. # setup the PlotCanvas
  570. self.on_plotcanvas_setup()
  571. end_plot_time = time.time()
  572. self.used_time = end_plot_time - start_plot_time
  573. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  574. if show_splash:
  575. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  576. "Canvas initialization started.\n"
  577. "Canvas initialization finished in"), '%.2f' % self.used_time),
  578. alignment=Qt.AlignBottom | Qt.AlignLeft,
  579. color=QtGui.QColor("gray"))
  580. self.ui.splitter.setStretchFactor(1, 2)
  581. # ###########################################################################################################
  582. # ############################################### SYS TRAY ##################################################
  583. # ###########################################################################################################
  584. if self.defaults["global_systray_icon"]:
  585. self.parent_w = QtWidgets.QWidget()
  586. if self.cmd_line_headless == 1:
  587. self.trayIcon = FlatCAMSystemTray(app=self,
  588. icon=QtGui.QIcon(self.resource_location +
  589. '/flatcam_icon32_green.png'),
  590. headless=True,
  591. parent=self.parent_w)
  592. else:
  593. self.trayIcon = FlatCAMSystemTray(app=self,
  594. icon=QtGui.QIcon(self.resource_location +
  595. '/flatcam_icon32_green.png'),
  596. parent=self.parent_w)
  597. # ###########################################################################################################
  598. # ############################################### Worker SETUP ##############################################
  599. # ###########################################################################################################
  600. if self.defaults["global_worker_number"]:
  601. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  602. else:
  603. self.workers = WorkerStack(workers_number=2)
  604. self.worker_task.connect(self.workers.add_task)
  605. self.log.debug("Finished creating Workers crew.")
  606. # ###########################################################################################################
  607. # ############################################# Activity Monitor ###########################################
  608. # ###########################################################################################################
  609. self.activity_view = FlatCAMActivityView(app=self)
  610. self.ui.infobar.addWidget(self.activity_view)
  611. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  612. # ###########################################################################################################
  613. # ############################################# Signal handling #############################################
  614. # ###########################################################################################################
  615. # ########################################## Custom signals ################################################
  616. # signal for displaying messages in status bar
  617. self.inform.connect(self.info)
  618. # signal to be called when the app is quiting
  619. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  620. self.message.connect(self.message_dialog)
  621. # self.progress.connect(self.set_progress_bar)
  622. # signals that are emitted when object state changes
  623. self.object_created.connect(self.on_object_created)
  624. self.object_changed.connect(self.on_object_changed)
  625. self.object_plotted.connect(self.on_object_plotted)
  626. self.plots_updated.connect(self.on_plots_updated)
  627. # signals emitted when file state change
  628. self.file_opened.connect(self.register_recent)
  629. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  630. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  631. # ########################################## Standard signals ###############################################
  632. # ### Menu
  633. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  634. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  635. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  636. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  637. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  638. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  639. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  640. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  641. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  642. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  643. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  644. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  645. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  646. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  647. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  648. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  649. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  650. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  651. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  652. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  653. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  654. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  655. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  656. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  657. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  658. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  659. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  660. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  661. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  662. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  663. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  664. self.ui.menufile_exit.triggered.connect(self.final_save)
  665. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  666. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  667. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  668. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  669. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  670. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  671. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  672. self.ui.menueditdelete.triggered.connect(self.on_delete)
  673. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  674. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  675. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  676. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  677. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  678. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  679. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  680. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  681. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  682. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  683. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  684. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  685. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  686. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  687. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  688. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  689. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  690. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  691. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  692. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  693. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  694. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  695. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  696. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  697. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  698. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  699. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  700. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  701. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  702. self.ui.menuview_replot.triggered.connect(self.plot_all)
  703. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  704. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  705. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  706. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  707. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  708. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  709. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  710. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  711. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  712. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  713. self.ui.menuhelp_about.triggered.connect(self.on_about)
  714. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  715. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  716. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  717. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  718. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  719. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  720. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  721. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  722. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  723. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  724. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  725. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  726. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  727. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  728. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  729. # ToolBar signals
  730. self.connect_toolbar_signals()
  731. # Notebook and Plot Tab Area signals
  732. # make the right click on the notebook tab and plot tab area tab raise a menu
  733. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  734. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  735. self.on_tab_setup_context_menu()
  736. # activate initial state
  737. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  738. # Context Menu
  739. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  740. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  741. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  742. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  743. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  744. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  745. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  746. self.ui.clearplot.triggered.connect(self.clear_plots)
  747. self.ui.replot.triggered.connect(self.plot_all)
  748. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  749. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  750. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  751. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  752. self.ui.popmenu_move.triggered.connect(self.obj_move)
  753. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  754. # Project Context Menu -> Color Setting
  755. for act in self.ui.menuprojectcolor.actions():
  756. act.triggered.connect(self.on_set_color_action_triggered)
  757. # ###########################################################################################################
  758. # #################################### GUI PREFERENCES SIGNALS ##############################################
  759. # ###########################################################################################################
  760. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  761. lambda: self.on_toggle_units(no_pref=False))
  762. # ##################################### Workspace Setting Signals ###########################################
  763. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  764. self.on_workspace_modified)
  765. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  766. self.on_workspace_modified
  767. )
  768. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  769. # ###########################################################################################################
  770. # ######################################## GUI SETTINGS SIGNALS #############################################
  771. # ###########################################################################################################
  772. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  773. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  774. # ######################################## Tools related signals ############################################
  775. # Film Tool
  776. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  777. self.on_film_color_entry)
  778. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  779. self.on_film_color_button)
  780. # QRCode Tool
  781. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  782. self.on_qrcode_fill_color_entry)
  783. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  784. self.on_qrcode_fill_color_button)
  785. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  786. self.on_qrcode_back_color_entry)
  787. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  788. self.on_qrcode_back_color_button)
  789. # portability changed signal
  790. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  791. # Object list
  792. self.collection.view.activated.connect(self.on_row_activated)
  793. self.collection.item_selected.connect(self.on_row_selected)
  794. self.object_status_changed.connect(self.on_collection_updated)
  795. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  796. # Export Excellon parameters.
  797. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  798. self.on_update_exc_export
  799. )
  800. # call it once to make sure it is updated at startup
  801. self.on_update_exc_export(state=self.defaults["excellon_update"])
  802. # when there are arguments at application startup this get launched
  803. self.args_at_startup[list].connect(self.on_startup_args)
  804. # ###########################################################################################################
  805. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  806. # ###########################################################################################################
  807. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  808. lambda: self.restore_extensions(ext_type='excellon'))
  809. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  810. lambda: self.restore_extensions(ext_type='gcode'))
  811. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  812. lambda: self.restore_extensions(ext_type='gerber'))
  813. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  814. lambda: self.delete_all_extensions(ext_type='excellon'))
  815. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  816. lambda: self.delete_all_extensions(ext_type='gcode'))
  817. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  818. lambda: self.delete_all_extensions(ext_type='gerber'))
  819. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  820. lambda: self.add_extension(ext_type='excellon'))
  821. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  822. lambda: self.add_extension(ext_type='gcode'))
  823. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  824. lambda: self.add_extension(ext_type='gerber'))
  825. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  826. lambda: self.del_extension(ext_type='excellon'))
  827. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  828. lambda: self.del_extension(ext_type='gcode'))
  829. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  830. lambda: self.del_extension(ext_type='gerber'))
  831. # connect the 'Apply' buttons from the Preferences/File Associations
  832. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  833. lambda: self.on_register_files(obj_type='excellon'))
  834. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  835. lambda: self.on_register_files(obj_type='gcode'))
  836. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  837. lambda: self.on_register_files(obj_type='gerber'))
  838. # ###########################################################################################################
  839. # ########################################### KEYWORDS SIGNALS ##############################################
  840. # ###########################################################################################################
  841. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  842. lambda: self.restore_extensions(ext_type='keyword'))
  843. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  844. lambda: self.delete_all_extensions(ext_type='keyword'))
  845. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  846. lambda: self.add_extension(ext_type='keyword'))
  847. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  848. lambda: self.del_extension(ext_type='keyword'))
  849. # connect the abort_all_tasks related slots to the related signals
  850. self.proc_container.idle_flag.connect(self.app_is_idle)
  851. # signal emitted when a tab is closed in the Plot Area
  852. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  853. # signal to close the application
  854. self.close_app_signal.connect(self.kill_app)
  855. # ################################# FINISHED CONNECTING SIGNALS #############################################
  856. # ###########################################################################################################
  857. # ###########################################################################################################
  858. # ###########################################################################################################
  859. self.log.debug("Finished connecting Signals.")
  860. # ###########################################################################################################
  861. # ########################################## Other setups ###################################################
  862. # ###########################################################################################################
  863. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  864. # depending on from where those tools are called different actions can be done
  865. self.call_source = 'app'
  866. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  867. self.tool_tab_locked = False
  868. # decide if to show or hide the Notebook side of the screen at startup
  869. if self.defaults["global_project_at_startup"] is True:
  870. self.ui.splitter.setSizes([1, 1])
  871. else:
  872. self.ui.splitter.setSizes([0, 1])
  873. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  874. self.setup_component_editor()
  875. # ###########################################################################################################
  876. # ####################################### Auto-complete KEYWORDS ############################################
  877. # ###########################################################################################################
  878. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  879. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  880. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  881. 'export_exc',
  882. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  883. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  884. 'interiors', 'isolate', 'join_excellon',
  885. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  886. 'mirror', 'ncc',
  887. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  888. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  889. 'options', 'origin',
  890. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  891. 'save', 'save_project',
  892. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  893. 'skew', 'subtract_poly', 'subtract_rectangle',
  894. 'version', 'write_gcode'
  895. ]
  896. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  897. 'Paste_1',
  898. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  899. 'Toolchange_manual', 'True', 'Users',
  900. 'all', 'auto', 'axis',
  901. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  902. 'contour', 'default',
  903. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  904. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  905. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  906. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  907. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  908. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  909. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  910. 'spacing_columns',
  911. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  912. 'toolchange_xy', 'toolchangez', 'travelz',
  913. 'tooldia', 'use_threads', 'value',
  914. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  915. ]
  916. self.tcl_keywords = [
  917. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  918. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  919. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  920. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  921. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  922. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  923. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  924. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  925. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  926. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  927. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  928. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  929. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  930. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  931. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  932. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  933. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  934. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  935. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  936. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  937. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  938. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  939. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  940. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  941. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  942. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  943. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  944. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  945. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  946. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  947. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  948. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  949. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  950. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  951. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  952. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  953. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  954. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  955. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  956. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  957. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  958. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  959. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  960. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  961. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  962. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  963. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  964. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  965. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  966. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  967. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  968. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  969. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  970. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  971. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  972. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  973. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  974. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  975. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  976. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  977. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  978. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  979. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  980. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  981. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  982. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  983. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  984. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  985. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  986. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  987. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  988. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  989. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  990. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  991. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  992. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  993. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  994. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  995. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  996. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  997. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  998. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  999. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1000. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1001. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1002. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1003. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1004. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1005. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1006. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1007. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1008. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1009. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1010. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1011. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1012. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1013. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1014. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1015. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1016. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1017. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1018. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1019. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1020. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1021. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1022. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1023. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1024. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1025. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1026. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1027. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1028. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1029. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1030. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1031. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1032. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1033. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1034. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1035. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1036. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1037. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1038. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1039. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1040. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1041. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1042. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1043. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1044. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1045. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1046. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1047. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1048. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1049. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1050. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1051. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1052. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1053. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1054. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1055. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1056. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1057. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1058. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1059. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1060. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1061. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1062. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1063. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1064. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1065. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1066. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1067. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1068. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1069. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1070. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1071. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1072. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1073. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1074. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1075. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1076. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1077. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1078. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1079. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1080. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1081. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1082. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1083. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1084. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1085. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1086. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1087. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1088. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1089. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1090. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1091. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1092. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1093. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1094. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1095. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1096. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1097. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1098. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1099. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1100. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1101. ]
  1102. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1103. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1104. # ###########################################################################################################
  1105. # ############################################## Shell SETUP ################################################
  1106. # ###########################################################################################################
  1107. self.shell = FCShell(app=self, version=self.version)
  1108. self.ui.shell_dock.setWidget(self.shell)
  1109. self.log.debug("TCL Shell has been initialized.")
  1110. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1111. if self.defaults["global_shell_at_startup"]:
  1112. self.ui.shell_dock.show()
  1113. else:
  1114. self.ui.shell_dock.hide()
  1115. # ###########################################################################################################
  1116. # ########################################## Tools and Plugins ##############################################
  1117. # ###########################################################################################################
  1118. self.dblsidedtool = None
  1119. self.distance_tool = None
  1120. self.distance_min_tool = None
  1121. self.panelize_tool = None
  1122. self.film_tool = None
  1123. self.paste_tool = None
  1124. self.calculator_tool = None
  1125. self.rules_tool = None
  1126. self.sub_tool = None
  1127. self.move_tool = None
  1128. self.cutout_tool = None
  1129. self.ncclear_tool = None
  1130. self.optimal_tool = None
  1131. self.paint_tool = None
  1132. self.transform_tool = None
  1133. self.properties_tool = None
  1134. self.pdf_tool = None
  1135. self.image_tool = None
  1136. self.pcb_wizard_tool = None
  1137. self.cal_exc_tool = None
  1138. self.qrcode_tool = None
  1139. self.copper_thieving_tool = None
  1140. self.fiducial_tool = None
  1141. self.edrills_tool = None
  1142. self.align_objects_tool = None
  1143. self.punch_tool = None
  1144. self.invert_tool = None
  1145. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1146. try:
  1147. self.install_tools()
  1148. except AttributeError as e:
  1149. log.debug("App.__init__() install tools() --> %s" % str(e))
  1150. # ###########################################################################################################
  1151. # ############################################ SETUP RECENT ITEMS ###########################################
  1152. # ###########################################################################################################
  1153. self.setup_recent_items()
  1154. # ###########################################################################################################
  1155. # ######################################### BookMarks Manager ###############################################
  1156. # ###########################################################################################################
  1157. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1158. self.install_bookmarks()
  1159. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1160. # ###########################################################################################################
  1161. # ########################################### Tools Database ################################################
  1162. # ###########################################################################################################
  1163. self.tools_db_tab = None
  1164. # ### System Font Parsing ###
  1165. # self.f_parse = ParseFont(self)
  1166. # self.parse_system_fonts()
  1167. # ###########################################################################################################
  1168. # ######################################### Check for updates ###############################################
  1169. # ###########################################################################################################
  1170. # Separate thread (Not worker)
  1171. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1172. if (self.beta is False or self.beta is None) and \
  1173. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1174. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1175. # self.thr2 = QtCore.QThread()
  1176. self.worker_task.emit({'fcn': self.version_check,
  1177. 'params': []})
  1178. # self.thr2.start(QtCore.QThread.LowPriority)
  1179. # ###########################################################################################################
  1180. # ##################################### Register files with FlatCAM; #######################################
  1181. # ################################### It works only for Windows for now ####################################
  1182. # ###########################################################################################################
  1183. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1184. self.on_register_files()
  1185. # ###########################################################################################################
  1186. # ######################################## Variables for global usage #######################################
  1187. # ###########################################################################################################
  1188. # hold the App units
  1189. self.units = 'MM'
  1190. # coordinates for relative position display
  1191. self.rel_point1 = (0, 0)
  1192. self.rel_point2 = (0, 0)
  1193. # variable to store coordinates
  1194. self.pos = (0, 0)
  1195. self.pos_canvas = (0, 0)
  1196. self.pos_jump = (0, 0)
  1197. # variable to store mouse coordinates
  1198. self.mouse = [0, 0]
  1199. # variable to store the delta positions on cavnas
  1200. self.dx = 0
  1201. self.dy = 0
  1202. # decide if we have a double click or single click
  1203. self.doubleclick = False
  1204. # store here the is_dragging value
  1205. self.event_is_dragging = False
  1206. # variable to store if a command is active (then the var is not None) and which one it is
  1207. self.command_active = None
  1208. # variable to store the status of moving selection action
  1209. # None value means that it's not an selection action
  1210. # True value = a selection from left to right
  1211. # False value = a selection from right to left
  1212. self.selection_type = None
  1213. # List to store the objects that are currently loaded in FlatCAM
  1214. # This list is updated on each object creation or object delete
  1215. self.all_objects_list = []
  1216. self.objects_under_the_click_list = []
  1217. # List to store the objects that are selected
  1218. self.sel_objects_list = []
  1219. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1220. self.key_modifiers = None
  1221. # Variable to hold the status of the axis
  1222. self.toggle_axis = True
  1223. # Variable to hold the status of the grid lines
  1224. self.toggle_grid_lines = True
  1225. # Variable to store the status of the fullscreen event
  1226. self.toggle_fscreen = False
  1227. # Variable to store the status of the code editor
  1228. self.toggle_codeeditor = False
  1229. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1230. self.click_noproject = False
  1231. self.cursor = None
  1232. # Variable to store the GCODE that was edited
  1233. self.gcode_edited = ""
  1234. self.text_editor_tab = None
  1235. # reference for the self.ui.code_editor
  1236. self.reference_code_editor = None
  1237. self.script_code = ''
  1238. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1239. self.tools_db_changed_flag = False
  1240. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1241. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1242. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1243. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1244. 'tsm']
  1245. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1246. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1247. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1248. 'sbp', 'tap', 'xpi']
  1249. self.svg_list = ['svg']
  1250. self.dxf_list = ['dxf']
  1251. self.pdf_list = ['pdf']
  1252. self.prj_list = ['flatprj']
  1253. self.conf_list = ['flatconfig']
  1254. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1255. # flag for polygons not cleared
  1256. self.poly_not_cleared = False
  1257. # VisPy visuals
  1258. self.isHovering = False
  1259. self.notHovering = True
  1260. # Window geometry
  1261. self.x_pos = None
  1262. self.y_pos = None
  1263. self.width = None
  1264. self.height = None
  1265. # when True, the app has to return from any thread
  1266. self.abort_flag = False
  1267. # set the value used in the Windows Title
  1268. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1269. # this holds a widget that is installed in the Plot Area when View Source option is used
  1270. self.source_editor_tab = None
  1271. self.pagesize = {}
  1272. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1273. # VisPy visuals
  1274. if self.is_legacy is False:
  1275. try:
  1276. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1277. except AttributeError:
  1278. self.tool_shapes = None
  1279. else:
  1280. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1281. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1282. # used in the delayed shutdown self.start_delayed_quit() method
  1283. self.save_timer = None
  1284. # ###########################################################################################################
  1285. # ################################## ADDING FlatCAM EDITORS section #########################################
  1286. # ###########################################################################################################
  1287. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1288. # at the first launch of the App , the editors will not be functional.
  1289. try:
  1290. self.geo_editor = FlatCAMGeoEditor(self)
  1291. except AttributeError:
  1292. pass
  1293. try:
  1294. self.exc_editor = FlatCAMExcEditor(self)
  1295. except AttributeError:
  1296. pass
  1297. try:
  1298. self.grb_editor = FlatCAMGrbEditor(self)
  1299. except AttributeError:
  1300. pass
  1301. self.log.debug("Finished adding FlatCAM Editor's.")
  1302. self.set_ui_title(name=_("New Project - Not saved"))
  1303. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1304. current_platform = platform.architecture()[0]
  1305. if current_platform != '64bit':
  1306. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1307. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1308. # ###########################################################################################################
  1309. # ##################################### Finished the CONSTRUCTOR ############################################
  1310. # ###########################################################################################################
  1311. App.log.debug("END of constructor. Releasing control.")
  1312. # ###########################################################################################################
  1313. # ########################################## SHOW GUI #######################################################
  1314. # ###########################################################################################################
  1315. # if the app is not started as headless, show it
  1316. if self.cmd_line_headless != 1:
  1317. if show_splash:
  1318. # finish the splash
  1319. self.splash.finish(self.ui)
  1320. mgui_settings = QSettings("Open Source", "FlatCAM")
  1321. if mgui_settings.contains("maximized_gui"):
  1322. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1323. if maximized_ui is True:
  1324. self.ui.showMaximized()
  1325. else:
  1326. self.ui.show()
  1327. else:
  1328. self.ui.show()
  1329. if self.defaults["global_systray_icon"]:
  1330. self.trayIcon.show()
  1331. else:
  1332. log.warning("******************* RUNNING HEADLESS *******************")
  1333. # ###########################################################################################################
  1334. # ######################################## START-UP ARGUMENTS ###############################################
  1335. # ###########################################################################################################
  1336. # test if the program was started with a script as parameter
  1337. if self.cmd_line_shellvar:
  1338. try:
  1339. cnt = 0
  1340. command_tcl = 0
  1341. for i in self.cmd_line_shellvar.split(','):
  1342. if i is not None:
  1343. # noinspection PyBroadException
  1344. try:
  1345. command_tcl = eval(i)
  1346. except Exception:
  1347. command_tcl = i
  1348. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1349. cnt += 1
  1350. # if there are Windows paths then replace the path separator with a Unix like one
  1351. if sys.platform == 'win32':
  1352. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1353. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1354. except Exception as ext:
  1355. print("ERROR: ", ext)
  1356. sys.exit(2)
  1357. if self.cmd_line_shellfile:
  1358. if self.cmd_line_headless != 1:
  1359. if self.ui.shell_dock.isHidden():
  1360. self.ui.shell_dock.show()
  1361. try:
  1362. with open(self.cmd_line_shellfile, "r") as myfile:
  1363. # if show_splash:
  1364. # self.splash.showMessage('%s: %ssec\n%s' % (
  1365. # _("Canvas initialization started.\n"
  1366. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1367. # _("Executing Tcl Script ...")),
  1368. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1369. # color=QtGui.QColor("gray"))
  1370. cmd_line_shellfile_text = myfile.read()
  1371. if self.cmd_line_headless != 1:
  1372. self.shell.exec_command(cmd_line_shellfile_text)
  1373. else:
  1374. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1375. except Exception as ext:
  1376. print("ERROR: ", ext)
  1377. sys.exit(2)
  1378. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1379. # the path/file_name must be enclosed in quotes if it contain spaces
  1380. if App.args:
  1381. self.args_at_startup.emit(App.args)
  1382. if self.defaults.old_defaults_found is True:
  1383. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1384. "Please reboot the application to update."))
  1385. self.defaults.old_defaults_found = False
  1386. # ######################################### INIT FINISHED #######################################################
  1387. # #################################################################################################################
  1388. # #################################################################################################################
  1389. # #################################################################################################################
  1390. # #################################################################################################################
  1391. # #################################################################################################################
  1392. @staticmethod
  1393. def copy_and_overwrite(from_path, to_path):
  1394. """
  1395. From here:
  1396. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1397. :param from_path: source path
  1398. :param to_path: destination path
  1399. :return: None
  1400. """
  1401. if os.path.exists(to_path):
  1402. shutil.rmtree(to_path)
  1403. try:
  1404. shutil.copytree(from_path, to_path)
  1405. except FileNotFoundError:
  1406. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1407. shutil.copytree(from_new_path, to_path)
  1408. def on_startup_args(self, args, silent=False):
  1409. """
  1410. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1411. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1412. :param args: a list containing the application args at startup
  1413. :return: None
  1414. """
  1415. if args is not None:
  1416. args_to_process = args
  1417. else:
  1418. args_to_process = App.args
  1419. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1420. for argument in args_to_process:
  1421. if '.FlatPrj'.lower() in argument.lower():
  1422. try:
  1423. project_name = str(argument)
  1424. if project_name == "":
  1425. if silent is False:
  1426. self.inform.emit(_("Cancelled."))
  1427. else:
  1428. # self.open_project(project_name)
  1429. run_from_arg = True
  1430. # self.worker_task.emit({'fcn': self.open_project,
  1431. # 'params': [project_name, run_from_arg]})
  1432. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1433. except Exception as e:
  1434. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1435. elif '.FlatConfig'.lower() in argument.lower():
  1436. try:
  1437. file_name = str(argument)
  1438. if file_name == "":
  1439. if silent is False:
  1440. self.inform.emit(_("Open Config file failed."))
  1441. else:
  1442. run_from_arg = True
  1443. # self.worker_task.emit({'fcn': self.open_config_file,
  1444. # 'params': [file_name, run_from_arg]})
  1445. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1446. except Exception as e:
  1447. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1448. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1449. try:
  1450. file_name = str(argument)
  1451. if file_name == "":
  1452. if silent is False:
  1453. self.inform.emit(_("Open Script file failed."))
  1454. else:
  1455. if silent is False:
  1456. self.on_fileopenscript(name=file_name)
  1457. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1458. self.on_filerunscript(name=file_name)
  1459. except Exception as e:
  1460. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1461. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1462. log.debug("App.on_startup_args() --> Quit event.")
  1463. sys.exit()
  1464. elif 'save'.lower() in argument.lower():
  1465. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1466. self.preferencesUiManager.save_defaults()
  1467. else:
  1468. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1469. proc_arg = argument.lower()
  1470. for ext in exc_list:
  1471. proc_ext = ext.replace(' ', '')
  1472. proc_ext = '.%s' % proc_ext
  1473. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1474. file_name = str(argument)
  1475. if file_name == "":
  1476. if silent is False:
  1477. self.inform.emit(_("Open Excellon file failed."))
  1478. else:
  1479. self.on_fileopenexcellon(name=file_name, signal=None)
  1480. return
  1481. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1482. for ext in gco_list:
  1483. proc_ext = ext.replace(' ', '')
  1484. proc_ext = '.%s' % proc_ext
  1485. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1486. file_name = str(argument)
  1487. if file_name == "":
  1488. if silent is False:
  1489. self.inform.emit(_("Open GCode file failed."))
  1490. else:
  1491. self.on_fileopengcode(name=file_name, signal=None)
  1492. return
  1493. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1494. for ext in grb_list:
  1495. proc_ext = ext.replace(' ', '')
  1496. proc_ext = '.%s' % proc_ext
  1497. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1498. file_name = str(argument)
  1499. if file_name == "":
  1500. if silent is False:
  1501. self.inform.emit(_("Open Gerber file failed."))
  1502. else:
  1503. self.on_fileopengerber(name=file_name, signal=None)
  1504. return
  1505. # if it reached here without already returning then the app was registered with a file that it does not
  1506. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1507. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1508. # for arg in args_to_process:
  1509. # if 'FlatCAM.exe' in arg:
  1510. # continue
  1511. # else:
  1512. # sys.exit(2)
  1513. def set_ui_title(self, name):
  1514. """
  1515. Sets the title of the main window.
  1516. :param name: String that store the project path and project name
  1517. :return: None
  1518. """
  1519. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1520. (self.version,
  1521. ('BETA' if self.beta else ''),
  1522. platform.architecture()[0],
  1523. self.engine,
  1524. name)
  1525. )
  1526. def on_app_restart(self):
  1527. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1528. # be left in the SySTray
  1529. try:
  1530. self.trayIcon.hide()
  1531. except Exception:
  1532. pass
  1533. fcTranslate.restart_program(app=self)
  1534. def clear_pool(self):
  1535. """
  1536. Clear the multiprocessing pool and calls garbage collector.
  1537. :return: None
  1538. """
  1539. self.pool.close()
  1540. self.pool = Pool()
  1541. self.pool_recreated.emit(self.pool)
  1542. gc.collect()
  1543. def install_tools(self):
  1544. """
  1545. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1546. Instantiation of the Tools classes.
  1547. The order that the tools are installed is important as they can depend on each other install position.
  1548. :return: None
  1549. """
  1550. self.distance_tool = Distance(self)
  1551. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1552. before=self.ui.menueditorigin,
  1553. separator=False)
  1554. self.distance_min_tool = DistanceMin(self)
  1555. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1556. pos=self.ui.menuedit,
  1557. before=self.ui.menueditorigin,
  1558. separator=True)
  1559. self.dblsidedtool = DblSidedTool(self)
  1560. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1561. self.cal_exc_tool = ToolCalibration(self)
  1562. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1563. before=self.dblsidedtool.menuAction,
  1564. separator=False)
  1565. self.align_objects_tool = AlignObjects(self)
  1566. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1567. self.edrills_tool = ToolExtractDrills(self)
  1568. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1569. self.panelize_tool = Panelize(self)
  1570. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1571. self.film_tool = Film(self)
  1572. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1573. self.paste_tool = SolderPaste(self)
  1574. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1575. self.calculator_tool = ToolCalculator(self)
  1576. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1577. self.sub_tool = ToolSub(self)
  1578. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1579. pos=self.ui.menutool, separator=True)
  1580. self.rules_tool = RulesCheck(self)
  1581. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1582. pos=self.ui.menutool, separator=False)
  1583. self.optimal_tool = ToolOptimal(self)
  1584. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1585. pos=self.ui.menutool, separator=True)
  1586. self.move_tool = ToolMove(self)
  1587. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1588. before=self.ui.menueditorigin, separator=True)
  1589. self.cutout_tool = CutOut(self)
  1590. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1591. before=self.sub_tool.menuAction)
  1592. self.ncclear_tool = NonCopperClear(self)
  1593. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1594. before=self.sub_tool.menuAction, separator=True)
  1595. self.paint_tool = ToolPaint(self)
  1596. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1597. before=self.sub_tool.menuAction, separator=True)
  1598. self.copper_thieving_tool = ToolCopperThieving(self)
  1599. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1600. pos=self.ui.menutool)
  1601. self.fiducial_tool = ToolFiducials(self)
  1602. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1603. pos=self.ui.menutool)
  1604. self.qrcode_tool = QRCode(self)
  1605. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1606. pos=self.ui.menutool)
  1607. self.punch_tool = ToolPunchGerber(self)
  1608. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1609. self.invert_tool = ToolInvertGerber(self)
  1610. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1611. self.transform_tool = ToolTransform(self)
  1612. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1613. pos=self.ui.menuoptions, separator=True)
  1614. self.properties_tool = Properties(self)
  1615. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1616. pos=self.ui.menuoptions)
  1617. self.pdf_tool = ToolPDF(self)
  1618. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1619. pos=self.ui.menufileimport,
  1620. separator=True)
  1621. self.image_tool = ToolImage(self)
  1622. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1623. pos=self.ui.menufileimport,
  1624. separator=True)
  1625. self.pcb_wizard_tool = PcbWizard(self)
  1626. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1627. pos=self.ui.menufileimport)
  1628. self.log.debug("Tools are installed.")
  1629. def remove_tools(self):
  1630. """
  1631. Will remove all the actions in the Tool menu.
  1632. :return: None
  1633. """
  1634. for act in self.ui.menutool.actions():
  1635. self.ui.menutool.removeAction(act)
  1636. def init_tools(self):
  1637. """
  1638. Initialize the Tool tab in the notebook side of the central widget.
  1639. Remove the actions in the Tools menu.
  1640. Instantiate again the FlatCAM tools (plugins).
  1641. All this is required when changing the layout: standard, compact etc.
  1642. :return: None
  1643. """
  1644. log.debug("init_tools()")
  1645. # delete the data currently in the Tools Tab and the Tab itself
  1646. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1647. if widget is not None:
  1648. widget.deleteLater()
  1649. self.ui.notebook.removeTab(2)
  1650. # rebuild the Tools Tab
  1651. self.ui.tool_tab = QtWidgets.QWidget()
  1652. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1653. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1654. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1655. self.ui.tool_scroll_area = VerticalScrollArea()
  1656. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1657. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1658. # first remove all of them
  1659. self.remove_tools()
  1660. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1661. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1662. '&Command Line\tS')
  1663. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1664. # third install all of them
  1665. try:
  1666. self.install_tools()
  1667. except AttributeError:
  1668. pass
  1669. self.log.debug("Tools are initialized.")
  1670. # def parse_system_fonts(self):
  1671. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1672. # 'params': []})
  1673. def connect_toolbar_signals(self):
  1674. """
  1675. Reconnect the signals to the actions in the toolbar.
  1676. This has to be done each time after the FlatCAM tools are removed/installed.
  1677. :return: None
  1678. """
  1679. # Toolbar
  1680. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1681. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1682. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1683. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1684. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1685. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1686. self.ui.replot_btn.triggered.connect(self.plot_all)
  1687. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1688. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1689. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1690. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1691. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1692. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1693. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1694. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1695. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1696. self.ui.delete_btn.triggered.connect(self.on_delete)
  1697. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1698. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1699. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1700. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1701. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1702. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1703. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1704. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1705. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1706. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1707. # Tools Toolbar Signals
  1708. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1709. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1710. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1711. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1712. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1713. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1714. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1715. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1716. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1717. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1718. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1719. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1720. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1721. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1722. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1723. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1724. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1725. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1726. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1727. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1728. def object2editor(self):
  1729. """
  1730. Send the current Geometry or Excellon object (if any) into the it's editor.
  1731. :return: None
  1732. """
  1733. self.defaults.report_usage("object2editor()")
  1734. # disable the objects menu as it may interfere with the Editors
  1735. self.ui.menuobjects.setDisabled(True)
  1736. edited_object = self.collection.get_active()
  1737. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1738. isinstance(edited_object, ExcellonObject):
  1739. pass
  1740. else:
  1741. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1742. return
  1743. if isinstance(edited_object, GeometryObject):
  1744. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1745. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1746. # we set the notebook to hidden
  1747. # self.ui.splitter.setSizes([0, 1])
  1748. if edited_object.multigeo is True:
  1749. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1750. if len(sel_rows) > 1:
  1751. self.inform.emit('[WARNING_NOTCL] %s' %
  1752. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1753. "is not possible.\n"
  1754. "Edit only one geometry at a time."))
  1755. # determine the tool dia of the selected tool
  1756. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1757. # now find the key in the edited_object.tools that has this tooldia
  1758. multi_tool = 1
  1759. for tool in edited_object.tools:
  1760. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1761. multi_tool = tool
  1762. break
  1763. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1764. else:
  1765. self.geo_editor.edit_fcgeometry(edited_object)
  1766. # set call source to the Editor we go into
  1767. self.call_source = 'geo_editor'
  1768. elif isinstance(edited_object, ExcellonObject):
  1769. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1770. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1771. if self.ui.splitter.sizes()[0] == 0:
  1772. self.ui.splitter.setSizes([1, 1])
  1773. self.exc_editor.edit_fcexcellon(edited_object)
  1774. # set call source to the Editor we go into
  1775. self.call_source = 'exc_editor'
  1776. elif isinstance(edited_object, GerberObject):
  1777. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1778. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1779. if self.ui.splitter.sizes()[0] == 0:
  1780. self.ui.splitter.setSizes([1, 1])
  1781. self.grb_editor.edit_fcgerber(edited_object)
  1782. # set call source to the Editor we go into
  1783. self.call_source = 'grb_editor'
  1784. # reset the following variables so the UI is built again after edit
  1785. edited_object.ui_build = False
  1786. edited_object.build_aperture_storage = False
  1787. # make sure that we can't select another object while in Editor Mode:
  1788. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1789. self.ui.project_frame.setDisabled(True)
  1790. # delete any selection shape that might be active as they are not relevant in Editor
  1791. self.delete_selection_shape()
  1792. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1793. self.ui.plot_tab_area.protectTab(0)
  1794. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1795. self.should_we_save = True
  1796. def editor2object(self, cleanup=None):
  1797. """
  1798. Transfers the Geometry or Excellon from it's editor to the current object.
  1799. :return: None
  1800. """
  1801. self.defaults.report_usage("editor2object()")
  1802. # re-enable the objects menu that was disabled on entry in Editor mode
  1803. self.ui.menuobjects.setDisabled(False)
  1804. # do not update a geometry or excellon object unless it comes out of an editor
  1805. if self.call_source != 'app':
  1806. edited_obj = self.collection.get_active()
  1807. if cleanup is None:
  1808. msgbox = QtWidgets.QMessageBox()
  1809. msgbox.setText(_("Do you want to save the edited object?"))
  1810. msgbox.setWindowTitle(_("Close Editor"))
  1811. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1812. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1813. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1814. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1815. msgbox.setDefaultButton(bt_yes)
  1816. msgbox.exec_()
  1817. response = msgbox.clickedButton()
  1818. if response == bt_yes:
  1819. # clean the Tools Tab
  1820. self.ui.tool_scroll_area.takeWidget()
  1821. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1822. self.ui.notebook.setTabText(2, "Tool")
  1823. if isinstance(edited_obj, GeometryObject):
  1824. obj_type = "Geometry"
  1825. if cleanup is None:
  1826. self.geo_editor.update_fcgeometry(edited_obj)
  1827. # self.geo_editor.update_options(edited_obj)
  1828. self.geo_editor.deactivate()
  1829. # restore GUI to the Selected TAB
  1830. # Remove anything else in the GUI
  1831. self.ui.tool_scroll_area.takeWidget()
  1832. # update the geo object options so it is including the bounding box values
  1833. try:
  1834. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1835. edited_obj.options['xmin'] = xmin
  1836. edited_obj.options['ymin'] = ymin
  1837. edited_obj.options['xmax'] = xmax
  1838. edited_obj.options['ymax'] = ymax
  1839. except AttributeError as e:
  1840. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1841. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1842. edited_obj.build_ui()
  1843. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1844. elif isinstance(edited_obj, GerberObject):
  1845. obj_type = "Gerber"
  1846. if cleanup is None:
  1847. self.grb_editor.update_fcgerber()
  1848. self.grb_editor.update_options(edited_obj)
  1849. self.grb_editor.deactivate_grb_editor()
  1850. # delete the old object (the source object) if it was an empty one
  1851. try:
  1852. if len(edited_obj.solid_geometry) == 0:
  1853. old_name = edited_obj.options['name']
  1854. self.collection.set_active(old_name)
  1855. self.collection.delete_active()
  1856. except TypeError:
  1857. # if the solid_geometry is a single Polygon the len() will not work
  1858. # in any case, falling here means that we have something in the solid_geometry, even if only
  1859. # a single Polygon, therefore we pass this
  1860. pass
  1861. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1862. # restore GUI to the Selected TAB
  1863. # Remove anything else in the GUI
  1864. self.ui.selected_scroll_area.takeWidget()
  1865. elif isinstance(edited_obj, ExcellonObject):
  1866. obj_type = "Excellon"
  1867. if cleanup is None:
  1868. self.exc_editor.update_fcexcellon(edited_obj)
  1869. # self.exc_editor.update_options(edited_obj)
  1870. self.exc_editor.deactivate()
  1871. # restore GUI to the Selected TAB
  1872. # Remove anything else in the GUI
  1873. self.ui.tool_scroll_area.takeWidget()
  1874. # delete the old object (the source object) if it was an empty one
  1875. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1876. old_name = edited_obj.options['name']
  1877. self.collection.delete_by_name(name=old_name)
  1878. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1879. else:
  1880. self.inform.emit('[WARNING_NOTCL] %s' %
  1881. _("Select a Gerber, Geometry or Excellon Object to update."))
  1882. return
  1883. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1884. elif response == bt_no:
  1885. # clean the Tools Tab
  1886. self.ui.tool_scroll_area.takeWidget()
  1887. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1888. self.ui.notebook.setTabText(2, "Tool")
  1889. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1890. if isinstance(edited_obj, GeometryObject):
  1891. self.geo_editor.deactivate()
  1892. edited_obj.build_ui()
  1893. elif isinstance(edited_obj, GerberObject):
  1894. self.grb_editor.deactivate_grb_editor()
  1895. edited_obj.build_ui()
  1896. elif isinstance(edited_obj, ExcellonObject):
  1897. self.exc_editor.deactivate()
  1898. edited_obj.build_ui()
  1899. else:
  1900. self.inform.emit('[WARNING_NOTCL] %s' %
  1901. _("Select a Gerber, Geometry or Excellon Object to update."))
  1902. return
  1903. elif response == bt_cancel:
  1904. return
  1905. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1906. # edited_obj.build_ui()
  1907. # Switch notebook to Selected page
  1908. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1909. else:
  1910. if isinstance(edited_obj, GeometryObject):
  1911. self.geo_editor.deactivate()
  1912. elif isinstance(edited_obj, GerberObject):
  1913. self.grb_editor.deactivate_grb_editor()
  1914. elif isinstance(edited_obj, ExcellonObject):
  1915. self.exc_editor.deactivate()
  1916. else:
  1917. self.inform.emit('[WARNING_NOTCL] %s' %
  1918. _("Select a Gerber, Geometry or Excellon Object to update."))
  1919. return
  1920. # if notebook is hidden we show it
  1921. if self.ui.splitter.sizes()[0] == 0:
  1922. self.ui.splitter.setSizes([1, 1])
  1923. # restore the call_source to app
  1924. self.call_source = 'app'
  1925. edited_obj.plot()
  1926. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1927. self.ui.plot_tab_area.protectTab(0)
  1928. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1929. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1930. self.ui.project_frame.setDisabled(False)
  1931. def get_last_folder(self):
  1932. """
  1933. Get the folder path from where the last file was opened.
  1934. :return: String, last opened folder path
  1935. """
  1936. return self.defaults["global_last_folder"]
  1937. def get_last_save_folder(self):
  1938. """
  1939. Get the folder path from where the last file was saved.
  1940. :return: String, last saved folder path
  1941. """
  1942. loc = self.defaults["global_last_save_folder"]
  1943. if loc is None:
  1944. loc = self.defaults["global_last_folder"]
  1945. if loc is None:
  1946. loc = os.path.dirname(__file__)
  1947. return loc
  1948. def info(self, msg):
  1949. """
  1950. Informs the user. Normally on the status bar, optionally
  1951. also on the shell.
  1952. :param msg: Text to write.
  1953. :return: None
  1954. """
  1955. # Type of message in brackets at the beginning of the message.
  1956. match = re.search(r"\[(.*)\](.*)", msg)
  1957. if match:
  1958. level = match.group(1)
  1959. msg_ = match.group(2)
  1960. self.ui.fcinfo.set_status(str(msg_), level=level)
  1961. if level.lower() == "error":
  1962. self.shell_message(msg, error=True, show=True)
  1963. elif level.lower() == "warning":
  1964. self.shell_message(msg, warning=True, show=True)
  1965. elif level.lower() == "error_notcl":
  1966. self.shell_message(msg, error=True, show=False)
  1967. elif level.lower() == "warning_notcl":
  1968. self.shell_message(msg, warning=True, show=False)
  1969. elif level.lower() == "success":
  1970. self.shell_message(msg, success=True, show=False)
  1971. elif level.lower() == "selected":
  1972. self.shell_message(msg, selected=True, show=False)
  1973. else:
  1974. self.shell_message(msg, show=False)
  1975. else:
  1976. self.ui.fcinfo.set_status(str(msg), level="info")
  1977. # make sure that if the message is to clear the infobar with a space
  1978. # is not printed over and over on the shell
  1979. if msg != '':
  1980. self.shell_message(msg)
  1981. def restore_toolbar_view(self):
  1982. """
  1983. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1984. was saved in the defaults dictionary.
  1985. :return: None
  1986. """
  1987. tb = self.defaults["global_toolbar_view"]
  1988. if tb & 1:
  1989. self.ui.toolbarfile.setVisible(True)
  1990. else:
  1991. self.ui.toolbarfile.setVisible(False)
  1992. if tb & 2:
  1993. self.ui.toolbargeo.setVisible(True)
  1994. else:
  1995. self.ui.toolbargeo.setVisible(False)
  1996. if tb & 4:
  1997. self.ui.toolbarview.setVisible(True)
  1998. else:
  1999. self.ui.toolbarview.setVisible(False)
  2000. if tb & 8:
  2001. self.ui.toolbartools.setVisible(True)
  2002. else:
  2003. self.ui.toolbartools.setVisible(False)
  2004. if tb & 16:
  2005. self.ui.exc_edit_toolbar.setVisible(True)
  2006. else:
  2007. self.ui.exc_edit_toolbar.setVisible(False)
  2008. if tb & 32:
  2009. self.ui.geo_edit_toolbar.setVisible(True)
  2010. else:
  2011. self.ui.geo_edit_toolbar.setVisible(False)
  2012. if tb & 64:
  2013. self.ui.grb_edit_toolbar.setVisible(True)
  2014. else:
  2015. self.ui.grb_edit_toolbar.setVisible(False)
  2016. if tb & 128:
  2017. self.ui.snap_toolbar.setVisible(True)
  2018. else:
  2019. self.ui.snap_toolbar.setVisible(False)
  2020. if tb & 256:
  2021. self.ui.toolbarshell.setVisible(True)
  2022. else:
  2023. self.ui.toolbarshell.setVisible(False)
  2024. def on_import_preferences(self):
  2025. """
  2026. Loads the application default settings from a saved file into
  2027. ``self.defaults`` dictionary.
  2028. :return: None
  2029. """
  2030. self.defaults.report_usage("on_import_preferences")
  2031. App.log.debug("App.on_import_preferences()")
  2032. # Show file chooser
  2033. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2034. try:
  2035. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2036. directory=self.data_path,
  2037. filter=filter_)
  2038. except TypeError:
  2039. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2040. filter=filter_)
  2041. filename = str(filename)
  2042. if filename == "":
  2043. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2044. return
  2045. # Load in the defaults from the chosen file
  2046. self.defaults.load(filename=filename)
  2047. self.preferencesUiManager.on_preferences_edited()
  2048. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2049. def on_export_preferences(self):
  2050. """
  2051. Save the defaults dictionary to a file.
  2052. :return: None
  2053. """
  2054. self.defaults.report_usage("on_export_preferences")
  2055. App.log.debug("on_export_preferences()")
  2056. # defaults_file_content = None
  2057. # Show file chooser
  2058. date = str(datetime.today()).rpartition('.')[0]
  2059. date = ''.join(c for c in date if c not in ':-')
  2060. date = date.replace(' ', '_')
  2061. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2062. try:
  2063. filename, _f = FCFileSaveDialog.get_saved_filename(
  2064. caption=_("Export FlatCAM Preferences"),
  2065. directory=self.data_path + '/preferences_' + date,
  2066. filter=filter__
  2067. )
  2068. except TypeError:
  2069. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2070. filename = str(filename)
  2071. if filename == "":
  2072. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2073. return
  2074. # Update options
  2075. self.preferencesUiManager.defaults_read_form()
  2076. self.defaults.propagate_defaults()
  2077. # Save update options
  2078. try:
  2079. self.defaults.write(filename=filename)
  2080. except Exception:
  2081. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2082. return
  2083. if self.defaults["global_open_style"] is False:
  2084. self.file_opened.emit("preferences", filename)
  2085. self.file_saved.emit("preferences", filename)
  2086. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2087. def save_to_file(self, content_to_save, txt_content):
  2088. """
  2089. Save something to a file.
  2090. :return: None
  2091. """
  2092. self.defaults.report_usage("save_to_file")
  2093. App.log.debug("save_to_file()")
  2094. self.date = str(datetime.today()).rpartition('.')[0]
  2095. self.date = ''.join(c for c in self.date if c not in ':-')
  2096. self.date = self.date.replace(' ', '_')
  2097. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2098. path_to_save = self.defaults["global_last_save_folder"] if\
  2099. self.defaults["global_last_save_folder"] is not None else self.data_path
  2100. try:
  2101. filename, _f = FCFileSaveDialog.get_saved_filename(
  2102. caption=_("Save to file"),
  2103. directory=path_to_save + '/file_' + self.date,
  2104. filter=filter__
  2105. )
  2106. except TypeError:
  2107. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2108. filename = str(filename)
  2109. if filename == "":
  2110. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2111. return
  2112. else:
  2113. try:
  2114. with open(filename, 'w') as f:
  2115. ___ = f.read()
  2116. except PermissionError:
  2117. self.inform.emit('[WARNING] %s' %
  2118. _("Permission denied, saving not possible.\n"
  2119. "Most likely another app is holding the file open and not accessible."))
  2120. return
  2121. except IOError:
  2122. App.log.debug('Creating a new file ...')
  2123. f = open(filename, 'w')
  2124. f.close()
  2125. except Exception:
  2126. e = sys.exc_info()[0]
  2127. App.log.error("Could not load the file.")
  2128. App.log.error(str(e))
  2129. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2130. return
  2131. # Save content
  2132. if filename.rpartition('.')[2].lower() == 'html':
  2133. file_content = content_to_save
  2134. else:
  2135. file_content = txt_content
  2136. try:
  2137. with open(filename, "w") as f:
  2138. f.write(file_content)
  2139. except Exception:
  2140. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2141. return
  2142. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2143. def save_geometry(self, x, y, width, height, notebook_width):
  2144. """
  2145. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2146. launch of the application.
  2147. :param x: X position of the main window
  2148. :param y: Y position of the main window
  2149. :param width: width of the main window
  2150. :param height: height of the main window
  2151. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2152. :return: None
  2153. """
  2154. self.defaults["global_def_win_x"] = x
  2155. self.defaults["global_def_win_y"] = y
  2156. self.defaults["global_def_win_w"] = width
  2157. self.defaults["global_def_win_h"] = height
  2158. self.defaults["global_def_notebook_width"] = notebook_width
  2159. self.preferencesUiManager.save_defaults()
  2160. def restore_main_win_geom(self):
  2161. try:
  2162. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2163. self.defaults["global_def_win_y"],
  2164. self.defaults["global_def_win_w"],
  2165. self.defaults["global_def_win_h"])
  2166. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2167. except KeyError as e:
  2168. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2169. def message_dialog(self, title, message, kind="info"):
  2170. """
  2171. Builds and show a custom QMessageBox to be used in FlatCAM.
  2172. :param title: title of the QMessageBox
  2173. :param message: message to be displayed
  2174. :param kind: type of QMessageBox; will display a specific icon.
  2175. :return:
  2176. """
  2177. icon = {"info": QtWidgets.QMessageBox.Information,
  2178. "warning": QtWidgets.QMessageBox.Warning,
  2179. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2180. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2181. dlg.setText(message)
  2182. dlg.exec_()
  2183. def register_recent(self, kind, filename):
  2184. """
  2185. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2186. dictionary.
  2187. :param kind: type of file that was opened
  2188. :param filename: the path and file name for the file that was opened
  2189. :return:
  2190. """
  2191. self.log.debug("register_recent()")
  2192. self.log.debug(" %s" % kind)
  2193. self.log.debug(" %s" % filename)
  2194. record = {'kind': str(kind), 'filename': str(filename)}
  2195. if record in self.recent:
  2196. return
  2197. if record in self.recent_projects:
  2198. return
  2199. if record['kind'] == 'project':
  2200. self.recent_projects.insert(0, record)
  2201. else:
  2202. self.recent.insert(0, record)
  2203. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2204. self.recent.pop()
  2205. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2206. self.recent_projects.pop()
  2207. try:
  2208. f = open(self.data_path + '/recent.json', 'w')
  2209. except IOError:
  2210. App.log.error("Failed to open recent items file for writing.")
  2211. self.inform.emit('[ERROR_NOTCL] %s' %
  2212. _('Failed to open recent files file for writing.'))
  2213. return
  2214. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2215. f.close()
  2216. try:
  2217. fp = open(self.data_path + '/recent_projects.json', 'w')
  2218. except IOError:
  2219. App.log.error("Failed to open recent items file for writing.")
  2220. self.inform.emit('[ERROR_NOTCL] %s' %
  2221. _('Failed to open recent projects file for writing.'))
  2222. return
  2223. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2224. fp.close()
  2225. # Re-build the recent items menu
  2226. self.setup_recent_items()
  2227. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2228. """
  2229. Creates a new specialized FlatCAMObj and attaches it to the application,
  2230. this is, updates the GUI accordingly, any other records and plots it.
  2231. This method is thread-safe.
  2232. Notes:
  2233. * If the name is in use, the self.collection will modify it
  2234. when appending it to the collection. There is no need to handle
  2235. name conflicts here.
  2236. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2237. :type kind: str
  2238. :param name: Name for the object.
  2239. :type name: str
  2240. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2241. The function is called with 2 parameters: the new object and the App instance.
  2242. :type initialize: function
  2243. :param plot: If to plot the resulting object
  2244. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2245. self.collection
  2246. :return: None
  2247. :rtype: None
  2248. """
  2249. App.log.debug("new_object()")
  2250. obj_plot = plot
  2251. obj_autoselected = autoselected
  2252. t0 = time.time() # Debug
  2253. # ## Create object
  2254. classdict = {
  2255. "gerber": GerberObject,
  2256. "excellon": ExcellonObject,
  2257. "cncjob": CNCJobObject,
  2258. "geometry": GeometryObject,
  2259. "script": ScriptObject,
  2260. "document": DocumentObject
  2261. }
  2262. App.log.debug("Calling object constructor...")
  2263. # Object creation/instantiation
  2264. obj = classdict[kind](name)
  2265. obj.units = self.options["units"]
  2266. # IMPORTANT
  2267. # The key names in defaults and options dictionary's are not random:
  2268. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2269. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2270. # copied to self.options. After that, below, depending on the type of
  2271. # object that is created, it will strip the name of the object and the underline (if the original key was
  2272. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2273. # "toolchange"
  2274. for option in self.options:
  2275. if option.find(kind + "_") == 0:
  2276. oname = option[len(kind) + 1:]
  2277. obj.options[oname] = self.options[option]
  2278. obj.isHovering = False
  2279. obj.notHovering = True
  2280. # Initialize as per user request
  2281. # User must take care to implement initialize
  2282. # in a thread-safe way as is is likely that we
  2283. # have been invoked in a separate thread.
  2284. t1 = time.time()
  2285. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2286. try:
  2287. return_value = initialize(obj, self)
  2288. except Exception as e:
  2289. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2290. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2291. msg += traceback.format_exc()
  2292. self.inform.emit(msg)
  2293. return "fail"
  2294. t2 = time.time()
  2295. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2296. if return_value == 'fail':
  2297. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2298. return "fail"
  2299. # Check units and convert if necessary
  2300. # This condition CAN be true because initialize() can change obj.units
  2301. if self.options["units"].upper() != obj.units.upper():
  2302. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2303. obj.convert_units(self.options["units"])
  2304. t3 = time.time()
  2305. self.log.debug("%f seconds converting units." % (t3 - t2))
  2306. # Create the bounding box for the object and then add the results to the obj.options
  2307. # But not for Scripts or for Documents
  2308. if kind != 'document' and kind != 'script':
  2309. try:
  2310. xmin, ymin, xmax, ymax = obj.bounds()
  2311. obj.options['xmin'] = xmin
  2312. obj.options['ymin'] = ymin
  2313. obj.options['xmax'] = xmax
  2314. obj.options['ymax'] = ymax
  2315. except Exception as e:
  2316. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2317. return "fail"
  2318. try:
  2319. if kind == 'excellon':
  2320. obj.fill_color = self.defaults["excellon_plot_fill"]
  2321. obj.outline_color = self.defaults["excellon_plot_line"]
  2322. if kind == 'gerber':
  2323. obj.fill_color = self.defaults["gerber_plot_fill"]
  2324. obj.outline_color = self.defaults["gerber_plot_line"]
  2325. except Exception as e:
  2326. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2327. # update the KeyWords list with the name of the file
  2328. self.myKeywords.append(obj.options['name'])
  2329. log.debug("Moving new object back to main thread.")
  2330. # Move the object to the main thread and let the app know that it is available.
  2331. obj.moveToThread(self.main_thread)
  2332. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2333. return obj
  2334. def new_excellon_object(self):
  2335. """
  2336. Creates a new, blank Excellon object.
  2337. :return: None
  2338. """
  2339. self.defaults.report_usage("new_excellon_object()")
  2340. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2341. def new_geometry_object(self):
  2342. """
  2343. Creates a new, blank and single-tool Geometry object.
  2344. :return: None
  2345. """
  2346. self.defaults.report_usage("new_geometry_object()")
  2347. def initialize(obj, app):
  2348. obj.multitool = False
  2349. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2350. def new_gerber_object(self):
  2351. """
  2352. Creates a new, blank Gerber object.
  2353. :return: None
  2354. """
  2355. self.defaults.report_usage("new_gerber_object()")
  2356. def initialize(grb_obj, app):
  2357. grb_obj.multitool = False
  2358. grb_obj.source_file = []
  2359. grb_obj.multigeo = False
  2360. grb_obj.follow = False
  2361. grb_obj.apertures = {}
  2362. grb_obj.solid_geometry = []
  2363. try:
  2364. grb_obj.options['xmin'] = 0
  2365. grb_obj.options['ymin'] = 0
  2366. grb_obj.options['xmax'] = 0
  2367. grb_obj.options['ymax'] = 0
  2368. except KeyError:
  2369. pass
  2370. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2371. def new_script_object(self):
  2372. """
  2373. Creates a new, blank TCL Script object.
  2374. :return: None
  2375. """
  2376. self.defaults.report_usage("new_script_object()")
  2377. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2378. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2379. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2380. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2381. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2382. # "ListSys, MillDrills,\n" \
  2383. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2384. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2385. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2386. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2387. # "# SubtractRectangle, Version, WriteGCode\n"
  2388. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2389. '# %s:\n' % _('TCL Tutorial is here') + \
  2390. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2391. '# %s:\n' % _("FlatCAM commands list")
  2392. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2393. "(displayed in Tcl Shell).")
  2394. def initialize(obj, app):
  2395. obj.source_file = deepcopy(new_source_file)
  2396. outname = 'new_script'
  2397. self.new_object('script', outname, initialize, plot=False)
  2398. def new_document_object(self):
  2399. """
  2400. Creates a new, blank Document object.
  2401. :return: None
  2402. """
  2403. self.defaults.report_usage("new_document_object()")
  2404. def initialize(obj, app):
  2405. obj.source_file = ""
  2406. self.new_object('document', 'new_document', initialize, plot=False)
  2407. def on_object_created(self, obj, plot, auto_select):
  2408. """
  2409. Event callback for object creation.
  2410. It will add the new object to the collection. After that it will plot the object in a threaded way
  2411. :param obj: The newly created FlatCAM object.
  2412. :param plot: if the newly create object t obe plotted
  2413. :param auto_select: if the newly created object to be autoselected after creation
  2414. :return: None
  2415. """
  2416. t0 = time.time() # DEBUG
  2417. self.log.debug("on_object_created()")
  2418. # The Collection might change the name if there is a collision
  2419. self.collection.append(obj)
  2420. # after adding the object to the collection always update the list of objects that are in the collection
  2421. self.all_objects_list = self.collection.get_list()
  2422. # self.inform.emit('[selected] %s created & selected: %s' %
  2423. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2424. if obj.kind == 'gerber':
  2425. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2426. kind=obj.kind.capitalize(),
  2427. color='green',
  2428. name=str(obj.options['name']), tx=_("created/selected"))
  2429. )
  2430. elif obj.kind == 'excellon':
  2431. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2432. kind=obj.kind.capitalize(),
  2433. color='brown',
  2434. name=str(obj.options['name']), tx=_("created/selected"))
  2435. )
  2436. elif obj.kind == 'cncjob':
  2437. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2438. kind=obj.kind.capitalize(),
  2439. color='blue',
  2440. name=str(obj.options['name']), tx=_("created/selected"))
  2441. )
  2442. elif obj.kind == 'geometry':
  2443. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2444. kind=obj.kind.capitalize(),
  2445. color='red',
  2446. name=str(obj.options['name']), tx=_("created/selected"))
  2447. )
  2448. elif obj.kind == 'script':
  2449. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2450. kind=obj.kind.capitalize(),
  2451. color='orange',
  2452. name=str(obj.options['name']), tx=_("created/selected"))
  2453. )
  2454. elif obj.kind == 'document':
  2455. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2456. kind=obj.kind.capitalize(),
  2457. color='darkCyan',
  2458. name=str(obj.options['name']), tx=_("created/selected"))
  2459. )
  2460. # update the SHELL auto-completer model with the name of the new object
  2461. self.shell._edit.set_model_data(self.myKeywords)
  2462. if auto_select:
  2463. # select the just opened object but deselect the previous ones
  2464. self.collection.set_all_inactive()
  2465. self.collection.set_active(obj.options["name"])
  2466. else:
  2467. self.collection.set_all_inactive()
  2468. # here it is done the object plotting
  2469. def worker_task(t_obj):
  2470. with self.proc_container.new(_("Plotting")):
  2471. if isinstance(t_obj, CNCJobObject):
  2472. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2473. else:
  2474. t_obj.plot()
  2475. t1 = time.time() # DEBUG
  2476. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2477. self.object_plotted.emit(t_obj)
  2478. # Send to worker
  2479. # self.worker.add_task(worker_task, [self])
  2480. if plot is True:
  2481. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2482. def on_object_changed(self, obj):
  2483. """
  2484. Called whenever the geometry of the object was changed in some way.
  2485. This require the update of it's bounding values so it can be the selected on canvas.
  2486. Update the bounding box data from obj.options
  2487. :param obj: the object that was changed
  2488. :return: None
  2489. """
  2490. xmin, ymin, xmax, ymax = obj.bounds()
  2491. obj.options['xmin'] = xmin
  2492. obj.options['ymin'] = ymin
  2493. obj.options['xmax'] = xmax
  2494. obj.options['ymax'] = ymax
  2495. log.debug("Object changed, updating the bounding box data on self.options")
  2496. # delete the old selection shape
  2497. self.delete_selection_shape()
  2498. self.should_we_save = True
  2499. def on_object_plotted(self):
  2500. """
  2501. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2502. :return: None
  2503. """
  2504. self.on_zoom_fit(None)
  2505. def on_about(self):
  2506. """
  2507. Displays the "about" dialog found in the Menu --> Help.
  2508. :return: None
  2509. """
  2510. self.defaults.report_usage("on_about")
  2511. version = self.version
  2512. version_date = self.version_date
  2513. beta = self.beta
  2514. class AboutDialog(QtWidgets.QDialog):
  2515. def __init__(self, app, parent=None):
  2516. QtWidgets.QDialog.__init__(self, parent)
  2517. self.app = app
  2518. # Icon and title
  2519. self.setWindowIcon(parent.app_icon)
  2520. self.setWindowTitle(_("About FlatCAM"))
  2521. self.resize(600, 200)
  2522. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2523. # self.setStyleSheet(
  2524. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2525. # "background-attachment: fixed"
  2526. # )
  2527. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2528. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2529. # palette = QtGui.QPalette()
  2530. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2531. # self.setPalette(palette)
  2532. logo = QtWidgets.QLabel()
  2533. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2534. title = QtWidgets.QLabel(
  2535. "<font size=8><B>FlatCAM</B></font><BR>"
  2536. "{title}<BR>"
  2537. "<BR>"
  2538. "<BR>"
  2539. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2540. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2541. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2542. "<B>{issue}</B></a><BR>".format(
  2543. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2544. devel=_("Development"),
  2545. down=_("DOWNLOAD"),
  2546. issue=_("Issue tracker"))
  2547. )
  2548. title.setOpenExternalLinks(True)
  2549. closebtn = QtWidgets.QPushButton(_("Close"))
  2550. tab_widget = QtWidgets.QTabWidget()
  2551. description_label = QtWidgets.QLabel(
  2552. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2553. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2554. version=version,
  2555. beta=('BETA' if beta else ''),
  2556. date=version_date,
  2557. arch=platform.architecture()[0])
  2558. )
  2559. description_label.setOpenExternalLinks(True)
  2560. lic_lbl_header = QtWidgets.QLabel(
  2561. '%s:<br>%s<br>' % (
  2562. _('Licensed under the MIT license'),
  2563. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2564. "http://www.opensource.org/licenses/mit-license.php</a>"
  2565. )
  2566. )
  2567. lic_lbl_header.setOpenExternalLinks(True)
  2568. lic_lbl_body = QtWidgets.QLabel(
  2569. _(
  2570. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2571. 'of this software and associated documentation files (the "Software"), to deal\n'
  2572. 'in the Software without restriction, including without limitation the rights\n'
  2573. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2574. 'copies of the Software, and to permit persons to whom the Software is\n'
  2575. 'furnished to do so, subject to the following conditions:\n\n'
  2576. 'The above copyright notice and this permission notice shall be included in\n'
  2577. 'all copies or substantial portions of the Software.\n\n'
  2578. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2579. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2580. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2581. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2582. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2583. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2584. 'THE SOFTWARE.'
  2585. )
  2586. )
  2587. attributions_label = QtWidgets.QLabel(
  2588. _(
  2589. 'Some of the icons used are from the following sources:<br>'
  2590. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2591. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2592. 'title="Flaticon">www.flaticon.com</a></div>'
  2593. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2594. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2595. )
  2596. )
  2597. attributions_label.setOpenExternalLinks(True)
  2598. # layouts
  2599. layout1 = QtWidgets.QVBoxLayout()
  2600. layout1_1 = QtWidgets.QHBoxLayout()
  2601. layout1_2 = QtWidgets.QHBoxLayout()
  2602. layout2 = QtWidgets.QHBoxLayout()
  2603. layout3 = QtWidgets.QHBoxLayout()
  2604. self.setLayout(layout1)
  2605. layout1.addLayout(layout1_1)
  2606. layout1.addLayout(layout1_2)
  2607. layout1.addLayout(layout2)
  2608. layout1.addLayout(layout3)
  2609. layout1_1.addStretch()
  2610. layout1_1.addWidget(description_label)
  2611. layout1_2.addWidget(tab_widget)
  2612. self.splash_tab = QtWidgets.QWidget()
  2613. self.splash_tab.setObjectName("splash_about")
  2614. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2615. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2616. tab_widget.addTab(self.splash_tab, _("Splash"))
  2617. self.programmmers_tab = QtWidgets.QWidget()
  2618. self.programmmers_tab.setObjectName("programmers_about")
  2619. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2620. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2621. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2622. self.translators_tab = QtWidgets.QWidget()
  2623. self.translators_tab.setObjectName("translators_about")
  2624. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2625. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2626. tab_widget.addTab(self.translators_tab, _("Translators"))
  2627. self.license_tab = QtWidgets.QWidget()
  2628. self.license_tab.setObjectName("license_about")
  2629. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2630. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2631. tab_widget.addTab(self.license_tab, _("License"))
  2632. self.attributions_tab = QtWidgets.QWidget()
  2633. self.attributions_tab.setObjectName("attributions_about")
  2634. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2635. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2636. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2637. self.splash_tab_layout.addWidget(logo, stretch=0)
  2638. self.splash_tab_layout.addWidget(title, stretch=1)
  2639. pal = QtGui.QPalette()
  2640. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2641. self.prog_grid_lay = QtWidgets.QGridLayout()
  2642. self.prog_grid_lay.setHorizontalSpacing(20)
  2643. self.prog_grid_lay.setColumnStretch(0, 0)
  2644. self.prog_grid_lay.setColumnStretch(2, 1)
  2645. prog_widget = QtWidgets.QWidget()
  2646. prog_widget.setLayout(self.prog_grid_lay)
  2647. prog_scroll = QtWidgets.QScrollArea()
  2648. prog_scroll.setWidget(prog_widget)
  2649. prog_scroll.setWidgetResizable(True)
  2650. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2651. prog_scroll.setPalette(pal)
  2652. self.programmmers_tab_layout.addWidget(prog_scroll)
  2653. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2654. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2655. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2656. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2657. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  2658. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2659. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2660. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2661. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2662. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2663. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2664. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2665. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2700. self.translator_grid_lay = QtWidgets.QGridLayout()
  2701. self.translator_grid_lay.setColumnStretch(0, 0)
  2702. self.translator_grid_lay.setColumnStretch(1, 0)
  2703. self.translator_grid_lay.setColumnStretch(2, 1)
  2704. self.translator_grid_lay.setColumnStretch(3, 0)
  2705. # trans_widget = QtWidgets.QWidget()
  2706. # trans_widget.setLayout(self.translator_grid_lay)
  2707. # self.translators_tab_layout.addWidget(trans_widget)
  2708. # self.translators_tab_layout.addStretch()
  2709. trans_widget = QtWidgets.QWidget()
  2710. trans_widget.setLayout(self.translator_grid_lay)
  2711. trans_scroll = QtWidgets.QScrollArea()
  2712. trans_scroll.setWidget(trans_widget)
  2713. trans_scroll.setWidgetResizable(True)
  2714. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2715. trans_scroll.setPalette(pal)
  2716. self.translators_tab_layout.addWidget(trans_scroll)
  2717. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2718. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2719. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2720. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2721. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2722. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2723. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2724. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2725. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2726. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2727. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2728. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "pcb@golfetto.eu"), 4, 3)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2750. self.translator_grid_lay.setColumnStretch(0, 0)
  2751. self.translators_tab_layout.addStretch()
  2752. self.license_tab_layout.addWidget(lic_lbl_header)
  2753. self.license_tab_layout.addWidget(lic_lbl_body)
  2754. self.license_tab_layout.addStretch()
  2755. self.attributions_tab_layout.addWidget(attributions_label)
  2756. self.attributions_tab_layout.addStretch()
  2757. layout3.addStretch()
  2758. layout3.addWidget(closebtn)
  2759. closebtn.clicked.connect(self.accept)
  2760. AboutDialog(app=self, parent=self.ui).exec_()
  2761. def install_bookmarks(self, book_dict=None):
  2762. """
  2763. Install the bookmarks actions in the Help menu -> Bookmarks
  2764. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2765. :return: None
  2766. """
  2767. if book_dict is None:
  2768. self.defaults["global_bookmarks"].update(
  2769. {
  2770. '1': ['FlatCAM', "http://flatcam.org"],
  2771. '2': ['Backup Site', ""]
  2772. }
  2773. )
  2774. else:
  2775. self.defaults["global_bookmarks"].clear()
  2776. self.defaults["global_bookmarks"].update(book_dict)
  2777. # first try to disconnect if somehow they get connected from elsewhere
  2778. for act in self.ui.menuhelp_bookmarks.actions():
  2779. try:
  2780. act.triggered.disconnect()
  2781. except TypeError:
  2782. pass
  2783. # clear all actions except the last one who is the Bookmark manager
  2784. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2785. pass
  2786. else:
  2787. self.ui.menuhelp_bookmarks.removeAction(act)
  2788. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2789. if self.defaults["global_bookmarks"]:
  2790. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2791. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2792. # the JSON is first making the keys as strings (therefore I have to use strings too
  2793. # or do the conversion :(
  2794. # )
  2795. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2796. # the '10' entry jsut after '1' therefore ordering as strings
  2797. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2798. key=lambda x: int(x[0]))
  2799. for entry, bookmark in sorted_bookmarks:
  2800. title = bookmark[0]
  2801. weblink = bookmark[1]
  2802. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2803. act.setText(title)
  2804. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2805. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2806. if title == 'Backup Site' and weblink == "":
  2807. act.triggered.connect(self.on_backup_site)
  2808. else:
  2809. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2810. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2811. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2812. def on_bookmarks_manager(self):
  2813. """
  2814. Adds the bookmark manager in a Tab in Plot Area
  2815. :return:
  2816. """
  2817. for idx in range(self.ui.plot_tab_area.count()):
  2818. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2819. # there can be only one instance of Bookmark Manager at one time
  2820. return
  2821. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2822. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2823. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2824. # add the tab if it was closed
  2825. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2826. # delete the absolute and relative position and messages in the infobar
  2827. self.ui.position_label.setText("")
  2828. self.ui.rel_position_label.setText("")
  2829. # Switch plot_area to preferences page
  2830. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2831. def on_backup_site(self):
  2832. msgbox = QtWidgets.QMessageBox()
  2833. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2834. "1. FlatCAM.org website is down\n"
  2835. "2. Someone forked FlatCAM project and wants to point\n"
  2836. "to his own website\n\n"
  2837. "If you can't get any informations about FlatCAM beta\n"
  2838. "use the YouTube channel link from the Help menu."))
  2839. msgbox.setWindowTitle(_("Alternative website"))
  2840. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2841. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2842. msgbox.setDefaultButton(bt_yes)
  2843. msgbox.exec_()
  2844. # response = msgbox.clickedButton()
  2845. def on_file_savedefaults(self):
  2846. """
  2847. Callback for menu item File->Save Defaults. Saves application default options
  2848. ``self.defaults`` to current_defaults.FlatConfig.
  2849. :return: None
  2850. """
  2851. self.preferencesUiManager.save_defaults()
  2852. def final_save(self):
  2853. """
  2854. Callback for doing a preferences save to file whenever the application is about to quit.
  2855. If the project has changes, it will ask the user to save the project.
  2856. :return: None
  2857. """
  2858. if self.save_in_progress:
  2859. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2860. return
  2861. if self.should_we_save and self.collection.get_list():
  2862. msgbox = QtWidgets.QMessageBox()
  2863. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2864. "\n"
  2865. "Do you want to Save the project?"))
  2866. msgbox.setWindowTitle(_("Save changes"))
  2867. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2868. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2869. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2870. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2871. msgbox.setDefaultButton(bt_yes)
  2872. msgbox.exec_()
  2873. response = msgbox.clickedButton()
  2874. if response == bt_yes:
  2875. try:
  2876. self.trayIcon.hide()
  2877. except Exception:
  2878. pass
  2879. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2880. elif response == bt_no:
  2881. try:
  2882. self.trayIcon.hide()
  2883. except Exception:
  2884. pass
  2885. self.quit_application()
  2886. elif response == bt_cancel:
  2887. return
  2888. else:
  2889. try:
  2890. self.trayIcon.hide()
  2891. except Exception:
  2892. pass
  2893. self.quit_application()
  2894. def quit_application(self):
  2895. """
  2896. Called (as a pyslot or not) when the application is quit.
  2897. :return: None
  2898. """
  2899. self.preferencesUiManager.save_defaults(silent=True)
  2900. log.debug("App.quit_application() --> App Defaults saved.")
  2901. if self.cmd_line_headless != 1:
  2902. # save app state to file
  2903. stgs = QSettings("Open Source", "FlatCAM")
  2904. stgs.setValue('saved_gui_state', self.ui.saveState())
  2905. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2906. stgs.setValue(
  2907. 'language',
  2908. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2909. )
  2910. stgs.setValue(
  2911. 'notebook_font_size',
  2912. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2913. )
  2914. stgs.setValue(
  2915. 'axis_font_size',
  2916. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2917. )
  2918. stgs.setValue(
  2919. 'textbox_font_size',
  2920. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2921. )
  2922. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2923. stgs.setValue(
  2924. 'machinist',
  2925. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2926. )
  2927. # This will write the setting to the platform specific storage.
  2928. del stgs
  2929. log.debug("App.quit_application() --> App UI state saved.")
  2930. # try to quit the Socket opened by ArgsThread class
  2931. try:
  2932. self.new_launch.thread_exit = True
  2933. self.new_launch.listener.close()
  2934. except Exception as err:
  2935. log.debug("App.quit_application() --> %s" % str(err))
  2936. # try to quit the QThread that run ArgsThread class
  2937. try:
  2938. self.th.terminate()
  2939. except Exception as e:
  2940. log.debug("App.quit_application() --> %s" % str(e))
  2941. # terminate workers
  2942. self.workers.__del__()
  2943. # quit app by signalling for self.kill_app() method
  2944. # self.close_app_signal.emit()
  2945. QtWidgets.qApp.quit()
  2946. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2947. # we use the following command
  2948. minor_v = sys.version_info.minor
  2949. if minor_v < 8:
  2950. sys.exit(0)
  2951. else:
  2952. os._exit(0) # fix to work with Python 3.8
  2953. @staticmethod
  2954. def kill_app():
  2955. # QtCore.QCoreApplication.quit()
  2956. QtWidgets.qApp.quit()
  2957. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2958. # we use the following command
  2959. sys.exit(0)
  2960. def on_portable_checked(self, state):
  2961. """
  2962. Callback called when the checkbox in Preferences GUI is checked.
  2963. It will set the application as portable by creating the preferences and recent files in the
  2964. 'config' folder found in the FlatCAM installation folder.
  2965. :param state: boolean, the state of the checkbox when clicked/checked
  2966. :return:
  2967. """
  2968. line_no = 0
  2969. data = None
  2970. if sys.platform != 'win32':
  2971. # this won't work in Linux or MacOS
  2972. return
  2973. # test if the app was frozen and choose the path for the configuration file
  2974. if getattr(sys, "frozen", False) is True:
  2975. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2976. else:
  2977. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2978. config_file = current_data_path + '\\configuration.txt'
  2979. try:
  2980. with open(config_file, 'r') as f:
  2981. try:
  2982. data = f.readlines()
  2983. except Exception as e:
  2984. log.debug('App.__init__() -->%s' % str(e))
  2985. return
  2986. except FileNotFoundError:
  2987. pass
  2988. for line in data:
  2989. line = line.strip('\n')
  2990. param = str(line).rpartition('=')
  2991. if param[0] == 'portable':
  2992. break
  2993. line_no += 1
  2994. if state:
  2995. data[line_no] = 'portable=True\n'
  2996. # create the new defauults files
  2997. # create current_defaults.FlatConfig file if there is none
  2998. try:
  2999. f = open(current_data_path + '/current_defaults.FlatConfig')
  3000. f.close()
  3001. except IOError:
  3002. App.log.debug('Creating empty current_defaults.FlatConfig')
  3003. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3004. json.dump({}, f)
  3005. f.close()
  3006. # create factory_defaults.FlatConfig file if there is none
  3007. try:
  3008. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3009. f.close()
  3010. except IOError:
  3011. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3012. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3013. json.dump({}, f)
  3014. f.close()
  3015. try:
  3016. f = open(current_data_path + '/recent.json')
  3017. f.close()
  3018. except IOError:
  3019. App.log.debug('Creating empty recent.json')
  3020. f = open(current_data_path + '/recent.json', 'w')
  3021. json.dump([], f)
  3022. f.close()
  3023. try:
  3024. fp = open(current_data_path + '/recent_projects.json')
  3025. fp.close()
  3026. except IOError:
  3027. App.log.debug('Creating empty recent_projects.json')
  3028. fp = open(current_data_path + '/recent_projects.json', 'w')
  3029. json.dump([], fp)
  3030. fp.close()
  3031. # save the current defaults to the new defaults file
  3032. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3033. else:
  3034. data[line_no] = 'portable=False\n'
  3035. with open(config_file, 'w') as f:
  3036. f.writelines(data)
  3037. def on_register_files(self, obj_type=None):
  3038. """
  3039. Called whenever there is a need to register file extensions with FlatCAM.
  3040. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3041. :param obj_type: the type of object to be register for.
  3042. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3043. :return: None
  3044. """
  3045. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3046. new_reg_path = 'Software\\Classes\\'
  3047. # find if the current user is admin
  3048. try:
  3049. is_admin = os.getuid() == 0
  3050. except AttributeError:
  3051. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3052. if is_admin is True:
  3053. root_path = winreg.HKEY_LOCAL_MACHINE
  3054. else:
  3055. root_path = winreg.HKEY_CURRENT_USER
  3056. # create the keys
  3057. def set_reg(name, root_pth, new_reg_path, value):
  3058. try:
  3059. winreg.CreateKey(root_pth, new_reg_path)
  3060. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3061. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3062. return True
  3063. except WindowsError:
  3064. return False
  3065. # delete key in registry
  3066. def delete_reg(root_pth, reg_path, key_to_del):
  3067. key_to_del_path = reg_path + key_to_del
  3068. try:
  3069. winreg.DeleteKey(root_pth, key_to_del_path)
  3070. return True
  3071. except WindowsError:
  3072. return False
  3073. if obj_type is None or obj_type == 'excellon':
  3074. exc_list = \
  3075. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3076. exc_list = [x for x in exc_list if x != '']
  3077. # register all keys in the Preferences window
  3078. for ext in exc_list:
  3079. new_k = new_reg_path + '.%s' % ext
  3080. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3081. # and unregister those that are no longer in the Preferences windows but are in the file
  3082. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3083. if ext not in exc_list:
  3084. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3085. # now write the updated extensions to the self.defaults
  3086. # new_ext = ''
  3087. # for ext in exc_list:
  3088. # new_ext = new_ext + ext + ', '
  3089. # self.defaults["fa_excellon"] = new_ext
  3090. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3091. if obj_type is None or obj_type == 'gcode':
  3092. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3093. gco_list = [x for x in gco_list if x != '']
  3094. # register all keys in the Preferences window
  3095. for ext in gco_list:
  3096. new_k = new_reg_path + '.%s' % ext
  3097. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3098. # and unregister those that are no longer in the Preferences windows but are in the file
  3099. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3100. if ext not in gco_list:
  3101. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3102. # now write the updated extensions to the self.defaults
  3103. # new_ext = ''
  3104. # for ext in gco_list:
  3105. # new_ext = new_ext + ext + ', '
  3106. # self.defaults["fa_gcode"] = new_ext
  3107. self.inform.emit('[success] %s' %
  3108. _("Selected GCode file extensions registered with FlatCAM."))
  3109. if obj_type is None or obj_type == 'gerber':
  3110. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3111. grb_list = [x for x in grb_list if x != '']
  3112. # register all keys in the Preferences window
  3113. for ext in grb_list:
  3114. new_k = new_reg_path + '.%s' % ext
  3115. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3116. # and unregister those that are no longer in the Preferences windows but are in the file
  3117. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3118. if ext not in grb_list:
  3119. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3120. # now write the updated extensions to the self.defaults
  3121. # new_ext = ''
  3122. # for ext in grb_list:
  3123. # new_ext = new_ext + ext + ', '
  3124. # self.defaults["fa_gerber"] = new_ext
  3125. self.inform.emit('[success] %s' %
  3126. _("Selected Gerber file extensions registered with FlatCAM."))
  3127. def add_extension(self, ext_type):
  3128. """
  3129. Add a file extension to the list for a specific object
  3130. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3131. :return:
  3132. """
  3133. if ext_type == 'excellon':
  3134. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3135. if new_ext == '':
  3136. return
  3137. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3138. if new_ext in old_val:
  3139. return
  3140. old_val.append(new_ext)
  3141. old_val.sort()
  3142. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3143. if ext_type == 'gcode':
  3144. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3145. if new_ext == '':
  3146. return
  3147. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3148. if new_ext in old_val:
  3149. return
  3150. old_val.append(new_ext)
  3151. old_val.sort()
  3152. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3153. if ext_type == 'gerber':
  3154. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3155. if new_ext == '':
  3156. return
  3157. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3158. if new_ext in old_val:
  3159. return
  3160. old_val.append(new_ext)
  3161. old_val.sort()
  3162. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3163. if ext_type == 'keyword':
  3164. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3165. if new_kw == '':
  3166. return
  3167. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3168. if new_kw in old_val:
  3169. return
  3170. old_val.append(new_kw)
  3171. old_val.sort()
  3172. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3173. # update the self.myKeywords so the model is updated
  3174. self.autocomplete_kw_list = \
  3175. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3176. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3177. self.shell._edit.set_model_data(self.myKeywords)
  3178. def del_extension(self, ext_type):
  3179. """
  3180. Remove a file extension from the list for a specific object
  3181. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3182. :return:
  3183. """
  3184. if ext_type == 'excellon':
  3185. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3186. if new_ext == '':
  3187. return
  3188. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3189. if new_ext not in old_val:
  3190. return
  3191. old_val.remove(new_ext)
  3192. old_val.sort()
  3193. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3194. if ext_type == 'gcode':
  3195. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3196. if new_ext == '':
  3197. return
  3198. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3199. if new_ext not in old_val:
  3200. return
  3201. old_val.remove(new_ext)
  3202. old_val.sort()
  3203. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3204. if ext_type == 'gerber':
  3205. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3206. if new_ext == '':
  3207. return
  3208. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3209. if new_ext not in old_val:
  3210. return
  3211. old_val.remove(new_ext)
  3212. old_val.sort()
  3213. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3214. if ext_type == 'keyword':
  3215. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3216. if new_kw == '':
  3217. return
  3218. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3219. if new_kw not in old_val:
  3220. return
  3221. old_val.remove(new_kw)
  3222. old_val.sort()
  3223. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3224. # update the self.myKeywords so the model is updated
  3225. self.autocomplete_kw_list = \
  3226. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3227. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3228. self.shell._edit.set_model_data(self.myKeywords)
  3229. def restore_extensions(self, ext_type):
  3230. """
  3231. Restore all file extensions associations with FlatCAM, for a specific object
  3232. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3233. :return:
  3234. """
  3235. if ext_type == 'excellon':
  3236. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3237. # for the ability to open Excellon files with .txt extension
  3238. new_exc_list = deepcopy(self.exc_list)
  3239. try:
  3240. new_exc_list.remove('txt')
  3241. except ValueError:
  3242. pass
  3243. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3244. if ext_type == 'gcode':
  3245. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3246. if ext_type == 'gerber':
  3247. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3248. if ext_type == 'keyword':
  3249. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3250. # update the self.myKeywords so the model is updated
  3251. self.autocomplete_kw_list = self.default_keywords
  3252. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3253. self.shell._edit.set_model_data(self.myKeywords)
  3254. def delete_all_extensions(self, ext_type):
  3255. """
  3256. Delete all file extensions associations with FlatCAM, for a specific object
  3257. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3258. :return:
  3259. """
  3260. if ext_type == 'excellon':
  3261. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3262. if ext_type == 'gcode':
  3263. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3264. if ext_type == 'gerber':
  3265. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3266. if ext_type == 'keyword':
  3267. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3268. # update the self.myKeywords so the model is updated
  3269. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3270. self.shell._edit.set_model_data(self.myKeywords)
  3271. def on_edit_join(self, name=None):
  3272. """
  3273. Callback for Edit->Join. Joins the selected geometry objects into
  3274. a new one.
  3275. :return: None
  3276. """
  3277. self.defaults.report_usage("on_edit_join()")
  3278. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3279. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3280. geo_type_set = set()
  3281. objs = self.collection.get_selected()
  3282. if len(objs) < 2:
  3283. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3284. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3285. return 'fail'
  3286. for obj in objs:
  3287. geo_type_set.add(obj.multigeo)
  3288. # if len(geo_type_list) == 1 means that all list elements are the same
  3289. if len(geo_type_set) != 1:
  3290. self.inform.emit('[ERROR] %s' %
  3291. _("Failed join. The Geometry objects are of different types.\n"
  3292. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3293. "convert from one to another and retry joining \n"
  3294. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3295. "the result may not be what was expected. \n"
  3296. "Check the generated GCODE."))
  3297. return
  3298. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3299. if True in geo_type_set:
  3300. def initialize(geo_obj, app):
  3301. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3302. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3303. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3304. for v in geo_obj.tools.values():
  3305. v['data']['name'] = obj_name_multi
  3306. self.new_object("geometry", obj_name_multi, initialize)
  3307. else:
  3308. def initialize(geo_obj, app):
  3309. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  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_single
  3314. self.new_object("geometry", obj_name_single, initialize)
  3315. self.should_we_save = True
  3316. def on_edit_join_exc(self):
  3317. """
  3318. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3319. a new Excellon.
  3320. :return: None
  3321. """
  3322. self.defaults.report_usage("on_edit_join_exc()")
  3323. objs = self.collection.get_selected()
  3324. for obj in objs:
  3325. if not isinstance(obj, ExcellonObject):
  3326. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3327. return
  3328. if len(objs) < 2:
  3329. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3330. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3331. return 'fail'
  3332. def initialize(exc_obj, app):
  3333. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3334. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3335. self.new_object("excellon", 'Combo_Excellon', initialize)
  3336. self.should_we_save = True
  3337. def on_edit_join_grb(self):
  3338. """
  3339. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3340. a new Gerber object.
  3341. :return: None
  3342. """
  3343. self.defaults.report_usage("on_edit_join_grb()")
  3344. objs = self.collection.get_selected()
  3345. for obj in objs:
  3346. if not isinstance(obj, GerberObject):
  3347. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3348. return
  3349. if len(objs) < 2:
  3350. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3351. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3352. return 'fail'
  3353. def initialize(grb_obj, app):
  3354. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3355. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3356. self.new_object("gerber", 'Combo_Gerber', initialize)
  3357. self.should_we_save = True
  3358. def on_convert_singlegeo_to_multigeo(self):
  3359. """
  3360. Called for converting a Geometry object from single-geo to multi-geo.
  3361. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3362. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3363. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3364. the solid-geometry of that tool.
  3365. :return: None
  3366. """
  3367. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3368. obj = self.collection.get_active()
  3369. if obj is None:
  3370. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3371. return
  3372. if not isinstance(obj, GeometryObject):
  3373. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3374. return
  3375. obj.multigeo = True
  3376. for tooluid, dict_value in obj.tools.items():
  3377. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3378. if not isinstance(obj.solid_geometry, list):
  3379. obj.solid_geometry = [obj.solid_geometry]
  3380. # obj.solid_geometry[:] = []
  3381. obj.plot()
  3382. self.should_we_save = True
  3383. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3384. def on_convert_multigeo_to_singlegeo(self):
  3385. """
  3386. Called for converting a Geometry object from multi-geo to single-geo.
  3387. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3388. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3389. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3390. the solid-geometry of that tool.
  3391. :return: None
  3392. """
  3393. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3394. obj = self.collection.get_active()
  3395. if obj is None:
  3396. self.inform.emit('[ERROR_NOTCL] %s' %
  3397. _("Failed. Select a Geometry Object and try again."))
  3398. return
  3399. if not isinstance(obj, GeometryObject):
  3400. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3401. (_("Expected a GeometryObject, got"), type(obj)))
  3402. return
  3403. obj.multigeo = False
  3404. total_solid_geometry = []
  3405. for tooluid, dict_value in obj.tools.items():
  3406. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3407. # clear the original geometry
  3408. dict_value['solid_geometry'][:] = []
  3409. obj.solid_geometry = deepcopy(total_solid_geometry)
  3410. obj.plot()
  3411. self.should_we_save = True
  3412. self.inform.emit('[success] %s' %
  3413. _("A Geometry object was converted to SingleGeo type."))
  3414. def on_defaults_dict_change(self, field):
  3415. """
  3416. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3417. Edit -> Preferences tab window.
  3418. :param field: the key of the self.defaults dictionary that was changed.
  3419. :return: None
  3420. """
  3421. self.preferencesUiManager.defaults_write_form_field(field=field)
  3422. if field == "units":
  3423. self.set_screen_units(self.defaults['units'])
  3424. def set_screen_units(self, units):
  3425. """
  3426. Set the FlatCAM units on the status bar.
  3427. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3428. :return: None
  3429. """
  3430. self.ui.units_label.setText("[" + units.lower() + "]")
  3431. def on_toggle_units_click(self):
  3432. try:
  3433. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3434. except (TypeError, AttributeError):
  3435. pass
  3436. if self.defaults["units"] == 'MM':
  3437. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3438. else:
  3439. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3440. self.on_toggle_units(no_pref=True)
  3441. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3442. lambda: self.on_toggle_units(no_pref=False))
  3443. def on_toggle_units(self, no_pref=False):
  3444. """
  3445. Callback for the Units radio-button change in the Preferences tab.
  3446. Changes the application's default units adn for the project too.
  3447. If changing the project's units, the change propagates to all of
  3448. the objects in the project.
  3449. :return: None
  3450. """
  3451. self.defaults.report_usage("on_toggle_units")
  3452. if self.toggle_units_ignore:
  3453. return
  3454. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3455. # If option is the same, then ignore
  3456. if new_units == self.defaults["units"].upper():
  3457. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3458. return
  3459. # Options to scale
  3460. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3461. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3462. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3463. "gerber_editor_ma_high",
  3464. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3465. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3466. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3467. "excellon_feedrate_probe", "excellon_milling_dia",
  3468. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3469. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3470. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3471. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3472. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3473. "geometry_extracut_length", "geometry_z_pdepth",
  3474. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3475. 'cncjob_tooldia',
  3476. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3477. "tools_paintnewdia",
  3478. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3479. "tools_nccnewdia", "tools_ncc_offset_value",
  3480. "tools_2sided_drilldia",
  3481. "tools_film_boundary", "tools_film_scale_stroke",
  3482. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3483. "tools_cutout_depthperpass",
  3484. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3485. "tools_panelize_spacing_rows",
  3486. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3487. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3488. "tools_transform_buffer_dis",
  3489. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3490. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3491. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3492. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3493. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3494. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3495. "tools_cr_h2h_val", "tools_cr_dh_val",
  3496. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3497. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3498. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3499. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3500. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3501. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3502. "tools_copper_thieving_mask_clearance",
  3503. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3504. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3505. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3506. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3507. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3508. "tools_invert_margin",
  3509. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3510. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3511. def scale_defaults(sfactor):
  3512. for dim in dimensions:
  3513. if dim == 'gerber_editor_newdim':
  3514. if self.defaults["gerber_editor_newdim"] is None or self.defaults["gerber_editor_newdim"] == '':
  3515. continue
  3516. coordinates = self.defaults["gerber_editor_newdim"].split(",")
  3517. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3518. coords_xy[0] *= sfactor
  3519. coords_xy[1] *= sfactor
  3520. self.defaults['gerber_editor_newdim'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3521. self.decimals, coords_xy[1])
  3522. if dim == 'excellon_toolchangexy':
  3523. if self.defaults["excellon_toolchangexy"] is None or self.defaults["excellon_toolchangexy"] == '':
  3524. continue
  3525. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3526. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3527. coords_xy[0] *= sfactor
  3528. coords_xy[1] *= sfactor
  3529. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3530. self.decimals, coords_xy[1])
  3531. elif dim == 'geometry_toolchangexy':
  3532. if self.defaults["geometry_toolchangexy"] is None or self.defaults["geometry_toolchangexy"] == '':
  3533. continue
  3534. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3535. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3536. coords_xy[0] *= sfactor
  3537. coords_xy[1] *= sfactor
  3538. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3539. self.decimals, coords_xy[1])
  3540. elif dim == 'excellon_endxy':
  3541. if self.defaults["excellon_endxy"] is None or self.defaults["excellon_endxy"] == '':
  3542. continue
  3543. coordinates = self.defaults["excellon_endxy"].split(",")
  3544. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3545. end_coords_xy[0] *= sfactor
  3546. end_coords_xy[1] *= sfactor
  3547. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3548. self.decimals, end_coords_xy[1])
  3549. elif dim == 'geometry_endxy':
  3550. if self.defaults["geometry_endxy"] is None or self.defaults["geometry_endxy"] == '':
  3551. continue
  3552. coordinates = self.defaults["geometry_endxy"].split(",")
  3553. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3554. end_coords_xy[0] *= sfactor
  3555. end_coords_xy[1] *= sfactor
  3556. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3557. self.decimals, end_coords_xy[1])
  3558. elif dim == 'geometry_cnctooldia':
  3559. if self.defaults["geometry_cnctooldia"] is None or self.defaults["geometry_cnctooldia"] == '':
  3560. continue
  3561. if type(self.defaults["geometry_cnctooldia"]) is float:
  3562. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  3563. else:
  3564. try:
  3565. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3566. tools_diameters = [eval(a) for a in tools_string if a != '']
  3567. except Exception as e:
  3568. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3569. continue
  3570. self.defaults['geometry_cnctooldia'] = ''
  3571. for t in range(len(tools_diameters)):
  3572. tools_diameters[t] *= sfactor
  3573. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  3574. elif dim == 'tools_ncctools':
  3575. if self.defaults["tools_ncctools"] is None or self.defaults["tools_ncctools"] == '':
  3576. continue
  3577. if type(self.defaults["tools_ncctools"]) == float:
  3578. ncctools = [self.defaults["tools_ncctools"]]
  3579. else:
  3580. try:
  3581. tools_string = self.defaults["tools_ncctools"].split(",")
  3582. ncctools = [eval(a) for a in tools_string if a != '']
  3583. except Exception as e:
  3584. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3585. continue
  3586. self.defaults['tools_ncctools'] = ''
  3587. for t in range(len(ncctools)):
  3588. ncctools[t] *= sfactor
  3589. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  3590. elif dim == 'tools_solderpaste_tools':
  3591. if self.defaults["tools_solderpaste_tools"] is None or \
  3592. self.defaults["tools_solderpaste_tools"] == '':
  3593. continue
  3594. if type(self.defaults["tools_solderpaste_tools"]) == float:
  3595. sptools = [self.defaults["tools_solderpaste_tools"]]
  3596. else:
  3597. try:
  3598. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3599. sptools = [eval(a) for a in tools_string if a != '']
  3600. except Exception as e:
  3601. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3602. continue
  3603. self.defaults['tools_solderpaste_tools'] = ""
  3604. for t in range(len(sptools)):
  3605. sptools[t] *= sfactor
  3606. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  3607. elif dim == 'tools_solderpaste_xy_toolchange':
  3608. if self.defaults["tools_solderpaste_xy_toolchange"] is None or \
  3609. self.defaults["tools_solderpaste_xy_toolchange"] == '':
  3610. continue
  3611. try:
  3612. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3613. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3614. sp_coords[0] *= sfactor
  3615. sp_coords[1] *= sfactor
  3616. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  3617. self.decimals, sp_coords[1])
  3618. except Exception as e:
  3619. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3620. continue
  3621. elif dim == 'tools_cal_toolchange_xy':
  3622. if self.defaults["tools_cal_toolchange_xy"] is None or \
  3623. self.defaults["tools_cal_toolchange_xy"] == '':
  3624. continue
  3625. coordinates = self.defaults["tools_cal_toolchange_xy"].split(",")
  3626. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3627. end_coords_xy[0] *= sfactor
  3628. end_coords_xy[1] *= sfactor
  3629. self.defaults['tools_cal_toolchange_xy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3630. self.decimals, end_coords_xy[1])
  3631. elif dim == 'global_gridx' or dim == 'global_gridy':
  3632. if new_units == 'IN':
  3633. try:
  3634. val = float(self.defaults[dim]) * sfactor
  3635. except Exception as e:
  3636. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3637. continue
  3638. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3639. else:
  3640. try:
  3641. val = float(self.defaults[dim]) * sfactor
  3642. except Exception as e:
  3643. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3644. continue
  3645. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3646. else:
  3647. if self.defaults[dim]:
  3648. try:
  3649. val = float(self.defaults[dim]) * sfactor
  3650. except Exception as e:
  3651. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3652. continue
  3653. self.defaults[dim] = val
  3654. # The scaling factor depending on choice of units.
  3655. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3656. # Changing project units. Warn user.
  3657. msgbox = QtWidgets.QMessageBox()
  3658. msgbox.setWindowTitle(_("Toggle Units"))
  3659. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3660. msgbox.setText(_("Changing the units of the project\n"
  3661. "will scale all objects.\n\n"
  3662. "Do you want to continue?"))
  3663. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3664. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3665. msgbox.setDefaultButton(bt_ok)
  3666. msgbox.exec_()
  3667. response = msgbox.clickedButton()
  3668. if response == bt_ok:
  3669. if no_pref is False:
  3670. self.preferencesUiManager.defaults_read_form()
  3671. scale_defaults(factor)
  3672. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3673. self.defaults["units"] = new_units
  3674. # update the defaults from form, some may assume that the conversion is enough and it's not
  3675. self.on_options_app2project()
  3676. # update the objects
  3677. for obj in self.collection.get_list():
  3678. obj.convert_units(new_units)
  3679. # make that the properties stored in the object are also updated
  3680. self.object_changed.emit(obj)
  3681. # rebuild the object UI
  3682. obj.build_ui()
  3683. # change this only if the workspace is active
  3684. if self.defaults['global_workspace'] is True:
  3685. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3686. # adjust the grid values on the main toolbar
  3687. val_x = float(self.defaults['global_gridx']) * factor
  3688. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3689. current = self.collection.get_active()
  3690. if current is not None:
  3691. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3692. if not isinstance(current, GeometryObject):
  3693. current.to_form()
  3694. # replot all objects
  3695. self.plot_all()
  3696. # set the status labels to reflect the current FlatCAM units
  3697. self.set_screen_units(new_units)
  3698. # signal to the app that we changed the object properties and it shoud save the project
  3699. self.should_we_save = True
  3700. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3701. else:
  3702. # Undo toggling
  3703. self.toggle_units_ignore = True
  3704. if self.defaults['units'].upper() == 'MM':
  3705. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3706. else:
  3707. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3708. self.toggle_units_ignore = False
  3709. # store the grid values so they are not changed in the next step
  3710. val_x = float(self.defaults['global_gridx'])
  3711. val_y = float(self.defaults['global_gridy'])
  3712. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3713. self.preferencesUiManager.defaults_read_form()
  3714. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3715. # in self.defaults from the GUI elements but
  3716. # I don't want it for the grid values, so I update them here
  3717. self.defaults['global_gridx'] = val_x
  3718. self.defaults['global_gridy'] = val_y
  3719. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3720. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3721. def on_fullscreen(self, disable=False):
  3722. self.defaults.report_usage("on_fullscreen()")
  3723. flags = self.ui.windowFlags()
  3724. if self.toggle_fscreen is False and disable is False:
  3725. # self.ui.showFullScreen()
  3726. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3727. a = self.ui.geometry()
  3728. self.x_pos = a.x()
  3729. self.y_pos = a.y()
  3730. self.width = a.width()
  3731. self.height = a.height()
  3732. # set new geometry to full desktop rect
  3733. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3734. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3735. # everything else will not work without this hack. This happen in Windows.
  3736. # https://bugreports.qt.io/browse/QTBUG-41309
  3737. desktop = QtWidgets.QApplication.desktop()
  3738. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3739. rec = desktop.screenGeometry(screen)
  3740. x = rec.x() - 1
  3741. y = rec.y() - 1
  3742. h = rec.height() + 2
  3743. w = rec.width() + 2
  3744. self.ui.setGeometry(x, y, w, h)
  3745. self.ui.show()
  3746. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3747. tb.setVisible(False)
  3748. self.ui.splitter_left.setVisible(False)
  3749. self.toggle_fscreen = True
  3750. elif self.toggle_fscreen is True or disable is True:
  3751. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3752. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3753. self.ui.showNormal()
  3754. self.restore_toolbar_view()
  3755. self.ui.splitter_left.setVisible(True)
  3756. self.toggle_fscreen = False
  3757. def on_toggle_plotarea(self):
  3758. self.defaults.report_usage("on_toggle_plotarea()")
  3759. try:
  3760. name = self.ui.plot_tab_area.widget(0).objectName()
  3761. except AttributeError:
  3762. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3763. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3764. self.ui.plot_tab_area.protectTab(0)
  3765. return
  3766. if name != 'plotarea_tab':
  3767. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3768. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3769. self.ui.plot_tab_area.protectTab(0)
  3770. else:
  3771. self.ui.plot_tab_area.closeTab(0)
  3772. def on_toggle_notebook(self):
  3773. if self.ui.splitter.sizes()[0] == 0:
  3774. self.ui.splitter.setSizes([1, 1])
  3775. self.ui.menu_toggle_nb.setChecked(True)
  3776. else:
  3777. self.ui.splitter.setSizes([0, 1])
  3778. self.ui.menu_toggle_nb.setChecked(False)
  3779. def on_toggle_axis(self):
  3780. self.defaults.report_usage("on_toggle_axis()")
  3781. if self.toggle_axis is False:
  3782. if self.is_legacy is False:
  3783. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3784. parent=self.plotcanvas.view.scene)
  3785. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3786. parent=self.plotcanvas.view.scene)
  3787. else:
  3788. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3789. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3790. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3791. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3792. self.plotcanvas.canvas.draw()
  3793. self.toggle_axis = True
  3794. else:
  3795. if self.is_legacy is False:
  3796. self.plotcanvas.v_line.parent = None
  3797. self.plotcanvas.h_line.parent = None
  3798. else:
  3799. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3800. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3801. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3802. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3803. self.plotcanvas.canvas.draw()
  3804. self.toggle_axis = False
  3805. def on_toggle_grid(self):
  3806. self.defaults.report_usage("on_toggle_grid()")
  3807. self.ui.grid_snap_btn.trigger()
  3808. self.ui.on_grid_snap_triggered(state=True)
  3809. def on_toggle_grid_lines(self):
  3810. self.defaults.report_usage("on_toggle_grd_lines()")
  3811. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3812. if tt_settings.contains("theme"):
  3813. theme = tt_settings.value('theme', type=str)
  3814. else:
  3815. theme = 'white'
  3816. if self.toggle_grid_lines is False:
  3817. if self.is_legacy is False:
  3818. if theme == 'white':
  3819. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3820. else:
  3821. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3822. else:
  3823. self.plotcanvas.axes.grid(True)
  3824. try:
  3825. self.plotcanvas.canvas.draw()
  3826. except IndexError:
  3827. pass
  3828. pass
  3829. self.toggle_grid_lines = True
  3830. else:
  3831. if self.is_legacy is False:
  3832. if theme == 'white':
  3833. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3834. else:
  3835. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3836. else:
  3837. self.plotcanvas.axes.grid(False)
  3838. try:
  3839. self.plotcanvas.canvas.draw()
  3840. except IndexError:
  3841. pass
  3842. self.toggle_grid_lines = False
  3843. if self.is_legacy is False:
  3844. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3845. # - perhaps is a bug in VisPy implementation
  3846. if self.grid_status() is True:
  3847. self.app_cursor.enabled = False
  3848. self.app_cursor.enabled = True
  3849. else:
  3850. self.app_cursor.enabled = True
  3851. self.app_cursor.enabled = False
  3852. def on_update_exc_export(self, state):
  3853. """
  3854. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3855. if the update_excellon_cb checkbox is checked
  3856. :param state: state of the checkbox whose signals is tied to his slot
  3857. :return:
  3858. """
  3859. if state:
  3860. # first try to disconnect
  3861. try:
  3862. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3863. disconnect(self.on_excellon_format_changed)
  3864. except TypeError:
  3865. pass
  3866. try:
  3867. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3868. disconnect(self.on_excellon_format_changed)
  3869. except TypeError:
  3870. pass
  3871. try:
  3872. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3873. disconnect(self.on_excellon_format_changed)
  3874. except TypeError:
  3875. pass
  3876. try:
  3877. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3878. disconnect(self.on_excellon_format_changed)
  3879. except TypeError:
  3880. pass
  3881. try:
  3882. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3883. disconnect(self.on_excellon_zeros_changed)
  3884. except TypeError:
  3885. pass
  3886. try:
  3887. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3888. disconnect(self.on_excellon_zeros_changed)
  3889. except TypeError:
  3890. pass
  3891. # the connect them
  3892. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3893. self.on_excellon_format_changed)
  3894. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3895. self.on_excellon_format_changed)
  3896. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3897. self.on_excellon_format_changed)
  3898. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3899. self.on_excellon_format_changed)
  3900. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3901. self.on_excellon_zeros_changed)
  3902. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3903. self.on_excellon_units_changed)
  3904. else:
  3905. # disconnect the signals
  3906. try:
  3907. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3908. disconnect(self.on_excellon_format_changed)
  3909. except TypeError:
  3910. pass
  3911. try:
  3912. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3913. disconnect(self.on_excellon_format_changed)
  3914. except TypeError:
  3915. pass
  3916. try:
  3917. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3918. disconnect(self.on_excellon_format_changed)
  3919. except TypeError:
  3920. pass
  3921. try:
  3922. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3923. disconnect(self.on_excellon_format_changed)
  3924. except TypeError:
  3925. pass
  3926. try:
  3927. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3928. disconnect(self.on_excellon_zeros_changed)
  3929. except TypeError:
  3930. pass
  3931. try:
  3932. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3933. disconnect(self.on_excellon_zeros_changed)
  3934. except TypeError:
  3935. pass
  3936. def on_excellon_format_changed(self):
  3937. """
  3938. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3939. :return: None
  3940. """
  3941. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3942. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3943. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3944. )
  3945. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3946. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3947. )
  3948. else:
  3949. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3950. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3951. )
  3952. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3953. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3954. )
  3955. def on_excellon_zeros_changed(self):
  3956. """
  3957. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3958. :return: None
  3959. """
  3960. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3961. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3962. )
  3963. def on_excellon_units_changed(self):
  3964. """
  3965. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3966. :return: None
  3967. """
  3968. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3969. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3970. )
  3971. self.on_excellon_format_changed()
  3972. def on_film_color_entry(self):
  3973. self.defaults['tools_film_color'] = \
  3974. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3975. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3976. "background-color:%s;"
  3977. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3978. )
  3979. def on_film_color_button(self):
  3980. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3981. c_dialog = QtWidgets.QColorDialog()
  3982. film_color = c_dialog.getColor(initial=current_color)
  3983. if film_color.isValid() is False:
  3984. return
  3985. # if new color is different then mark that the Preferences are changed
  3986. if film_color != current_color:
  3987. self.preferencesUiManager.on_preferences_edited()
  3988. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3989. "background-color:%s;"
  3990. "border-color: dimgray" % str(film_color.name())
  3991. )
  3992. new_val_sel = str(film_color.name())
  3993. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3994. self.defaults['tools_film_color'] = new_val_sel
  3995. def on_qrcode_fill_color_entry(self):
  3996. self.defaults['tools_qrcode_fill_color'] = \
  3997. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3998. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3999. "background-color:%s;"
  4000. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  4001. )
  4002. def on_qrcode_fill_color_button(self):
  4003. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  4004. c_dialog = QtWidgets.QColorDialog()
  4005. fill_color = c_dialog.getColor(initial=current_color)
  4006. if fill_color.isValid() is False:
  4007. return
  4008. # if new color is different then mark that the Preferences are changed
  4009. if fill_color != current_color:
  4010. self.preferencesUiManager.on_preferences_edited()
  4011. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4012. "background-color:%s;"
  4013. "border-color: dimgray" % str(fill_color.name())
  4014. )
  4015. new_val_sel = str(fill_color.name())
  4016. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  4017. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  4018. def on_qrcode_back_color_entry(self):
  4019. self.defaults['tools_qrcode_back_color'] = \
  4020. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  4021. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4022. "background-color:%s;"
  4023. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  4024. )
  4025. def on_qrcode_back_color_button(self):
  4026. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  4027. c_dialog = QtWidgets.QColorDialog()
  4028. back_color = c_dialog.getColor(initial=current_color)
  4029. if back_color.isValid() is False:
  4030. return
  4031. # if new color is different then mark that the Preferences are changed
  4032. if back_color != current_color:
  4033. self.preferencesUiManager.on_preferences_edited()
  4034. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4035. "background-color:%s;"
  4036. "border-color: dimgray" % str(back_color.name())
  4037. )
  4038. new_val_sel = str(back_color.name())
  4039. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  4040. self.defaults['tools_qrcode_back_color'] = new_val_sel
  4041. def on_tab_rmb_click(self, checked):
  4042. self.ui.notebook.set_detachable(val=checked)
  4043. self.defaults["global_tabs_detachable"] = checked
  4044. self.ui.plot_tab_area.set_detachable(val=checked)
  4045. self.defaults["global_tabs_detachable"] = checked
  4046. def on_tab_setup_context_menu(self):
  4047. initial_checked = self.defaults["global_tabs_detachable"]
  4048. action_name = str(_("Detachable Tabs"))
  4049. action = QtWidgets.QAction(self)
  4050. action.setCheckable(True)
  4051. action.setText(action_name)
  4052. action.setChecked(initial_checked)
  4053. self.ui.notebook.tabBar.addAction(action)
  4054. self.ui.plot_tab_area.tabBar.addAction(action)
  4055. try:
  4056. action.triggered.disconnect()
  4057. except TypeError:
  4058. pass
  4059. action.triggered.connect(self.on_tab_rmb_click)
  4060. def on_deselect_all(self):
  4061. self.collection.set_all_inactive()
  4062. self.delete_selection_shape()
  4063. def on_workspace_modified(self):
  4064. # self.save_defaults(silent=True)
  4065. if self.is_legacy is True:
  4066. self.plotcanvas.delete_workspace()
  4067. self.preferencesUiManager.defaults_read_form()
  4068. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4069. def on_workspace(self):
  4070. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4071. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4072. else:
  4073. self.plotcanvas.delete_workspace()
  4074. self.preferencesUiManager.defaults_read_form()
  4075. # self.save_defaults(silent=True)
  4076. def on_workspace_toggle(self):
  4077. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4078. try:
  4079. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4080. except TypeError:
  4081. pass
  4082. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4083. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4084. self.on_workspace()
  4085. def on_cursor_type(self, val):
  4086. """
  4087. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4088. :return: None
  4089. """
  4090. self.app_cursor.enabled = False
  4091. if val == 'small':
  4092. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4093. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4094. self.app_cursor = self.plotcanvas.new_cursor()
  4095. else:
  4096. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4097. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4098. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4099. if self.ui.grid_snap_btn.isChecked():
  4100. self.app_cursor.enabled = True
  4101. else:
  4102. self.app_cursor.enabled = False
  4103. def on_tool_add_keypress(self):
  4104. # ## Current application units in Upper Case
  4105. self.units = self.defaults['units'].upper()
  4106. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4107. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4108. if notebook_widget_name == 'selected_tab':
  4109. if self.collection.get_active().kind == 'geometry':
  4110. # Tool add works for Geometry only if Advanced is True in Preferences
  4111. if self.defaults["global_app_level"] == 'a':
  4112. tool_add_popup = FCInputDialog(title="New Tool ...",
  4113. text='Enter a Tool Diameter:',
  4114. min=0.0000, max=99.9999, decimals=4)
  4115. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4116. val, ok = tool_add_popup.get_value()
  4117. if ok:
  4118. if float(val) == 0:
  4119. self.inform.emit('[WARNING_NOTCL] %s' %
  4120. _("Please enter a tool diameter with non-zero value, in Float format."))
  4121. return
  4122. self.collection.get_active().on_tool_add(dia=float(val))
  4123. else:
  4124. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4125. else:
  4126. msgbox = QtWidgets.QMessageBox()
  4127. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4128. "Go to Preferences -> General - Show Advanced Options."))
  4129. msgbox.setWindowTitle("Tool adding ...")
  4130. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4131. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4132. msgbox.setDefaultButton(bt_ok)
  4133. msgbox.exec_()
  4134. # work only if the notebook tab on focus is the Tools_Tab
  4135. if notebook_widget_name == 'tool_tab':
  4136. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4137. # and only if the tool is NCC Tool
  4138. if tool_widget == self.ncclear_tool.toolName:
  4139. self.ncclear_tool.on_add_tool_by_key()
  4140. # and only if the tool is Paint Area Tool
  4141. elif tool_widget == self.paint_tool.toolName:
  4142. self.paint_tool.on_add_tool_by_key()
  4143. # and only if the tool is Solder Paste Dispensing Tool
  4144. elif tool_widget == self.paste_tool.toolName:
  4145. self.paste_tool.on_add_tool_by_key()
  4146. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4147. # See description below.
  4148. def on_delete_keypress(self):
  4149. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4150. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4151. if notebook_widget_name == 'selected_tab':
  4152. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4153. self.collection.get_active().on_tool_delete()
  4154. # work only if the notebook tab on focus is the Tools_Tab
  4155. elif notebook_widget_name == 'tool_tab':
  4156. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4157. # and only if the tool is NCC Tool
  4158. if tool_widget == self.ncclear_tool.toolName:
  4159. self.ncclear_tool.on_tool_delete()
  4160. # and only if the tool is Paint Tool
  4161. elif tool_widget == self.paint_tool.toolName:
  4162. self.paint_tool.on_tool_delete()
  4163. # and only if the tool is Solder Paste Dispensing Tool
  4164. elif tool_widget == self.paste_tool.toolName:
  4165. self.paste_tool.on_tool_delete()
  4166. else:
  4167. self.on_delete()
  4168. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4169. # some screens you have to be careful where you hover with your mouse.
  4170. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4171. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4172. # Complicated, I know :)
  4173. def on_delete(self, force_deletion=False):
  4174. """
  4175. Delete the currently selected FlatCAMObjs.
  4176. :param force_deletion: used by Tcl command
  4177. :return: None
  4178. """
  4179. self.defaults.report_usage("on_delete()")
  4180. response = None
  4181. bt_ok = None
  4182. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4183. # a geometry object before we update it.
  4184. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4185. and self.grb_editor.editor_active is False:
  4186. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4187. msgbox = QtWidgets.QMessageBox()
  4188. msgbox.setWindowTitle(_("Delete objects"))
  4189. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4190. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4191. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4192. "the selected objects?"))
  4193. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4194. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4195. msgbox.setDefaultButton(bt_ok)
  4196. msgbox.exec_()
  4197. response = msgbox.clickedButton()
  4198. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4199. response = bt_ok
  4200. if response == bt_ok:
  4201. if self.collection.get_active():
  4202. self.log.debug("App.on_delete()")
  4203. for obj_active in self.collection.get_selected():
  4204. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4205. if isinstance(obj_active, GerberObject):
  4206. for el in obj_active.mark_shapes:
  4207. obj_active.mark_shapes[el].clear(update=True)
  4208. obj_active.mark_shapes[el].enabled = False
  4209. # obj_active.mark_shapes[el] = None
  4210. del el
  4211. elif isinstance(obj_active, CNCJobObject):
  4212. try:
  4213. obj_active.text_col.enabled = False
  4214. del obj_active.text_col
  4215. obj_active.annotation.clear(update=True)
  4216. del obj_active.annotation
  4217. except AttributeError as e:
  4218. log.debug(
  4219. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4220. )
  4221. while self.collection.get_selected():
  4222. self.delete_first_selected()
  4223. self.inform.emit('%s...' % _("Object(s) deleted"))
  4224. # make sure that the selection shape is deleted, too
  4225. self.delete_selection_shape()
  4226. else:
  4227. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4228. else:
  4229. self.inform.emit(_("Save the work in Editor and try again ..."))
  4230. def delete_first_selected(self):
  4231. # Keep this for later
  4232. try:
  4233. sel_obj = self.collection.get_active()
  4234. name = sel_obj.options["name"]
  4235. isPlotted = sel_obj.options["plot"]
  4236. except AttributeError:
  4237. self.log.debug("Nothing selected for deletion")
  4238. return
  4239. if self.is_legacy is True:
  4240. # Remove plot only if the object was plotted otherwise delaxes will fail
  4241. if isPlotted:
  4242. try:
  4243. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4244. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4245. except Exception as e:
  4246. log.debug("App.delete_first_selected() --> %s" % str(e))
  4247. self.plotcanvas.auto_adjust_axes()
  4248. # Remove from dictionary
  4249. self.collection.delete_active()
  4250. # Clear form
  4251. self.setup_component_editor()
  4252. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4253. def on_set_origin(self):
  4254. """
  4255. Set the origin to the left mouse click position
  4256. :return: None
  4257. """
  4258. # display the message for the user
  4259. # and ask him to click on the desired position
  4260. self.defaults.report_usage("on_set_origin()")
  4261. def origin_replot():
  4262. def worker_task():
  4263. with self.proc_container.new('%s...' % _("Plotting")):
  4264. for obj in self.collection.get_list():
  4265. obj.plot()
  4266. self.plotcanvas.fit_view()
  4267. if self.is_legacy:
  4268. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4269. else:
  4270. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4271. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4272. self.inform.emit(_('Click to set the origin ...'))
  4273. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4274. # first disconnect it as it may have been used by something else
  4275. try:
  4276. self.replot_signal.disconnect()
  4277. except TypeError:
  4278. pass
  4279. self.replot_signal[list].connect(origin_replot)
  4280. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4281. """
  4282. :param event:
  4283. :param location:
  4284. :param noplot:
  4285. :param use_thread:
  4286. :return:
  4287. """
  4288. noplot_sig = noplot
  4289. def worker_task():
  4290. with self.proc_container.new(_("Setting Origin...")):
  4291. obj_list = self.collection.get_list()
  4292. for obj in obj_list:
  4293. obj.offset((x, y))
  4294. self.object_changed.emit(obj)
  4295. # Update the object bounding box options
  4296. a, b, c, d = obj.bounds()
  4297. obj.options['xmin'] = a
  4298. obj.options['ymin'] = b
  4299. obj.options['xmax'] = c
  4300. obj.options['ymax'] = d
  4301. self.inform.emit('[success] %s...' % _('Origin set'))
  4302. for obj in obj_list:
  4303. out_name = obj.options["name"]
  4304. if obj.kind == 'gerber':
  4305. obj.source_file = self.export_gerber(
  4306. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4307. elif obj.kind == 'excellon':
  4308. obj.source_file = self.export_excellon(
  4309. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4310. if noplot_sig is False:
  4311. self.replot_signal.emit([])
  4312. if location is not None:
  4313. if len(location) != 2:
  4314. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4315. return 'fail'
  4316. x, y = location
  4317. if use_thread is True:
  4318. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4319. else:
  4320. worker_task()
  4321. self.should_we_save = True
  4322. return
  4323. if event.button == 1:
  4324. if self.is_legacy is False:
  4325. event_pos = event.pos
  4326. else:
  4327. event_pos = (event.xdata, event.ydata)
  4328. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4329. if self.grid_status():
  4330. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4331. else:
  4332. pos = pos_canvas
  4333. x = 0 - pos[0]
  4334. y = 0 - pos[1]
  4335. if use_thread is True:
  4336. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4337. else:
  4338. worker_task()
  4339. self.should_we_save = True
  4340. def on_move2origin(self, use_thread=True):
  4341. """
  4342. Move selected objects to origin.
  4343. :param use_thread: Control if to use threaded operation. Boolean.
  4344. :return:
  4345. """
  4346. def worker_task():
  4347. with self.proc_container.new(_("Moving to Origin...")):
  4348. obj_list = self.collection.get_selected()
  4349. if not obj_list:
  4350. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4351. return
  4352. xminlist = []
  4353. yminlist = []
  4354. # first get a bounding box to fit all
  4355. for obj in obj_list:
  4356. xmin, ymin, xmax, ymax = obj.bounds()
  4357. xminlist.append(xmin)
  4358. yminlist.append(ymin)
  4359. # get the minimum x,y for all objects selected
  4360. x = min(xminlist)
  4361. y = min(yminlist)
  4362. for obj in obj_list:
  4363. obj.offset((-x, -y))
  4364. self.object_changed.emit(obj)
  4365. # Update the object bounding box options
  4366. a, b, c, d = obj.bounds()
  4367. obj.options['xmin'] = a
  4368. obj.options['ymin'] = b
  4369. obj.options['xmax'] = c
  4370. obj.options['ymax'] = d
  4371. for obj in obj_list:
  4372. obj.plot()
  4373. for obj in obj_list:
  4374. out_name = obj.options["name"]
  4375. if obj.kind == 'gerber':
  4376. obj.source_file = self.export_gerber(
  4377. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4378. elif obj.kind == 'excellon':
  4379. obj.source_file = self.export_excellon(
  4380. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4381. self.inform.emit('[success] %s...' % _('Origin set'))
  4382. if use_thread is True:
  4383. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4384. else:
  4385. worker_task()
  4386. self.should_we_save = True
  4387. def on_jump_to(self, custom_location=None, fit_center=True):
  4388. """
  4389. Jump to a location by setting the mouse cursor location.
  4390. :param custom_location: Jump to a specified point. (x, y) tuple.
  4391. :param fit_center: If to fit view. Boolean.
  4392. :return:
  4393. """
  4394. self.defaults.report_usage("on_jump_to()")
  4395. if not custom_location:
  4396. dia_box_location = None
  4397. try:
  4398. dia_box_location = eval(self.clipboard.text())
  4399. except Exception:
  4400. pass
  4401. if type(dia_box_location) == tuple:
  4402. dia_box_location = str(dia_box_location)
  4403. else:
  4404. dia_box_location = None
  4405. # dia_box = Dialog_box(title=_("Jump to ..."),
  4406. # label=_("Enter the coordinates in format X,Y:"),
  4407. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4408. # initial_text=dia_box_location)
  4409. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4410. label=_("Enter the coordinates in format X,Y:"),
  4411. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4412. initial_text=dia_box_location,
  4413. reference=self.defaults['global_jump_ref'])
  4414. if dia_box.ok is True:
  4415. try:
  4416. location = eval(dia_box.location)
  4417. if not isinstance(location, tuple):
  4418. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4419. return
  4420. if dia_box.reference == 'rel':
  4421. rel_x = self.mouse[0] + location[0]
  4422. rel_y = self.mouse[1] + location[1]
  4423. location = (rel_x, rel_y)
  4424. self.defaults['global_jump_ref'] = dia_box.reference
  4425. except Exception:
  4426. return
  4427. else:
  4428. return
  4429. else:
  4430. location = custom_location
  4431. self.jump_signal.emit(location)
  4432. if fit_center:
  4433. self.plotcanvas.fit_center(loc=location)
  4434. cursor = QtGui.QCursor()
  4435. if self.is_legacy is False:
  4436. # I don't know where those differences come from but they are constant for the current
  4437. # execution of the application and they are multiples of a value around 0.0263mm.
  4438. # In a random way sometimes they are more sometimes they are less
  4439. # if units == 'MM':
  4440. # cal_factor = 0.0263
  4441. # else:
  4442. # cal_factor = 0.0263 / 25.4
  4443. cal_location = (location[0], location[1])
  4444. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4445. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4446. j_pos = (
  4447. int(canvas_origin.x() + round(jump_loc[0])),
  4448. int(canvas_origin.y() + round(jump_loc[1]))
  4449. )
  4450. cursor.setPos(j_pos[0], j_pos[1])
  4451. else:
  4452. # find the canvas origin which is in the top left corner
  4453. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4454. # determine the coordinates for the lowest left point of the canvas
  4455. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4456. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4457. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4458. # canvas) and the point (width, height) is in the top-right location
  4459. loc = self.plotcanvas.axes.transData.transform_point(location)
  4460. j_pos = (
  4461. int(x0 + loc[0]),
  4462. int(y0 - loc[1])
  4463. )
  4464. cursor.setPos(j_pos[0], j_pos[1])
  4465. self.plotcanvas.mouse = [location[0], location[1]]
  4466. if self.defaults["global_cursor_color_enabled"] is True:
  4467. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4468. else:
  4469. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4470. if self.grid_status():
  4471. # Update cursor
  4472. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4473. symbol='++', edge_color=self.cursor_color_3D,
  4474. edge_width=self.defaults["global_cursor_width"],
  4475. size=self.defaults["global_cursor_size"])
  4476. # Set the position label
  4477. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4478. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4479. # Set the relative position label
  4480. dx = location[0] - float(self.rel_point1[0])
  4481. dy = location[1] - float(self.rel_point1[1])
  4482. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4483. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4484. self.inform.emit('[success] %s' % _("Done."))
  4485. return location
  4486. def on_locate(self, obj, fit_center=True):
  4487. """
  4488. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4489. :param obj: The object on which to locate certain points
  4490. :param fit_center: If to fit view. Boolean.
  4491. :return: A point location. (x, y) tuple.
  4492. """
  4493. self.defaults.report_usage("on_locate()")
  4494. if obj is None:
  4495. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4496. return 'fail'
  4497. class DialogBoxChoice(QtWidgets.QDialog):
  4498. def __init__(self, title=None, icon=None, choice='bl'):
  4499. """
  4500. :param title: string with the window title
  4501. """
  4502. super(DialogBoxChoice, self).__init__()
  4503. self.ok = False
  4504. self.setWindowIcon(icon)
  4505. self.setWindowTitle(str(title))
  4506. self.form = QtWidgets.QFormLayout(self)
  4507. self.ref_radio = RadioSet([
  4508. {"label": _("Bottom-Left"), "value": "bl"},
  4509. {"label": _("Top-Left"), "value": "tl"},
  4510. {"label": _("Bottom-Right"), "value": "br"},
  4511. {"label": _("Top-Right"), "value": "tr"},
  4512. {"label": _("Center"), "value": "c"}
  4513. ], orientation='vertical', stretch=False)
  4514. self.ref_radio.set_value(choice)
  4515. self.form.addRow(self.ref_radio)
  4516. self.button_box = QtWidgets.QDialogButtonBox(
  4517. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4518. Qt.Horizontal, parent=self)
  4519. self.form.addRow(self.button_box)
  4520. self.button_box.accepted.connect(self.accept)
  4521. self.button_box.rejected.connect(self.reject)
  4522. if self.exec_() == QtWidgets.QDialog.Accepted:
  4523. self.ok = True
  4524. self.location_point = self.ref_radio.get_value()
  4525. else:
  4526. self.ok = False
  4527. self.location_point = None
  4528. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4529. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4530. choice=self.defaults['global_locate_pt'])
  4531. if dia_box.ok is True:
  4532. try:
  4533. location_point = dia_box.location_point
  4534. self.defaults['global_locate_pt'] = dia_box.location_point
  4535. except Exception:
  4536. return
  4537. else:
  4538. return
  4539. loc_b = obj.bounds()
  4540. if location_point == 'bl':
  4541. location = (loc_b[0], loc_b[1])
  4542. elif location_point == 'tl':
  4543. location = (loc_b[0], loc_b[3])
  4544. elif location_point == 'br':
  4545. location = (loc_b[2], loc_b[1])
  4546. elif location_point == 'tr':
  4547. location = (loc_b[2], loc_b[3])
  4548. else:
  4549. # center
  4550. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4551. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4552. location = (cx, cy)
  4553. self.locate_signal.emit(location, location_point)
  4554. if fit_center:
  4555. self.plotcanvas.fit_center(loc=location)
  4556. cursor = QtGui.QCursor()
  4557. if self.is_legacy is False:
  4558. # I don't know where those differences come from but they are constant for the current
  4559. # execution of the application and they are multiples of a value around 0.0263mm.
  4560. # In a random way sometimes they are more sometimes they are less
  4561. # if units == 'MM':
  4562. # cal_factor = 0.0263
  4563. # else:
  4564. # cal_factor = 0.0263 / 25.4
  4565. cal_location = (location[0], location[1])
  4566. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4567. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4568. j_pos = (
  4569. int(canvas_origin.x() + round(jump_loc[0])),
  4570. int(canvas_origin.y() + round(jump_loc[1]))
  4571. )
  4572. cursor.setPos(j_pos[0], j_pos[1])
  4573. else:
  4574. # find the canvas origin which is in the top left corner
  4575. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4576. # determine the coordinates for the lowest left point of the canvas
  4577. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4578. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4579. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4580. # canvas) and the point (width, height) is in the top-right location
  4581. loc = self.plotcanvas.axes.transData.transform_point(location)
  4582. j_pos = (
  4583. int(x0 + loc[0]),
  4584. int(y0 - loc[1])
  4585. )
  4586. cursor.setPos(j_pos[0], j_pos[1])
  4587. self.plotcanvas.mouse = [location[0], location[1]]
  4588. if self.defaults["global_cursor_color_enabled"] is True:
  4589. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4590. else:
  4591. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4592. if self.grid_status():
  4593. # Update cursor
  4594. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4595. symbol='++', edge_color=self.cursor_color_3D,
  4596. edge_width=self.defaults["global_cursor_width"],
  4597. size=self.defaults["global_cursor_size"])
  4598. # Set the position label
  4599. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4600. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4601. # Set the relative position label
  4602. self.dx = location[0] - float(self.rel_point1[0])
  4603. self.dy = location[1] - float(self.rel_point1[1])
  4604. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4605. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4606. self.inform.emit('[success] %s' % _("Done."))
  4607. return location
  4608. def on_copy_command(self):
  4609. """
  4610. Will copy a selection of objects, creating new objects.
  4611. :return:
  4612. """
  4613. self.defaults.report_usage("on_copy_command()")
  4614. def initialize(obj_init, app):
  4615. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4616. try:
  4617. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4618. except AttributeError:
  4619. pass
  4620. try:
  4621. obj_init.apertures = deepcopy(obj.apertures)
  4622. except AttributeError:
  4623. pass
  4624. try:
  4625. if obj.tools:
  4626. obj_init.tools = deepcopy(obj.tools)
  4627. except Exception as err:
  4628. log.debug("App.on_copy_command() --> %s" % str(err))
  4629. try:
  4630. obj_init.source_file = deepcopy(obj.source_file)
  4631. except (AttributeError, TypeError):
  4632. pass
  4633. def initialize_excellon(obj_init, app):
  4634. obj_init.source_file = deepcopy(obj.source_file)
  4635. obj_init.tools = deepcopy(obj.tools)
  4636. # drills are offset, so they need to be deep copied
  4637. obj_init.drills = deepcopy(obj.drills)
  4638. # slots are offset, so they need to be deep copied
  4639. obj_init.slots = deepcopy(obj.slots)
  4640. obj_init.create_geometry()
  4641. def initialize_script(obj_init, app_obj):
  4642. obj_init.source_file = deepcopy(obj.source_file)
  4643. def initialize_document(obj_init, app_obj):
  4644. obj_init.source_file = deepcopy(obj.source_file)
  4645. for obj in self.collection.get_selected():
  4646. obj_name = obj.options["name"]
  4647. try:
  4648. if isinstance(obj, ExcellonObject):
  4649. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4650. elif isinstance(obj, GerberObject):
  4651. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4652. elif isinstance(obj, GeometryObject):
  4653. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4654. elif isinstance(obj, ScriptObject):
  4655. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4656. elif isinstance(obj, DocumentObject):
  4657. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4658. except Exception as e:
  4659. return "Operation failed: %s" % str(e)
  4660. def on_copy_object2(self, custom_name):
  4661. def initialize_geometry(obj_init, app):
  4662. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4663. try:
  4664. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4665. except AttributeError:
  4666. pass
  4667. try:
  4668. obj_init.apertures = deepcopy(obj.apertures)
  4669. except AttributeError:
  4670. pass
  4671. try:
  4672. if obj.tools:
  4673. obj_init.tools = deepcopy(obj.tools)
  4674. except Exception as ee:
  4675. log.debug("on_copy_object2() --> %s" % str(ee))
  4676. def initialize_gerber(obj_init, app):
  4677. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4678. obj_init.apertures = deepcopy(obj.apertures)
  4679. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4680. def initialize_excellon(obj_init, app):
  4681. obj_init.tools = deepcopy(obj.tools)
  4682. # drills are offset, so they need to be deep copied
  4683. obj_init.drills = deepcopy(obj.drills)
  4684. # slots are offset, so they need to be deep copied
  4685. obj_init.slots = deepcopy(obj.slots)
  4686. obj_init.create_geometry()
  4687. for obj in self.collection.get_selected():
  4688. obj_name = obj.options["name"]
  4689. try:
  4690. if isinstance(obj, ExcellonObject):
  4691. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4692. elif isinstance(obj, GerberObject):
  4693. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4694. elif isinstance(obj, GeometryObject):
  4695. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4696. except Exception as er:
  4697. return "Operation failed: %s" % str(er)
  4698. def on_rename_object(self, text):
  4699. """
  4700. Will rename an object.
  4701. :param text: New name for the object.
  4702. :return:
  4703. """
  4704. self.defaults.report_usage("on_rename_object()")
  4705. named_obj = self.collection.get_active()
  4706. for obj in named_obj:
  4707. if obj is list:
  4708. self.on_rename_object(text)
  4709. else:
  4710. try:
  4711. obj.options['name'] = text
  4712. except Exception as e:
  4713. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4714. def convert_any2geo(self):
  4715. """
  4716. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4717. :return:
  4718. """
  4719. self.defaults.report_usage("convert_any2geo()")
  4720. def initialize(obj_init, app):
  4721. obj_init.solid_geometry = obj.solid_geometry
  4722. try:
  4723. obj_init.follow_geometry = obj.follow_geometry
  4724. except AttributeError:
  4725. pass
  4726. try:
  4727. obj_init.apertures = obj.apertures
  4728. except AttributeError:
  4729. pass
  4730. try:
  4731. if obj.tools:
  4732. obj_init.tools = obj.tools
  4733. except AttributeError:
  4734. pass
  4735. def initialize_excellon(obj_init, app):
  4736. # objs = self.collection.get_selected()
  4737. # GeometryObject.merge(objs, obj)
  4738. solid_geo = []
  4739. for tool in obj.tools:
  4740. for geo in obj.tools[tool]['solid_geometry']:
  4741. solid_geo.append(geo)
  4742. obj_init.solid_geometry = deepcopy(solid_geo)
  4743. if not self.collection.get_selected():
  4744. log.warning("App.convert_any2geo --> No object selected")
  4745. self.inform.emit('[WARNING_NOTCL] %s' %
  4746. _("No object is selected. Select an object and try again."))
  4747. return
  4748. for obj in self.collection.get_selected():
  4749. obj_name = obj.options["name"]
  4750. try:
  4751. if isinstance(obj, ExcellonObject):
  4752. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4753. else:
  4754. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4755. except Exception as e:
  4756. return "Operation failed: %s" % str(e)
  4757. def convert_any2gerber(self):
  4758. """
  4759. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4760. :return:
  4761. """
  4762. self.defaults.report_usage("convert_any2gerber()")
  4763. def initialize_geometry(obj_init, app):
  4764. apertures = {}
  4765. apid = 0
  4766. apertures[str(apid)] = {}
  4767. apertures[str(apid)]['geometry'] = []
  4768. for obj_orig in obj.solid_geometry:
  4769. new_elem = {}
  4770. new_elem['solid'] = obj_orig
  4771. try:
  4772. new_elem['follow'] = obj_orig.exterior
  4773. except AttributeError:
  4774. pass
  4775. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4776. apertures[str(apid)]['size'] = 0.0
  4777. apertures[str(apid)]['type'] = 'C'
  4778. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4779. obj_init.apertures = deepcopy(apertures)
  4780. def initialize_excellon(obj_init, app):
  4781. apertures = {}
  4782. apid = 10
  4783. for tool in obj.tools:
  4784. apertures[str(apid)] = {}
  4785. apertures[str(apid)]['geometry'] = []
  4786. for geo in obj.tools[tool]['solid_geometry']:
  4787. new_el = {}
  4788. new_el['solid'] = geo
  4789. new_el['follow'] = geo.exterior
  4790. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4791. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4792. apertures[str(apid)]['type'] = 'C'
  4793. apid += 1
  4794. # create solid_geometry
  4795. solid_geometry = []
  4796. for apid in apertures:
  4797. for geo_el in apertures[apid]['geometry']:
  4798. solid_geometry.append(geo_el['solid'])
  4799. solid_geometry = MultiPolygon(solid_geometry)
  4800. solid_geometry = solid_geometry.buffer(0.0000001)
  4801. obj_init.solid_geometry = deepcopy(solid_geometry)
  4802. obj_init.apertures = deepcopy(apertures)
  4803. # clear the working objects (perhaps not necessary due of Python GC)
  4804. apertures.clear()
  4805. if not self.collection.get_selected():
  4806. log.warning("App.convert_any2gerber --> No object selected")
  4807. self.inform.emit('[WARNING_NOTCL] %s' %
  4808. _("No object is selected. Select an object and try again."))
  4809. return
  4810. for obj in self.collection.get_selected():
  4811. obj_name = obj.options["name"]
  4812. try:
  4813. if isinstance(obj, ExcellonObject):
  4814. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4815. elif isinstance(obj, GeometryObject):
  4816. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4817. else:
  4818. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4819. except Exception as e:
  4820. return "Operation failed: %s" % str(e)
  4821. def abort_all_tasks(self):
  4822. """
  4823. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4824. on the first possible occasion.
  4825. :return:
  4826. """
  4827. if self.abort_flag is False:
  4828. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4829. self.abort_flag = True
  4830. self.cleanup.emit()
  4831. def app_is_idle(self):
  4832. if self.abort_flag:
  4833. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4834. self.abort_flag = False
  4835. def on_selectall(self):
  4836. """
  4837. Will draw a selection box shape around the selected objects.
  4838. :return:
  4839. """
  4840. self.defaults.report_usage("on_selectall()")
  4841. # delete the possible selection box around a possible selected object
  4842. self.delete_selection_shape()
  4843. for name in self.collection.get_names():
  4844. self.collection.set_active(name)
  4845. curr_sel_obj = self.collection.get_by_name(name)
  4846. # create the selection box around the selected object
  4847. if self.defaults['global_selection_shape'] is True:
  4848. self.draw_selection_shape(curr_sel_obj)
  4849. def on_preferences(self):
  4850. """
  4851. Adds the Preferences in a Tab in Plot Area
  4852. :return:
  4853. """
  4854. # add the tab if it was closed
  4855. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4856. # delete the absolute and relative position and messages in the infobar
  4857. self.ui.position_label.setText("")
  4858. self.ui.rel_position_label.setText("")
  4859. # Switch plot_area to preferences page
  4860. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4861. # self.ui.show()
  4862. # detect changes in the preferences
  4863. for idx in range(self.ui.pref_tab_area.count()):
  4864. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4865. try:
  4866. try:
  4867. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4868. except (TypeError, AttributeError):
  4869. pass
  4870. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4871. except AttributeError:
  4872. pass
  4873. try:
  4874. try:
  4875. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4876. except (TypeError, AttributeError):
  4877. pass
  4878. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4879. except AttributeError:
  4880. pass
  4881. try:
  4882. try:
  4883. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4884. except (TypeError, AttributeError):
  4885. pass
  4886. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4887. except AttributeError:
  4888. pass
  4889. try:
  4890. try:
  4891. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4892. except (TypeError, AttributeError):
  4893. pass
  4894. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4895. except AttributeError:
  4896. pass
  4897. try:
  4898. try:
  4899. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4900. except (TypeError, AttributeError):
  4901. pass
  4902. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4903. except AttributeError:
  4904. pass
  4905. def on_tools_database(self, source='app'):
  4906. """
  4907. Adds the Tools Database in a Tab in Plot Area.
  4908. :return:
  4909. """
  4910. for idx in range(self.ui.plot_tab_area.count()):
  4911. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4912. # there can be only one instance of Tools Database at one time
  4913. return
  4914. if source == 'app':
  4915. self.tools_db_tab = ToolsDB2(
  4916. app=self,
  4917. parent=self.ui,
  4918. callback_on_edited=self.on_tools_db_edited,
  4919. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4920. )
  4921. elif source == 'ncc':
  4922. self.tools_db_tab = ToolsDB2(
  4923. app=self,
  4924. parent=self.ui,
  4925. callback_on_edited=self.on_tools_db_edited,
  4926. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4927. )
  4928. elif source == 'paint':
  4929. self.tools_db_tab = ToolsDB2(
  4930. app=self,
  4931. parent=self.ui,
  4932. callback_on_edited=self.on_tools_db_edited,
  4933. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4934. )
  4935. # add the tab if it was closed
  4936. try:
  4937. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4938. self.tools_db_tab.setObjectName("database_tab")
  4939. except Exception as e:
  4940. log.debug("App.on_tools_database() --> %s" % str(e))
  4941. return
  4942. # delete the absolute and relative position and messages in the infobar
  4943. self.ui.position_label.setText("")
  4944. self.ui.rel_position_label.setText("")
  4945. # Switch plot_area to preferences page
  4946. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4947. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4948. self.tools_db_tab.ui_connect()
  4949. def on_tools_db_edited(self):
  4950. """
  4951. Executed whenever a tool is edited in Tools Database.
  4952. Will color the text of the Tools Database tab to Red color.
  4953. :return:
  4954. """
  4955. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4956. for idx in range(self.ui.plot_tab_area.count()):
  4957. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4958. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4959. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4960. self.tools_db_changed_flag = True
  4961. def on_geometry_tool_add_from_db_executed(self, tool):
  4962. """
  4963. Here add the tool from DB in the selected geometry object.
  4964. :return:
  4965. """
  4966. tool_from_db = deepcopy(tool)
  4967. obj = self.collection.get_active()
  4968. if isinstance(obj, GeometryObject):
  4969. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4970. # close the tab and delete it
  4971. for idx in range(self.ui.plot_tab_area.count()):
  4972. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4973. wdg = self.ui.plot_tab_area.widget(idx)
  4974. wdg.deleteLater()
  4975. self.ui.plot_tab_area.removeTab(idx)
  4976. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4977. else:
  4978. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4979. def on_plot_area_tab_closed(self, tab_obj_name):
  4980. """
  4981. Executed whenever a QTab is closed in the Plot Area.
  4982. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4983. :return:
  4984. """
  4985. if tab_obj_name == "preferences_tab":
  4986. self.preferencesUiManager.on_close_preferences_tab()
  4987. elif tab_obj_name == "database_tab":
  4988. # disconnect the signals from the table widget in tab
  4989. self.tools_db_tab.ui_disconnect()
  4990. if self.tools_db_changed_flag is True:
  4991. msgbox = QtWidgets.QMessageBox()
  4992. msgbox.setText(_("One or more Tools are edited.\n"
  4993. "Do you want to update the Tools Database?"))
  4994. msgbox.setWindowTitle(_("Save Tools Database"))
  4995. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4996. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4997. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4998. msgbox.setDefaultButton(bt_yes)
  4999. msgbox.exec_()
  5000. response = msgbox.clickedButton()
  5001. if response == bt_yes:
  5002. self.tools_db_tab.on_save_tools_db()
  5003. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  5004. else:
  5005. self.tools_db_changed_flag = False
  5006. self.inform.emit('')
  5007. return
  5008. self.tools_db_tab.deleteLater()
  5009. elif tab_obj_name == "text_editor_tab":
  5010. self.toggle_codeeditor = False
  5011. elif tab_obj_name == "bookmarks_tab":
  5012. self.book_dialog_tab.rebuild_actions()
  5013. self.book_dialog_tab.deleteLater()
  5014. else:
  5015. return
  5016. # def on_plotarea_tab_closed(self, tab_idx):
  5017. # """
  5018. #
  5019. # :param tab_idx: Index of the Tab from the plotarea that was closed
  5020. # :return:
  5021. # """
  5022. # widget = self.ui.plot_tab_area.widget(tab_idx)
  5023. #
  5024. # if widget is not None:
  5025. # widget.deleteLater()
  5026. # self.ui.plot_tab_area.removeTab(tab_idx)
  5027. def on_flipy(self):
  5028. """
  5029. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  5030. :return:
  5031. """
  5032. self.defaults.report_usage("on_flipy()")
  5033. obj_list = self.collection.get_selected()
  5034. xminlist = []
  5035. yminlist = []
  5036. xmaxlist = []
  5037. ymaxlist = []
  5038. if not obj_list:
  5039. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  5040. else:
  5041. try:
  5042. # first get a bounding box to fit all
  5043. for obj in obj_list:
  5044. xmin, ymin, xmax, ymax = obj.bounds()
  5045. xminlist.append(xmin)
  5046. yminlist.append(ymin)
  5047. xmaxlist.append(xmax)
  5048. ymaxlist.append(ymax)
  5049. # get the minimum x,y and maximum x,y for all objects selected
  5050. xminimal = min(xminlist)
  5051. yminimal = min(yminlist)
  5052. xmaximal = max(xmaxlist)
  5053. ymaximal = max(ymaxlist)
  5054. px = 0.5 * (xminimal + xmaximal)
  5055. py = 0.5 * (yminimal + ymaximal)
  5056. # execute mirroring
  5057. for obj in obj_list:
  5058. obj.mirror('X', [px, py])
  5059. obj.plot()
  5060. self.object_changed.emit(obj)
  5061. self.inform.emit('[success] %s' %
  5062. _("Flip on Y axis done."))
  5063. except Exception as e:
  5064. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5065. return
  5066. def on_flipx(self):
  5067. """
  5068. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5069. :return:
  5070. """
  5071. self.defaults.report_usage("on_flipx()")
  5072. obj_list = self.collection.get_selected()
  5073. xminlist = []
  5074. yminlist = []
  5075. xmaxlist = []
  5076. ymaxlist = []
  5077. if not obj_list:
  5078. self.inform.emit('[WARNING_NOTCL] %s' %
  5079. _("No object selected to Flip on X axis."))
  5080. else:
  5081. try:
  5082. # first get a bounding box to fit all
  5083. for obj in obj_list:
  5084. xmin, ymin, xmax, ymax = obj.bounds()
  5085. xminlist.append(xmin)
  5086. yminlist.append(ymin)
  5087. xmaxlist.append(xmax)
  5088. ymaxlist.append(ymax)
  5089. # get the minimum x,y and maximum x,y for all objects selected
  5090. xminimal = min(xminlist)
  5091. yminimal = min(yminlist)
  5092. xmaximal = max(xmaxlist)
  5093. ymaximal = max(ymaxlist)
  5094. px = 0.5 * (xminimal + xmaximal)
  5095. py = 0.5 * (yminimal + ymaximal)
  5096. # execute mirroring
  5097. for obj in obj_list:
  5098. obj.mirror('Y', [px, py])
  5099. obj.plot()
  5100. self.object_changed.emit(obj)
  5101. self.inform.emit('[success] %s' %
  5102. _("Flip on X axis done."))
  5103. except Exception as e:
  5104. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5105. return
  5106. def on_rotate(self, silent=False, preset=None):
  5107. """
  5108. Executed when Options -> Rotate Selection menu entry is clicked.
  5109. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5110. :param preset: A value to be used as predefined angle for rotation.
  5111. :return:
  5112. """
  5113. self.defaults.report_usage("on_rotate()")
  5114. obj_list = self.collection.get_selected()
  5115. xminlist = []
  5116. yminlist = []
  5117. xmaxlist = []
  5118. ymaxlist = []
  5119. if not obj_list:
  5120. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5121. else:
  5122. if silent is False:
  5123. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5124. min=-360, max=360, decimals=4,
  5125. init_val=float(self.defaults['tools_transform_rotate']))
  5126. num, ok = rotatebox.get_value()
  5127. else:
  5128. num = preset
  5129. ok = True
  5130. if ok:
  5131. try:
  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. xmaxlist.append(xmax)
  5138. ymaxlist.append(ymax)
  5139. # get the minimum x,y and maximum x,y for all objects selected
  5140. xminimal = min(xminlist)
  5141. yminimal = min(yminlist)
  5142. xmaximal = max(xmaxlist)
  5143. ymaximal = max(ymaxlist)
  5144. px = 0.5 * (xminimal + xmaximal)
  5145. py = 0.5 * (yminimal + ymaximal)
  5146. for sel_obj in obj_list:
  5147. sel_obj.rotate(-float(num), point=(px, py))
  5148. sel_obj.plot()
  5149. self.object_changed.emit(sel_obj)
  5150. self.inform.emit('[success] %s' %
  5151. _("Rotation done."))
  5152. except Exception as e:
  5153. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5154. return
  5155. def on_skewx(self):
  5156. """
  5157. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5158. :return:
  5159. """
  5160. self.defaults.report_usage("on_skewx()")
  5161. obj_list = self.collection.get_selected()
  5162. xminlist = []
  5163. yminlist = []
  5164. if not obj_list:
  5165. self.inform.emit('[WARNING_NOTCL] %s' %
  5166. _("No object selected to Skew/Shear on X axis."))
  5167. else:
  5168. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5169. min=-360, max=360, decimals=4,
  5170. init_val=float(self.defaults['tools_transform_skew_x']))
  5171. num, ok = skewxbox.get_value()
  5172. if ok:
  5173. # first get a bounding box to fit all
  5174. for obj in obj_list:
  5175. xmin, ymin, xmax, ymax = obj.bounds()
  5176. xminlist.append(xmin)
  5177. yminlist.append(ymin)
  5178. # get the minimum x,y and maximum x,y for all objects selected
  5179. xminimal = min(xminlist)
  5180. yminimal = min(yminlist)
  5181. for obj in obj_list:
  5182. obj.skew(num, 0, point=(xminimal, yminimal))
  5183. obj.plot()
  5184. self.object_changed.emit(obj)
  5185. self.inform.emit('[success] %s' %
  5186. _("Skew on X axis done."))
  5187. def on_skewy(self):
  5188. """
  5189. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5190. :return:
  5191. """
  5192. self.defaults.report_usage("on_skewy()")
  5193. obj_list = self.collection.get_selected()
  5194. xminlist = []
  5195. yminlist = []
  5196. if not obj_list:
  5197. self.inform.emit('[WARNING_NOTCL] %s' %
  5198. _("No object selected to Skew/Shear on Y axis."))
  5199. else:
  5200. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5201. min=-360, max=360, decimals=4,
  5202. init_val=float(self.defaults['tools_transform_skew_y']))
  5203. num, ok = skewybox.get_value()
  5204. if ok:
  5205. # first get a bounding box to fit all
  5206. for obj in obj_list:
  5207. xmin, ymin, xmax, ymax = obj.bounds()
  5208. xminlist.append(xmin)
  5209. yminlist.append(ymin)
  5210. # get the minimum x,y and maximum x,y for all objects selected
  5211. xminimal = min(xminlist)
  5212. yminimal = min(yminlist)
  5213. for obj in obj_list:
  5214. obj.skew(0, num, point=(xminimal, yminimal))
  5215. obj.plot()
  5216. self.object_changed.emit(obj)
  5217. self.inform.emit('[success] %s' %
  5218. _("Skew on Y axis done."))
  5219. def on_plots_updated(self):
  5220. """
  5221. Callback used to report when the plots have changed.
  5222. Adjust axes and zooms to fit.
  5223. :return: None
  5224. """
  5225. if self.is_legacy is False:
  5226. self.plotcanvas.update()
  5227. else:
  5228. self.plotcanvas.auto_adjust_axes()
  5229. self.on_zoom_fit(None)
  5230. self.collection.update_view()
  5231. # self.inform.emit(_("Plots updated ..."))
  5232. def on_toolbar_replot(self):
  5233. """
  5234. Callback for toolbar button. Re-plots all objects.
  5235. :return: None
  5236. """
  5237. self.defaults.report_usage("on_toolbar_replot")
  5238. self.log.debug("on_toolbar_replot()")
  5239. try:
  5240. self.collection.get_active().read_form()
  5241. except AttributeError:
  5242. self.log.debug("on_toolbar_replot(): AttributeError")
  5243. pass
  5244. self.plot_all()
  5245. def on_row_activated(self, index):
  5246. if index.isValid():
  5247. if index.internalPointer().parent_item != self.collection.root_item:
  5248. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5249. self.collection.on_item_activated(index)
  5250. def on_row_selected(self, obj_name):
  5251. """
  5252. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5253. It mean we clicked outside of the items and deselected all
  5254. :param obj_name:
  5255. :return:
  5256. """
  5257. if obj_name == 'none':
  5258. for act in self.ui.menuobjects.actions():
  5259. act.setChecked(False)
  5260. return
  5261. # get the name of the selected objects and add them to a list
  5262. name_list = []
  5263. for obj in self.collection.get_selected():
  5264. name_list.append(obj.options['name'])
  5265. # set all actions as unchecked but the ones selected make them checked
  5266. for act in self.ui.menuobjects.actions():
  5267. act.setChecked(False)
  5268. if act.text() in name_list:
  5269. act.setChecked(True)
  5270. def on_collection_updated(self, obj, state, old_name):
  5271. """
  5272. Create a menu from the object loaded in the collection.
  5273. :param obj: object that was changed (added, deleted, renamed)
  5274. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5275. :param old_name: the old name of the object before the action that triggered this slot happened
  5276. :return: None
  5277. """
  5278. icon_files = {
  5279. "gerber": self.resource_location + "/flatcam_icon16.png",
  5280. "excellon": self.resource_location + "/drill16.png",
  5281. "cncjob": self.resource_location + "/cnc16.png",
  5282. "geometry": self.resource_location + "/geometry16.png",
  5283. "script": self.resource_location + "/script_new16.png",
  5284. "document": self.resource_location + "/notes16_1.png"
  5285. }
  5286. if state == 'append':
  5287. for act in self.ui.menuobjects.actions():
  5288. try:
  5289. act.triggered.disconnect()
  5290. except TypeError:
  5291. pass
  5292. self.ui.menuobjects.clear()
  5293. gerber_list = []
  5294. exc_list = []
  5295. cncjob_list = []
  5296. geo_list = []
  5297. script_list = []
  5298. doc_list = []
  5299. for name in self.collection.get_names():
  5300. obj_named = self.collection.get_by_name(name)
  5301. if obj_named.kind == 'gerber':
  5302. gerber_list.append(name)
  5303. elif obj_named.kind == 'excellon':
  5304. exc_list.append(name)
  5305. elif obj_named.kind == 'cncjob':
  5306. cncjob_list.append(name)
  5307. elif obj_named.kind == 'geometry':
  5308. geo_list.append(name)
  5309. elif obj_named.kind == 'script':
  5310. script_list.append(name)
  5311. elif obj_named.kind == 'document':
  5312. doc_list.append(name)
  5313. def add_act(o_name):
  5314. obj_for_icon = self.collection.get_by_name(o_name)
  5315. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5316. add_action.setCheckable(True)
  5317. add_action.setText(o_name)
  5318. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5319. add_action.triggered.connect(
  5320. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5321. self.collection.set_inactive(o_name))
  5322. self.ui.menuobjects.addAction(add_action)
  5323. for name in gerber_list:
  5324. add_act(name)
  5325. self.ui.menuobjects.addSeparator()
  5326. for name in exc_list:
  5327. add_act(name)
  5328. self.ui.menuobjects.addSeparator()
  5329. for name in cncjob_list:
  5330. add_act(name)
  5331. self.ui.menuobjects.addSeparator()
  5332. for name in geo_list:
  5333. add_act(name)
  5334. self.ui.menuobjects.addSeparator()
  5335. for name in script_list:
  5336. add_act(name)
  5337. self.ui.menuobjects.addSeparator()
  5338. for name in doc_list:
  5339. add_act(name)
  5340. self.ui.menuobjects.addSeparator()
  5341. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5342. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5343. _('Select All')
  5344. )
  5345. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5346. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5347. _('Deselect All')
  5348. )
  5349. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5350. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5351. elif state == 'delete':
  5352. for act in self.ui.menuobjects.actions():
  5353. if act.text() == obj.options['name']:
  5354. try:
  5355. act.triggered.disconnect()
  5356. except TypeError:
  5357. pass
  5358. self.ui.menuobjects.removeAction(act)
  5359. break
  5360. elif state == 'rename':
  5361. for act in self.ui.menuobjects.actions():
  5362. if act.text() == old_name:
  5363. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5364. add_action.setText(obj.options['name'])
  5365. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5366. add_action.triggered.connect(
  5367. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5368. self.collection.set_inactive(obj.options['name']))
  5369. self.ui.menuobjects.insertAction(act, add_action)
  5370. try:
  5371. act.triggered.disconnect()
  5372. except TypeError:
  5373. pass
  5374. self.ui.menuobjects.removeAction(act)
  5375. break
  5376. elif state == 'delete_all':
  5377. for act in self.ui.menuobjects.actions():
  5378. try:
  5379. act.triggered.disconnect()
  5380. except TypeError:
  5381. pass
  5382. self.ui.menuobjects.clear()
  5383. self.ui.menuobjects.addSeparator()
  5384. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5385. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5386. _('Select All')
  5387. )
  5388. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5389. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5390. _('Deselect All')
  5391. )
  5392. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5393. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5394. def on_objects_selection(self, on_off):
  5395. obj_list = self.collection.get_names()
  5396. if on_off is True:
  5397. self.collection.set_all_active()
  5398. for act in self.ui.menuobjects.actions():
  5399. try:
  5400. act.setChecked(True)
  5401. except Exception:
  5402. pass
  5403. if obj_list:
  5404. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5405. else:
  5406. self.collection.set_all_inactive()
  5407. for act in self.ui.menuobjects.actions():
  5408. try:
  5409. act.setChecked(False)
  5410. except Exception:
  5411. pass
  5412. if obj_list:
  5413. self.inform.emit('%s' % _("Objects selection is cleared."))
  5414. else:
  5415. self.inform.emit('')
  5416. def grid_status(self):
  5417. if self.ui.grid_snap_btn.isChecked():
  5418. return True
  5419. else:
  5420. return False
  5421. def populate_cmenu_grids(self):
  5422. units = self.defaults['units'].lower()
  5423. # for act in self.ui.cmenu_gridmenu.actions():
  5424. # act.triggered.disconnect()
  5425. self.ui.cmenu_gridmenu.clear()
  5426. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5427. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5428. _("Grid On/Off"))
  5429. grid_toggle.setCheckable(True)
  5430. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5431. self.ui.cmenu_gridmenu.addSeparator()
  5432. for grid in sorted_list:
  5433. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5434. "%s" % str(grid))
  5435. action.triggered.connect(self.set_grid)
  5436. self.ui.cmenu_gridmenu.addSeparator()
  5437. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5438. _("Add"))
  5439. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5440. _("Delete"))
  5441. grid_add.triggered.connect(self.on_grid_add)
  5442. grid_delete.triggered.connect(self.on_grid_delete)
  5443. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5444. def set_grid(self):
  5445. menu_action = self.sender()
  5446. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5447. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5448. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5449. def on_grid_add(self):
  5450. # ## Current application units in lower Case
  5451. units = self.defaults['units'].lower()
  5452. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5453. text=_('Enter a Grid Value:'),
  5454. min=0.0000, max=99.9999, decimals=4)
  5455. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5456. val, ok = grid_add_popup.get_value()
  5457. if ok:
  5458. if float(val) == 0:
  5459. self.inform.emit('[WARNING_NOTCL] %s' %
  5460. _("Please enter a grid value with non-zero value, in Float format."))
  5461. return
  5462. else:
  5463. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5464. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5465. self.inform.emit('[success] %s...' %
  5466. _("New Grid added"))
  5467. else:
  5468. self.inform.emit('[WARNING_NOTCL] %s...' %
  5469. _("Grid already exists"))
  5470. else:
  5471. self.inform.emit('[WARNING_NOTCL] %s...' %
  5472. _("Adding New Grid cancelled"))
  5473. def on_grid_delete(self):
  5474. # ## Current application units in lower Case
  5475. units = self.defaults['units'].lower()
  5476. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5477. text='Enter a Grid Value:',
  5478. min=0.0000, max=99.9999, decimals=4)
  5479. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5480. val, ok = grid_del_popup.get_value()
  5481. if ok:
  5482. if float(val) == 0:
  5483. self.inform.emit('[WARNING_NOTCL] %s' %
  5484. _("Please enter a grid value with non-zero value, in Float format."))
  5485. return
  5486. else:
  5487. try:
  5488. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5489. except ValueError:
  5490. self.inform.emit('[ERROR_NOTCL]%s...' %
  5491. _(" Grid Value does not exist"))
  5492. return
  5493. self.inform.emit('[success] %s...' %
  5494. _("Grid Value deleted"))
  5495. else:
  5496. self.inform.emit('[WARNING_NOTCL] %s...' %
  5497. _("Delete Grid value cancelled"))
  5498. def on_shortcut_list(self):
  5499. self.defaults.report_usage("on_shortcut_list()")
  5500. # add the tab if it was closed
  5501. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5502. # delete the absolute and relative position and messages in the infobar
  5503. self.ui.position_label.setText("")
  5504. self.ui.rel_position_label.setText("")
  5505. # Switch plot_area to preferences page
  5506. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5507. # self.ui.show()
  5508. def on_select_tab(self, name):
  5509. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5510. if self.ui.splitter.sizes()[0] == 0:
  5511. self.ui.splitter.setSizes([1, 1])
  5512. else:
  5513. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5514. self.ui.splitter.setSizes([0, 1])
  5515. if name == 'project':
  5516. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5517. elif name == 'selected':
  5518. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5519. elif name == 'tool':
  5520. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5521. def on_copy_name(self):
  5522. self.defaults.report_usage("on_copy_name()")
  5523. obj = self.collection.get_active()
  5524. try:
  5525. name = obj.options["name"]
  5526. except AttributeError:
  5527. log.debug("on_copy_name() --> No object selected to copy it's name")
  5528. self.inform.emit('[WARNING_NOTCL]%s' %
  5529. _(" No object selected to copy it's name"))
  5530. return
  5531. self.clipboard.setText(name)
  5532. self.inform.emit(_("Name copied on clipboard ..."))
  5533. def on_mouse_click_over_plot(self, event):
  5534. """
  5535. Default actions are:
  5536. :param event: Contains information about the event, like which button
  5537. was clicked, the pixel coordinates and the axes coordinates.
  5538. :return: None
  5539. """
  5540. self.pos = []
  5541. if self.is_legacy is False:
  5542. event_pos = event.pos
  5543. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5544. # # Set the mouse button for panning
  5545. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5546. else:
  5547. event_pos = (event.xdata, event.ydata)
  5548. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5549. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5550. # So it can receive key presses
  5551. self.plotcanvas.native.setFocus()
  5552. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5553. if self.grid_status():
  5554. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5555. else:
  5556. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5557. try:
  5558. if event.button == 1:
  5559. # Reset here the relative coordinates so there is a new reference on the click position
  5560. if self.rel_point1 is None:
  5561. self.rel_point1 = self.pos
  5562. else:
  5563. self.rel_point2 = copy(self.rel_point1)
  5564. self.rel_point1 = self.pos
  5565. self.on_mouse_move_over_plot(event, origin_click=True)
  5566. except Exception as e:
  5567. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5568. def on_mouse_double_click_over_plot(self, event):
  5569. if event.button == 1:
  5570. self.doubleclick = True
  5571. def on_mouse_move_over_plot(self, event, origin_click=None):
  5572. """
  5573. Callback for the mouse motion event over the plot.
  5574. :param event: Contains information about the event.
  5575. :param origin_click
  5576. :return: None
  5577. """
  5578. if self.is_legacy is False:
  5579. event_pos = event.pos
  5580. if self.defaults["global_pan_button"] == '2':
  5581. pan_button = 2
  5582. else:
  5583. pan_button = 3
  5584. self.event_is_dragging = event.is_dragging
  5585. else:
  5586. event_pos = (event.xdata, event.ydata)
  5587. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5588. if self.defaults["global_pan_button"] == '2':
  5589. pan_button = 3
  5590. else:
  5591. pan_button = 2
  5592. self.event_is_dragging = self.plotcanvas.is_dragging
  5593. # So it can receive key presses but not when the Tcl Shell is active
  5594. if not self.ui.shell_dock.isVisible():
  5595. if not self.plotcanvas.native.hasFocus():
  5596. self.plotcanvas.native.setFocus()
  5597. self.pos_jump = event_pos
  5598. self.ui.popMenu.mouse_is_panning = False
  5599. if origin_click is None:
  5600. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5601. if event.button == pan_button and self.event_is_dragging == 1:
  5602. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5603. if self.ui.popMenu.popup_active:
  5604. self.ui.popMenu.popup_active = False
  5605. return
  5606. self.ui.popMenu.mouse_is_panning = True
  5607. return
  5608. if self.rel_point1 is not None:
  5609. try: # May fail in case mouse not within axes
  5610. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5611. if self.grid_status():
  5612. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5613. # Update cursor
  5614. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5615. symbol='++', edge_color=self.cursor_color_3D,
  5616. edge_width=self.defaults["global_cursor_width"],
  5617. size=self.defaults["global_cursor_size"])
  5618. else:
  5619. pos = (pos_canvas[0], pos_canvas[1])
  5620. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5621. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5622. self.dx = pos[0] - float(self.rel_point1[0])
  5623. self.dy = pos[1] - float(self.rel_point1[1])
  5624. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5625. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5626. self.mouse = [pos[0], pos[1]]
  5627. # if the mouse is moved and the LMB is clicked then the action is a selection
  5628. if self.event_is_dragging == 1 and event.button == 1:
  5629. self.delete_selection_shape()
  5630. if self.dx < 0:
  5631. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5632. face_color=self.defaults['global_alt_sel_fill'])
  5633. self.selection_type = False
  5634. elif self.dx >= 0:
  5635. self.draw_moving_selection_shape(self.pos, pos)
  5636. self.selection_type = True
  5637. else:
  5638. self.selection_type = None
  5639. else:
  5640. self.selection_type = None
  5641. # hover effect - enabled in Preferences -> General -> GUI Settings
  5642. if self.defaults['global_hover']:
  5643. for obj in self.collection.get_list():
  5644. try:
  5645. # select the object(s) only if it is enabled (plotted)
  5646. if obj.options['plot']:
  5647. if obj not in self.collection.get_selected():
  5648. poly_obj = Polygon(
  5649. [(obj.options['xmin'], obj.options['ymin']),
  5650. (obj.options['xmax'], obj.options['ymin']),
  5651. (obj.options['xmax'], obj.options['ymax']),
  5652. (obj.options['xmin'], obj.options['ymax'])]
  5653. )
  5654. if Point(pos).within(poly_obj):
  5655. if obj.isHovering is False:
  5656. obj.isHovering = True
  5657. obj.notHovering = True
  5658. # create the selection box around the selected object
  5659. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5660. else:
  5661. if obj.notHovering is True:
  5662. obj.notHovering = False
  5663. obj.isHovering = False
  5664. self.delete_hover_shape()
  5665. except Exception:
  5666. # the Exception here will happen if we try to select on screen and we have an
  5667. # newly (and empty) just created Geometry or Excellon object that do not have the
  5668. # xmin, xmax, ymin, ymax options.
  5669. # In this case poly_obj creation (see above) will fail
  5670. pass
  5671. except Exception:
  5672. self.ui.position_label.setText("")
  5673. self.ui.rel_position_label.setText("")
  5674. self.mouse = None
  5675. def on_mouse_click_release_over_plot(self, event):
  5676. """
  5677. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5678. and has been registered in ''self.__init__()''.
  5679. :param event: contains information about the event.
  5680. :return:
  5681. """
  5682. if self.is_legacy is False:
  5683. event_pos = event.pos
  5684. right_button = 2
  5685. else:
  5686. event_pos = (event.xdata, event.ydata)
  5687. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5688. right_button = 3
  5689. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5690. if self.grid_status():
  5691. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5692. else:
  5693. pos = (pos_canvas[0], pos_canvas[1])
  5694. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5695. # canvas menu
  5696. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5697. self.ui.popMenu.mouse_is_panning = False
  5698. self.cursor = QtGui.QCursor()
  5699. self.populate_cmenu_grids()
  5700. self.ui.popMenu.popup(self.cursor.pos())
  5701. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5702. # selection and then select a type of selection ("enclosing" or "touching")
  5703. if event.button == 1: # left click
  5704. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5705. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5706. if modifiers == QtCore.Qt.ShiftModifier:
  5707. # do not auto open the Project Tab
  5708. self.click_noproject = True
  5709. self.clipboard.setText(
  5710. self.defaults["global_point_clipboard_format"] %
  5711. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5712. )
  5713. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5714. return
  5715. if self.doubleclick is True:
  5716. self.doubleclick = False
  5717. if self.collection.get_selected():
  5718. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5719. if self.ui.splitter.sizes()[0] == 0:
  5720. self.ui.splitter.setSizes([1, 1])
  5721. try:
  5722. # delete the selection shape(S) as it may be in the way
  5723. self.delete_selection_shape()
  5724. self.delete_hover_shape()
  5725. except Exception as e:
  5726. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5727. return
  5728. else:
  5729. # WORKAROUND for LEGACY MODE
  5730. if self.is_legacy is True:
  5731. # if there is no move on canvas then we have no dragging selection
  5732. if self.dx == 0 or self.dy == 0:
  5733. self.selection_type = None
  5734. if self.selection_type is not None:
  5735. try:
  5736. self.selection_area_handler(self.pos, pos, self.selection_type)
  5737. self.selection_type = None
  5738. except Exception as e:
  5739. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5740. return
  5741. else:
  5742. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5743. if key_modifier == QtCore.Qt.ShiftModifier:
  5744. mod_key = 'Shift'
  5745. elif key_modifier == QtCore.Qt.ControlModifier:
  5746. mod_key = 'Control'
  5747. else:
  5748. mod_key = None
  5749. try:
  5750. if self.command_active is None:
  5751. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5752. # deselect, and if it's not selected then it will be selected
  5753. # If there is no active command (self.command_active is None) then we check if we clicked
  5754. # on a object by checking the bounding limits against mouse click position
  5755. if mod_key == self.defaults["global_mselect_key"]:
  5756. self.select_objects(key='multisel')
  5757. else:
  5758. # If there is no active command (self.command_active is None) then we check if
  5759. # we clicked on a object by checking the bounding limits against mouse click position
  5760. self.select_objects()
  5761. self.delete_hover_shape()
  5762. except Exception as e:
  5763. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5764. return
  5765. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5766. """
  5767. :param start_pos: mouse position when the selection LMB click was done
  5768. :param end_pos: mouse position when the left mouse button is released
  5769. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5770. :return:
  5771. """
  5772. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5773. # delete previous selection shape
  5774. self.delete_selection_shape()
  5775. # make all objects inactive
  5776. self.collection.set_all_inactive()
  5777. for obj in self.collection.get_list():
  5778. try:
  5779. # select the object(s) only if it is enabled (plotted)
  5780. if obj.options['plot']:
  5781. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5782. (obj.options['xmax'], obj.options['ymin']),
  5783. (obj.options['xmax'], obj.options['ymax']),
  5784. (obj.options['xmin'], obj.options['ymax'])])
  5785. if sel_type is True:
  5786. if poly_obj.within(poly_selection):
  5787. # create the selection box around the selected object
  5788. if self.defaults['global_selection_shape'] is True:
  5789. self.draw_selection_shape(obj)
  5790. self.collection.set_active(obj.options['name'])
  5791. else:
  5792. if poly_selection.intersects(poly_obj):
  5793. # create the selection box around the selected object
  5794. if self.defaults['global_selection_shape'] is True:
  5795. self.draw_selection_shape(obj)
  5796. self.collection.set_active(obj.options['name'])
  5797. obj.selection_shape_drawn = True
  5798. except Exception as e:
  5799. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5800. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5801. # In this case poly_obj creation (see above) will fail
  5802. log.debug("App.selection_area_handler() --> %s" % str(e))
  5803. def select_objects(self, key=None):
  5804. """
  5805. Will select objects clicked on canvas
  5806. :param key: for future use in cumulative selection
  5807. :return:
  5808. """
  5809. # list where we store the overlapped objects under our mouse left click position
  5810. if key is None:
  5811. self.objects_under_the_click_list = []
  5812. # Populate the list with the overlapped objects on the click position
  5813. curr_x, curr_y = self.pos
  5814. for obj in self.all_objects_list:
  5815. # ScriptObject and DocumentObject objects can't be selected
  5816. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5817. continue
  5818. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5819. continue
  5820. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5821. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5822. if obj.options['name'] not in self.objects_under_the_click_list:
  5823. if obj.options['plot']:
  5824. # add objects to the objects_under_the_click list only if the object is plotted
  5825. # (active and not disabled)
  5826. self.objects_under_the_click_list.append(obj.options['name'])
  5827. try:
  5828. if self.objects_under_the_click_list:
  5829. curr_sel_obj = self.collection.get_active()
  5830. # case when there is only an object under the click and we toggle it
  5831. if len(self.objects_under_the_click_list) == 1:
  5832. if curr_sel_obj is None:
  5833. self.collection.set_active(self.objects_under_the_click_list[0])
  5834. curr_sel_obj = self.collection.get_active()
  5835. # create the selection box around the selected object
  5836. if self.defaults['global_selection_shape'] is True:
  5837. self.draw_selection_shape(curr_sel_obj)
  5838. curr_sel_obj.selection_shape_drawn = True
  5839. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5840. self.on_objects_selection(False)
  5841. self.delete_selection_shape()
  5842. curr_sel_obj.selection_shape_drawn = False
  5843. self.collection.set_active(self.objects_under_the_click_list[0])
  5844. curr_sel_obj = self.collection.get_active()
  5845. # create the selection box around the selected object
  5846. if self.defaults['global_selection_shape'] is True:
  5847. self.draw_selection_shape(curr_sel_obj)
  5848. curr_sel_obj.selection_shape_drawn = True
  5849. self.selected_message(curr_sel_obj=curr_sel_obj)
  5850. elif curr_sel_obj.selection_shape_drawn is False:
  5851. if self.defaults['global_selection_shape'] is True:
  5852. self.draw_selection_shape(curr_sel_obj)
  5853. curr_sel_obj.selection_shape_drawn = True
  5854. else:
  5855. self.on_objects_selection(False)
  5856. self.delete_selection_shape()
  5857. if self.call_source != 'app':
  5858. self.call_source = 'app'
  5859. self.selected_message(curr_sel_obj=curr_sel_obj)
  5860. else:
  5861. # If there is no selected object
  5862. # make active the first element of the overlapped objects list
  5863. if self.collection.get_active() is None:
  5864. self.collection.set_active(self.objects_under_the_click_list[0])
  5865. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5866. name_sel_obj = self.collection.get_active().options['name']
  5867. # In case that there is a selected object but it is not in the overlapped object list
  5868. # make that object inactive and activate the first element in the overlapped object list
  5869. if name_sel_obj not in self.objects_under_the_click_list:
  5870. self.collection.set_inactive(name_sel_obj)
  5871. name_sel_obj = self.objects_under_the_click_list[0]
  5872. self.collection.set_active(name_sel_obj)
  5873. else:
  5874. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5875. self.collection.set_all_inactive()
  5876. self.collection.set_active(
  5877. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5878. curr_sel_obj = self.collection.get_active()
  5879. # delete the possible selection box around a possible selected object
  5880. self.delete_selection_shape()
  5881. curr_sel_obj.selection_shape_drawn = False
  5882. # create the selection box around the selected object
  5883. if self.defaults['global_selection_shape'] is True:
  5884. self.draw_selection_shape(curr_sel_obj)
  5885. curr_sel_obj.selection_shape_drawn = True
  5886. self.selected_message(curr_sel_obj=curr_sel_obj)
  5887. else:
  5888. # deselect everything
  5889. self.on_objects_selection(False)
  5890. # delete the possible selection box around a possible selected object
  5891. self.delete_selection_shape()
  5892. for o in self.collection.get_list():
  5893. o.selection_shape_drawn = False
  5894. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5895. # only when working on App
  5896. if self.call_source == 'app':
  5897. if self.click_noproject is False:
  5898. # if the Tool Tab is in focus don't change focus to Project Tab
  5899. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5900. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5901. else:
  5902. # restore auto open the Project Tab
  5903. self.click_noproject = False
  5904. # delete any text in the status bar, implicitly the last object name that was selected
  5905. # self.inform.emit("")
  5906. else:
  5907. self.call_source = 'app'
  5908. except Exception as e:
  5909. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5910. def selected_message(self, curr_sel_obj):
  5911. if curr_sel_obj:
  5912. if curr_sel_obj.kind == 'gerber':
  5913. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5914. color='green',
  5915. name=str(curr_sel_obj.options['name']),
  5916. tx=_("selected"))
  5917. )
  5918. elif curr_sel_obj.kind == 'excellon':
  5919. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5920. color='brown',
  5921. name=str(curr_sel_obj.options['name']),
  5922. tx=_("selected"))
  5923. )
  5924. elif curr_sel_obj.kind == 'cncjob':
  5925. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5926. color='blue',
  5927. name=str(curr_sel_obj.options['name']),
  5928. tx=_("selected"))
  5929. )
  5930. elif curr_sel_obj.kind == 'geometry':
  5931. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5932. color='red',
  5933. name=str(curr_sel_obj.options['name']),
  5934. tx=_("selected"))
  5935. )
  5936. def delete_hover_shape(self):
  5937. self.hover_shapes.clear()
  5938. self.hover_shapes.redraw()
  5939. def draw_hover_shape(self, sel_obj, color=None):
  5940. """
  5941. :param sel_obj: The object for which the hover shape must be drawn
  5942. :param color: The color of the hover shape
  5943. :return: None
  5944. """
  5945. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5946. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5947. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5948. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5949. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5950. if self.defaults['units'].upper() == 'MM':
  5951. hover_rect = hover_rect.buffer(-0.1)
  5952. hover_rect = hover_rect.buffer(0.2)
  5953. else:
  5954. hover_rect = hover_rect.buffer(-0.00393)
  5955. hover_rect = hover_rect.buffer(0.00787)
  5956. # if color:
  5957. # face = Color(color)
  5958. # face.alpha = 0.2
  5959. # outline = Color(color, alpha=0.8)
  5960. # else:
  5961. # face = Color(self.defaults['global_sel_fill'])
  5962. # face.alpha = 0.2
  5963. # outline = self.defaults['global_sel_line']
  5964. if color:
  5965. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5966. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5967. else:
  5968. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5969. outline = self.defaults['global_sel_line']
  5970. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5971. if self.is_legacy is True:
  5972. self.hover_shapes.redraw()
  5973. def delete_selection_shape(self):
  5974. self.move_tool.sel_shapes.clear()
  5975. self.move_tool.sel_shapes.redraw()
  5976. def draw_selection_shape(self, sel_obj, color=None):
  5977. """
  5978. Will draw a selection shape around the selected object.
  5979. :param sel_obj: The object for which the selection shape must be drawn
  5980. :param color: The color for the selection shape.
  5981. :return: None
  5982. """
  5983. if sel_obj is None:
  5984. return
  5985. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5986. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5987. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5988. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5989. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5990. if self.defaults['units'].upper() == 'MM':
  5991. sel_rect = sel_rect.buffer(-0.1)
  5992. sel_rect = sel_rect.buffer(0.2)
  5993. else:
  5994. sel_rect = sel_rect.buffer(-0.00393)
  5995. sel_rect = sel_rect.buffer(0.00787)
  5996. if color:
  5997. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5998. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5999. else:
  6000. if self.is_legacy is False:
  6001. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6002. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  6003. else:
  6004. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  6005. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  6006. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6007. color=outline,
  6008. face_color=face,
  6009. update=True,
  6010. layer=0,
  6011. tolerance=None))
  6012. if self.is_legacy is True:
  6013. self.move_tool.sel_shapes.redraw()
  6014. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6015. """
  6016. Will draw a selection shape when dragging mouse on canvas.
  6017. :param old_coords: Old coordinates
  6018. :param coords: New coordinates
  6019. :param kwargs: Keyword arguments
  6020. :return:
  6021. """
  6022. if 'color' in kwargs:
  6023. color = kwargs['color']
  6024. else:
  6025. color = self.defaults['global_sel_line']
  6026. if 'face_color' in kwargs:
  6027. face_color = kwargs['face_color']
  6028. else:
  6029. face_color = self.defaults['global_sel_fill']
  6030. if 'face_alpha' in kwargs:
  6031. face_alpha = kwargs['face_alpha']
  6032. else:
  6033. face_alpha = 0.3
  6034. x0, y0 = old_coords
  6035. x1, y1 = coords
  6036. pt1 = (x0, y0)
  6037. pt2 = (x1, y0)
  6038. pt3 = (x1, y1)
  6039. pt4 = (x0, y1)
  6040. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6041. # color_t = Color(face_color)
  6042. # color_t.alpha = face_alpha
  6043. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  6044. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6045. layer=0, tolerance=None)
  6046. if self.is_legacy is True:
  6047. self.move_tool.sel_shapes.redraw()
  6048. def on_file_new_click(self):
  6049. """
  6050. Callback for menu item File -> New.
  6051. Executed on clicking the Menu -> File -> New Project
  6052. :return:
  6053. """
  6054. if self.collection.get_list() and self.should_we_save:
  6055. msgbox = QtWidgets.QMessageBox()
  6056. # msgbox.setText("<B>Save changes ...</B>")
  6057. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6058. "Creating a New project will delete them.\n"
  6059. "Do you want to Save the project?"))
  6060. msgbox.setWindowTitle(_("Save changes"))
  6061. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6062. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6063. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6064. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6065. msgbox.setDefaultButton(bt_yes)
  6066. msgbox.exec_()
  6067. response = msgbox.clickedButton()
  6068. if response == bt_yes:
  6069. self.on_file_saveprojectas()
  6070. elif response == bt_cancel:
  6071. return
  6072. elif response == bt_no:
  6073. self.on_file_new()
  6074. else:
  6075. self.on_file_new()
  6076. self.inform.emit('[success] %s...' % _("New Project created"))
  6077. def on_file_new(self, cli=None):
  6078. """
  6079. Returns the application to its startup state. This method is thread-safe.
  6080. :param cli: Boolean. If True this method was run from command line
  6081. :return: None
  6082. """
  6083. self.defaults.report_usage("on_file_new")
  6084. # Remove everything from memory
  6085. App.log.debug("on_file_new()")
  6086. # close any editor that might be open
  6087. if self.call_source != 'app':
  6088. self.editor2object(cleanup=True)
  6089. # ## EDITOR section
  6090. self.geo_editor = FlatCAMGeoEditor(self)
  6091. self.exc_editor = FlatCAMExcEditor(self)
  6092. self.grb_editor = FlatCAMGrbEditor(self)
  6093. # Clear pool
  6094. self.clear_pool()
  6095. for obj in self.collection.get_list():
  6096. # delete shapes left drawn from mark shape_collections, if any
  6097. if isinstance(obj, GerberObject):
  6098. try:
  6099. for el in obj.mark_shapes:
  6100. obj.mark_shapes[el].clear(update=True)
  6101. obj.mark_shapes[el].enabled = False
  6102. del el
  6103. except AttributeError:
  6104. pass
  6105. # also delete annotation shapes, if any
  6106. elif isinstance(obj, CNCJobObject):
  6107. try:
  6108. obj.text_col.enabled = False
  6109. del obj.text_col
  6110. obj.annotation.clear(update=True)
  6111. del obj.annotation
  6112. except AttributeError:
  6113. pass
  6114. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6115. self.shell.init_tcl()
  6116. # delete any selection shape on canvas
  6117. self.delete_selection_shape()
  6118. # delete all FlatCAM objects
  6119. self.collection.delete_all()
  6120. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  6121. self.setup_component_editor()
  6122. # Clear project filename
  6123. self.project_filename = None
  6124. # Load the application defaults
  6125. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6126. # Re-fresh project options
  6127. self.on_options_app2project()
  6128. # Init FlatCAMTools
  6129. self.init_tools()
  6130. # Try to close all tabs in the PlotArea but only if the GUI is active (CLI is None)
  6131. if cli is None:
  6132. # we need to go in reverse because once we remove a tab then the index changes
  6133. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  6134. # and so on. Therefore the deletion should be done in reverse
  6135. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  6136. for index in range(wdg_count, -1, -1):
  6137. try:
  6138. self.ui.plot_tab_area.closeTab(index)
  6139. except Exception as e:
  6140. log.debug("App.on_file_new() --> %s" % str(e))
  6141. # # And then add again the Plot Area
  6142. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  6143. self.ui.plot_tab_area.protectTab(0)
  6144. # take the focus of the Notebook on Project Tab.
  6145. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6146. self.set_ui_title(name=_("New Project - Not saved"))
  6147. def obj_properties(self):
  6148. """
  6149. Will launch the object Properties Tool
  6150. :return:
  6151. """
  6152. self.defaults.report_usage("obj_properties()")
  6153. self.properties_tool.run(toggle=False)
  6154. def on_project_context_save(self):
  6155. """
  6156. Wrapper, will save the object function of it's type
  6157. :return:
  6158. """
  6159. obj = self.collection.get_active()
  6160. if type(obj) == GeometryObject:
  6161. self.on_file_exportdxf()
  6162. elif type(obj) == ExcellonObject:
  6163. self.on_file_saveexcellon()
  6164. elif type(obj) == CNCJobObject:
  6165. obj.on_exportgcode_button_click()
  6166. elif type(obj) == GerberObject:
  6167. self.on_file_savegerber()
  6168. elif type(obj) == ScriptObject:
  6169. self.on_file_savescript()
  6170. elif type(obj) == DocumentObject:
  6171. self.on_file_savedocument()
  6172. def obj_move(self):
  6173. """
  6174. Callback for the Move menu entry in various Context Menu's.
  6175. :return:
  6176. """
  6177. self.defaults.report_usage("obj_move()")
  6178. self.move_tool.run(toggle=False)
  6179. def on_fileopengerber(self, signal, name=None):
  6180. """
  6181. File menu callback for opening a Gerber.
  6182. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6183. :param name:
  6184. :return: None
  6185. """
  6186. self.defaults.report_usage("on_fileopengerber")
  6187. App.log.debug("on_fileopengerber()")
  6188. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6189. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6190. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6191. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6192. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6193. "*.mil);;" \
  6194. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6195. "Allegro Files (*.art);;" \
  6196. "Mentor Files (*.pho *.gdo);;" \
  6197. "All Files (*.*)"
  6198. if name is None:
  6199. try:
  6200. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6201. directory=self.get_last_folder(),
  6202. filter=_filter_)
  6203. except TypeError:
  6204. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6205. filenames = [str(filename) for filename in filenames]
  6206. else:
  6207. filenames = [name]
  6208. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6209. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6210. _("Opening Gerber file.")),
  6211. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6212. color=QtGui.QColor("gray"))
  6213. if len(filenames) == 0:
  6214. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6215. else:
  6216. for filename in filenames:
  6217. if filename != '':
  6218. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6219. def on_fileopenexcellon(self, signal, name=None):
  6220. """
  6221. File menu callback for opening an Excellon file.
  6222. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6223. :param name:
  6224. :return: None
  6225. """
  6226. self.defaults.report_usage("on_fileopenexcellon")
  6227. App.log.debug("on_fileopenexcellon()")
  6228. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6229. "All Files (*.*)"
  6230. if name is None:
  6231. try:
  6232. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6233. directory=self.get_last_folder(),
  6234. filter=_filter_)
  6235. except TypeError:
  6236. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6237. filenames = [str(filename) for filename in filenames]
  6238. else:
  6239. filenames = [str(name)]
  6240. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6241. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6242. _("Opening Excellon file.")),
  6243. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6244. color=QtGui.QColor("gray"))
  6245. if len(filenames) == 0:
  6246. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6247. else:
  6248. for filename in filenames:
  6249. if filename != '':
  6250. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6251. def on_fileopengcode(self, signal, name=None):
  6252. """
  6253. File menu call back for opening gcode.
  6254. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6255. :param name:
  6256. :return:
  6257. """
  6258. self.defaults.report_usage("on_fileopengcode")
  6259. App.log.debug("on_fileopengcode()")
  6260. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6261. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6262. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6263. "All Files (*.*)"
  6264. if name is None:
  6265. try:
  6266. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6267. directory=self.get_last_folder(),
  6268. filter=_filter_)
  6269. except TypeError:
  6270. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6271. filenames = [str(filename) for filename in filenames]
  6272. else:
  6273. filenames = [name]
  6274. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6275. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6276. _("Opening G-Code file.")),
  6277. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6278. color=QtGui.QColor("gray"))
  6279. if len(filenames) == 0:
  6280. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6281. else:
  6282. for filename in filenames:
  6283. if filename != '':
  6284. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6285. def on_file_openproject(self, signal):
  6286. """
  6287. File menu callback for opening a project.
  6288. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6289. :return: None
  6290. """
  6291. self.defaults.report_usage("on_file_openproject")
  6292. App.log.debug("on_file_openproject()")
  6293. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6294. try:
  6295. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6296. directory=self.get_last_folder(), filter=_filter_)
  6297. except TypeError:
  6298. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6299. # The Qt methods above will return a QString which can cause problems later.
  6300. # So far json.dump() will fail to serialize it.
  6301. # TODO: Improve the serialization methods and remove this fix.
  6302. filename = str(filename)
  6303. if filename == "":
  6304. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6305. else:
  6306. # self.worker_task.emit({'fcn': self.open_project,
  6307. # 'params': [filename]})
  6308. # The above was failing because open_project() is not
  6309. # thread safe. The new_project()
  6310. self.open_project(filename)
  6311. def on_fileopenhpgl2(self, signal, name=None):
  6312. """
  6313. File menu callback for opening a HPGL2.
  6314. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6315. :param name:
  6316. :return: None
  6317. """
  6318. self.defaults.report_usage("on_fileopenhpgl2")
  6319. App.log.debug("on_fileopenhpgl2()")
  6320. _filter_ = "HPGL2 Files (*.plt);;" \
  6321. "All Files (*.*)"
  6322. if name is None:
  6323. try:
  6324. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6325. directory=self.get_last_folder(),
  6326. filter=_filter_)
  6327. except TypeError:
  6328. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6329. filenames = [str(filename) for filename in filenames]
  6330. else:
  6331. filenames = [name]
  6332. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6333. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6334. _("Opening HPGL2 file.")),
  6335. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6336. color=QtGui.QColor("gray"))
  6337. if len(filenames) == 0:
  6338. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6339. else:
  6340. for filename in filenames:
  6341. if filename != '':
  6342. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6343. def on_file_openconfig(self, signal):
  6344. """
  6345. File menu callback for opening a config file.
  6346. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6347. :return: None
  6348. """
  6349. self.defaults.report_usage("on_file_openconfig")
  6350. App.log.debug("on_file_openconfig()")
  6351. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6352. try:
  6353. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6354. directory=self.data_path, filter=_filter_)
  6355. except TypeError:
  6356. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6357. filter=_filter_)
  6358. if filename == "":
  6359. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6360. else:
  6361. self.open_config_file(filename)
  6362. def on_file_exportsvg(self):
  6363. """
  6364. Callback for menu item File->Export SVG.
  6365. :return: None
  6366. """
  6367. self.defaults.report_usage("on_file_exportsvg")
  6368. App.log.debug("on_file_exportsvg()")
  6369. obj = self.collection.get_active()
  6370. if obj is None:
  6371. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6372. msg = _("Please Select a Geometry object to export")
  6373. msgbox = QtWidgets.QMessageBox()
  6374. msgbox.setInformativeText(msg)
  6375. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6376. msgbox.setDefaultButton(bt_ok)
  6377. msgbox.exec_()
  6378. return
  6379. # Check for more compatible types and add as required
  6380. if (not isinstance(obj, GeometryObject)
  6381. and not isinstance(obj, GerberObject)
  6382. and not isinstance(obj, CNCJobObject)
  6383. and not isinstance(obj, ExcellonObject)):
  6384. msg = '[ERROR_NOTCL] %s' % \
  6385. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6386. msgbox = QtWidgets.QMessageBox()
  6387. msgbox.setInformativeText(msg)
  6388. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6389. msgbox.setDefaultButton(bt_ok)
  6390. msgbox.exec_()
  6391. return
  6392. name = obj.options["name"]
  6393. _filter = "SVG File (*.svg);;All Files (*.*)"
  6394. try:
  6395. filename, _f = FCFileSaveDialog.get_saved_filename(
  6396. caption=_("Export SVG"),
  6397. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6398. filter=_filter)
  6399. except TypeError:
  6400. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6401. filename = str(filename)
  6402. if filename == "":
  6403. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6404. return
  6405. else:
  6406. self.export_svg(name, filename)
  6407. if self.defaults["global_open_style"] is False:
  6408. self.file_opened.emit("SVG", filename)
  6409. self.file_saved.emit("SVG", filename)
  6410. def on_file_exportpng(self):
  6411. self.defaults.report_usage("on_file_exportpng")
  6412. App.log.debug("on_file_exportpng()")
  6413. self.date = str(datetime.today()).rpartition('.')[0]
  6414. self.date = ''.join(c for c in self.date if c not in ':-')
  6415. self.date = self.date.replace(' ', '_')
  6416. if self.is_legacy is False:
  6417. image = _screenshot()
  6418. data = np.asarray(image)
  6419. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6420. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6421. return
  6422. filter_ = "PNG File (*.png);;All Files (*.*)"
  6423. try:
  6424. filename, _f = FCFileSaveDialog.get_saved_filename(
  6425. caption=_("Export PNG Image"),
  6426. directory=self.get_last_save_folder() + '/png_' + self.date,
  6427. filter=filter_)
  6428. except TypeError:
  6429. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6430. filename = str(filename)
  6431. if filename == "":
  6432. self.inform.emit(_("Cancelled."))
  6433. return
  6434. else:
  6435. if self.is_legacy is False:
  6436. write_png(filename, data)
  6437. else:
  6438. self.plotcanvas.figure.savefig(filename)
  6439. if self.defaults["global_open_style"] is False:
  6440. self.file_opened.emit("png", filename)
  6441. self.file_saved.emit("png", filename)
  6442. def on_file_savegerber(self):
  6443. """
  6444. Callback for menu item in Project context menu.
  6445. :return: None
  6446. """
  6447. self.defaults.report_usage("on_file_savegerber")
  6448. App.log.debug("on_file_savegerber()")
  6449. obj = self.collection.get_active()
  6450. if obj is None:
  6451. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6452. return
  6453. # Check for more compatible types and add as required
  6454. if not isinstance(obj, GerberObject):
  6455. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6456. return
  6457. name = self.collection.get_active().options["name"]
  6458. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6459. try:
  6460. filename, _f = FCFileSaveDialog.get_saved_filename(
  6461. caption="Save Gerber source file",
  6462. directory=self.get_last_save_folder() + '/' + name,
  6463. filter=_filter)
  6464. except TypeError:
  6465. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6466. filename = str(filename)
  6467. if filename == "":
  6468. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6469. return
  6470. else:
  6471. self.save_source_file(name, filename)
  6472. if self.defaults["global_open_style"] is False:
  6473. self.file_opened.emit("Gerber", filename)
  6474. self.file_saved.emit("Gerber", filename)
  6475. def on_file_savescript(self):
  6476. """
  6477. Callback for menu item in Project context menu.
  6478. :return: None
  6479. """
  6480. self.defaults.report_usage("on_file_savescript")
  6481. App.log.debug("on_file_savescript()")
  6482. obj = self.collection.get_active()
  6483. if obj is None:
  6484. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6485. return
  6486. # Check for more compatible types and add as required
  6487. if not isinstance(obj, ScriptObject):
  6488. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6489. return
  6490. name = self.collection.get_active().options["name"]
  6491. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6492. try:
  6493. filename, _f = FCFileSaveDialog.get_saved_filename(
  6494. caption="Save Script source file",
  6495. directory=self.get_last_save_folder() + '/' + name,
  6496. filter=_filter)
  6497. except TypeError:
  6498. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6499. filename = str(filename)
  6500. if filename == "":
  6501. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6502. return
  6503. else:
  6504. self.save_source_file(name, filename)
  6505. if self.defaults["global_open_style"] is False:
  6506. self.file_opened.emit("Script", filename)
  6507. self.file_saved.emit("Script", filename)
  6508. def on_file_savedocument(self):
  6509. """
  6510. Callback for menu item in Project context menu.
  6511. :return: None
  6512. """
  6513. self.defaults.report_usage("on_file_savedocument")
  6514. App.log.debug("on_file_savedocument()")
  6515. obj = self.collection.get_active()
  6516. if obj is None:
  6517. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6518. return
  6519. # Check for more compatible types and add as required
  6520. if not isinstance(obj, ScriptObject):
  6521. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6522. return
  6523. name = self.collection.get_active().options["name"]
  6524. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6525. try:
  6526. filename, _f = FCFileSaveDialog.get_saved_filename(
  6527. caption="Save Document source file",
  6528. directory=self.get_last_save_folder() + '/' + name,
  6529. filter=_filter)
  6530. except TypeError:
  6531. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6532. filename = str(filename)
  6533. if filename == "":
  6534. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6535. return
  6536. else:
  6537. self.save_source_file(name, filename)
  6538. if self.defaults["global_open_style"] is False:
  6539. self.file_opened.emit("Document", filename)
  6540. self.file_saved.emit("Document", filename)
  6541. def on_file_saveexcellon(self):
  6542. """
  6543. Callback for menu item in project context menu.
  6544. :return: None
  6545. """
  6546. self.defaults.report_usage("on_file_saveexcellon")
  6547. App.log.debug("on_file_saveexcellon()")
  6548. obj = self.collection.get_active()
  6549. if obj is None:
  6550. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6551. return
  6552. # Check for more compatible types and add as required
  6553. if not isinstance(obj, ExcellonObject):
  6554. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6555. return
  6556. name = self.collection.get_active().options["name"]
  6557. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6558. try:
  6559. filename, _f = FCFileSaveDialog.get_saved_filename(
  6560. caption=_("Save Excellon source file"),
  6561. directory=self.get_last_save_folder() + '/' + name,
  6562. filter=_filter)
  6563. except TypeError:
  6564. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6565. filename = str(filename)
  6566. if filename == "":
  6567. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6568. return
  6569. else:
  6570. self.save_source_file(name, filename)
  6571. if self.defaults["global_open_style"] is False:
  6572. self.file_opened.emit("Excellon", filename)
  6573. self.file_saved.emit("Excellon", filename)
  6574. def on_file_exportexcellon(self):
  6575. """
  6576. Callback for menu item File->Export->Excellon.
  6577. :return: None
  6578. """
  6579. self.defaults.report_usage("on_file_exportexcellon")
  6580. App.log.debug("on_file_exportexcellon()")
  6581. obj = self.collection.get_active()
  6582. if obj is None:
  6583. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6584. return
  6585. # Check for more compatible types and add as required
  6586. if not isinstance(obj, ExcellonObject):
  6587. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6588. return
  6589. name = self.collection.get_active().options["name"]
  6590. _filter = self.defaults["excellon_save_filters"]
  6591. try:
  6592. filename, _f = FCFileSaveDialog.get_saved_filename(
  6593. caption=_("Export Excellon"),
  6594. directory=self.get_last_save_folder() + '/' + name,
  6595. filter=_filter)
  6596. except TypeError:
  6597. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6598. filename = str(filename)
  6599. if filename == "":
  6600. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6601. return
  6602. else:
  6603. used_extension = filename.rpartition('.')[2]
  6604. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6605. self.export_excellon(name, filename)
  6606. if self.defaults["global_open_style"] is False:
  6607. self.file_opened.emit("Excellon", filename)
  6608. self.file_saved.emit("Excellon", filename)
  6609. def on_file_exportgerber(self):
  6610. """
  6611. Callback for menu item File->Export->Gerber.
  6612. :return: None
  6613. """
  6614. self.defaults.report_usage("on_file_exportgerber")
  6615. App.log.debug("on_file_exportgerber()")
  6616. obj = self.collection.get_active()
  6617. if obj is None:
  6618. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6619. return
  6620. # Check for more compatible types and add as required
  6621. if not isinstance(obj, GerberObject):
  6622. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6623. return
  6624. name = self.collection.get_active().options["name"]
  6625. _filter_ = self.defaults['gerber_save_filters']
  6626. try:
  6627. filename, _f = FCFileSaveDialog.get_saved_filename(
  6628. caption=_("Export Gerber"),
  6629. directory=self.get_last_save_folder() + '/' + name,
  6630. filter=_filter_)
  6631. except TypeError:
  6632. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6633. filename = str(filename)
  6634. if filename == "":
  6635. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6636. return
  6637. else:
  6638. used_extension = filename.rpartition('.')[2]
  6639. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6640. self.export_gerber(name, filename)
  6641. if self.defaults["global_open_style"] is False:
  6642. self.file_opened.emit("Gerber", filename)
  6643. self.file_saved.emit("Gerber", filename)
  6644. def on_file_exportdxf(self):
  6645. """
  6646. Callback for menu item File->Export DXF.
  6647. :return: None
  6648. """
  6649. self.defaults.report_usage("on_file_exportdxf")
  6650. App.log.debug("on_file_exportdxf()")
  6651. obj = self.collection.get_active()
  6652. if obj is None:
  6653. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6654. msg = _("Please Select a Geometry object to export")
  6655. msgbox = QtWidgets.QMessageBox()
  6656. msgbox.setInformativeText(msg)
  6657. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6658. msgbox.setDefaultButton(bt_ok)
  6659. msgbox.exec_()
  6660. return
  6661. # Check for more compatible types and add as required
  6662. if not isinstance(obj, GeometryObject):
  6663. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6664. msgbox = QtWidgets.QMessageBox()
  6665. msgbox.setInformativeText(msg)
  6666. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6667. msgbox.setDefaultButton(bt_ok)
  6668. msgbox.exec_()
  6669. return
  6670. name = self.collection.get_active().options["name"]
  6671. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6672. try:
  6673. filename, _f = FCFileSaveDialog.get_saved_filename(
  6674. caption=_("Export DXF"),
  6675. directory=self.get_last_save_folder() + '/' + name,
  6676. filter=_filter_)
  6677. except TypeError:
  6678. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6679. filename = str(filename)
  6680. if filename == "":
  6681. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6682. return
  6683. else:
  6684. self.export_dxf(name, filename)
  6685. if self.defaults["global_open_style"] is False:
  6686. self.file_opened.emit("DXF", filename)
  6687. self.file_saved.emit("DXF", filename)
  6688. def on_file_importsvg(self, type_of_obj):
  6689. """
  6690. Callback for menu item File->Import SVG.
  6691. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6692. :type type_of_obj: str
  6693. :return: None
  6694. """
  6695. self.defaults.report_usage("on_file_importsvg")
  6696. App.log.debug("on_file_importsvg()")
  6697. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6698. try:
  6699. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6700. directory=self.get_last_folder(), filter=_filter_)
  6701. except TypeError:
  6702. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6703. filter=_filter_)
  6704. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6705. type_of_obj = "geometry"
  6706. filenames = [str(filename) for filename in filenames]
  6707. if len(filenames) == 0:
  6708. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6709. else:
  6710. for filename in filenames:
  6711. if filename != '':
  6712. self.worker_task.emit({'fcn': self.import_svg,
  6713. 'params': [filename, type_of_obj]})
  6714. def on_file_importdxf(self, type_of_obj):
  6715. """
  6716. Callback for menu item File->Import DXF.
  6717. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6718. :type type_of_obj: str
  6719. :return: None
  6720. """
  6721. self.defaults.report_usage("on_file_importdxf")
  6722. App.log.debug("on_file_importdxf()")
  6723. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6724. try:
  6725. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6726. directory=self.get_last_folder(),
  6727. filter=_filter_)
  6728. except TypeError:
  6729. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6730. filter=_filter_)
  6731. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6732. type_of_obj = "geometry"
  6733. filenames = [str(filename) for filename in filenames]
  6734. if len(filenames) == 0:
  6735. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6736. else:
  6737. for filename in filenames:
  6738. if filename != '':
  6739. self.worker_task.emit({'fcn': self.import_dxf,
  6740. 'params': [filename, type_of_obj]})
  6741. # ###############################################################################################################
  6742. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6743. # ###############################################################################################################
  6744. def init_code_editor(self, name):
  6745. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6746. # add the tab if it was closed
  6747. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6748. self.text_editor_tab.setObjectName('text_editor_tab')
  6749. # delete the absolute and relative position and messages in the infobar
  6750. self.ui.position_label.setText("")
  6751. self.ui.rel_position_label.setText("")
  6752. # first clear previous text in text editor (if any)
  6753. self.text_editor_tab.code_editor.clear()
  6754. self.text_editor_tab.code_editor.setReadOnly(False)
  6755. self.toggle_codeeditor = True
  6756. self.text_editor_tab.code_editor.completer_enable = False
  6757. self.text_editor_tab.buttonRun.hide()
  6758. # make sure to keep a reference to the code editor
  6759. self.reference_code_editor = self.text_editor_tab.code_editor
  6760. # Switch plot_area to CNCJob tab
  6761. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6762. def on_view_source(self):
  6763. """
  6764. Called when the user wants to see the source file of the selected object
  6765. :return:
  6766. """
  6767. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6768. self.proc_container.view.set_busy(_("Loading..."))
  6769. try:
  6770. obj = self.collection.get_active()
  6771. except Exception as e:
  6772. log.debug("App.on_view_source() --> %s" % str(e))
  6773. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6774. return 'fail'
  6775. if obj is None:
  6776. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6777. return 'fail'
  6778. flt = "All Files (*.*)"
  6779. if obj.kind == 'gerber':
  6780. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6781. elif obj.kind == 'excellon':
  6782. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6783. elif obj.kind == 'cncjob':
  6784. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6785. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6786. # add the tab if it was closed
  6787. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6788. self.source_editor_tab.setObjectName('source_editor_tab')
  6789. # delete the absolute and relative position and messages in the infobar
  6790. self.ui.position_label.setText("")
  6791. self.ui.rel_position_label.setText("")
  6792. # first clear previous text in text editor (if any)
  6793. self.source_editor_tab.code_editor.clear()
  6794. self.source_editor_tab.code_editor.setReadOnly(False)
  6795. self.source_editor_tab.code_editor.completer_enable = False
  6796. self.source_editor_tab.buttonRun.hide()
  6797. # Switch plot_area to CNCJob tab
  6798. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6799. try:
  6800. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6801. except TypeError:
  6802. pass
  6803. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6804. try:
  6805. self.source_editor_tab.buttonSave.clicked.disconnect()
  6806. except TypeError:
  6807. pass
  6808. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6809. # then append the text from GCode to the text editor
  6810. if obj.kind == 'cncjob':
  6811. try:
  6812. file = obj.export_gcode(
  6813. preamble=self.defaults["cncjob_prepend"],
  6814. postamble=self.defaults["cncjob_append"],
  6815. to_file=True)
  6816. if file == 'fail':
  6817. return 'fail'
  6818. except AttributeError:
  6819. self.inform.emit('[WARNING_NOTCL] %s' %
  6820. _("There is no selected object for which to see it's source file code."))
  6821. return 'fail'
  6822. else:
  6823. try:
  6824. file = StringIO(obj.source_file)
  6825. except (AttributeError, TypeError):
  6826. self.inform.emit('[WARNING_NOTCL] %s' %
  6827. _("There is no selected object for which to see it's source file code."))
  6828. return 'fail'
  6829. self.source_editor_tab.t_frame.hide()
  6830. try:
  6831. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6832. # for line in file:
  6833. # QtWidgets.QApplication.processEvents()
  6834. # proc_line = str(line).strip('\n')
  6835. # self.source_editor_tab.code_editor.append(proc_line)
  6836. except Exception as e:
  6837. log.debug('App.on_view_source() -->%s' % str(e))
  6838. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6839. return
  6840. self.source_editor_tab.handleTextChanged()
  6841. self.source_editor_tab.t_frame.show()
  6842. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6843. self.proc_container.view.set_idle()
  6844. # self.ui.show()
  6845. def on_toggle_code_editor(self):
  6846. self.defaults.report_usage("on_toggle_code_editor()")
  6847. if self.toggle_codeeditor is False:
  6848. self.init_code_editor(name=_("Code Editor"))
  6849. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6850. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6851. self.text_editor_tab.buttonSave.clicked.disconnect()
  6852. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6853. else:
  6854. for idx in range(self.ui.plot_tab_area.count()):
  6855. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6856. self.ui.plot_tab_area.closeTab(idx)
  6857. break
  6858. self.toggle_codeeditor = False
  6859. def on_code_editor_close(self):
  6860. self.toggle_codeeditor = False
  6861. def goto_text_line(self):
  6862. """
  6863. Will scroll a text to the specified text line.
  6864. :return: None
  6865. """
  6866. dia_box = Dialog_box(title=_("Go to Line ..."),
  6867. label=_("Line:"),
  6868. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6869. initial_text='')
  6870. try:
  6871. line = int(dia_box.location) - 1
  6872. except (ValueError, TypeError):
  6873. line = 0
  6874. if dia_box.ok:
  6875. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6876. # at the top of the window
  6877. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6878. # get the document() of the TextEditor
  6879. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6880. # create a Text Cursor based on the searched line
  6881. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6882. # set cursor of the code editor with the cursor at the searcehd line
  6883. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6884. def on_filenewscript(self, silent=False):
  6885. """
  6886. Will create a new script file and open it in the Code Editor
  6887. :param silent: if True will not display status messages
  6888. :param name: if specified will be the name of the new script
  6889. :param text: pass a source file to the newly created script to be loaded in it
  6890. :return: None
  6891. """
  6892. if silent is False:
  6893. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6894. # delete the absolute and relative position and messages in the infobar
  6895. self.ui.position_label.setText("")
  6896. self.ui.rel_position_label.setText("")
  6897. self.new_script_object()
  6898. # script_text = script_obj.source_file
  6899. #
  6900. # self.proc_container.view.set_busy(_("Loading..."))
  6901. # script_obj.script_editor_tab.t_frame.hide()
  6902. #
  6903. # script_obj.script_editor_tab.t_frame.show()
  6904. # self.proc_container.view.set_idle()
  6905. def on_fileopenscript(self, name=None, silent=False):
  6906. """
  6907. Will open a Tcl script file into the Code Editor
  6908. :param silent: if True will not display status messages
  6909. :param name: name of a Tcl script file to open
  6910. :return: None
  6911. """
  6912. self.defaults.report_usage("on_fileopenscript")
  6913. App.log.debug("on_fileopenscript()")
  6914. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6915. "All Files (*.*)"
  6916. if name:
  6917. filenames = [name]
  6918. else:
  6919. try:
  6920. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6921. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6922. except TypeError:
  6923. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6924. if len(filenames) == 0:
  6925. if silent is False:
  6926. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6927. else:
  6928. for filename in filenames:
  6929. if filename != '':
  6930. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6931. def on_fileopenscript_example(self, name=None, silent=False):
  6932. """
  6933. Will open a Tcl script file into the Code Editor
  6934. :param silent: if True will not display status messages
  6935. :param name: name of a Tcl script file to open
  6936. :return:
  6937. """
  6938. self.defaults.report_usage("on_fileopenscript_example")
  6939. log.debug("on_fileopenscript_example()")
  6940. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6941. "All Files (*.*)"
  6942. # test if the app was frozen and choose the path for the configuration file
  6943. if getattr(sys, "frozen", False) is True:
  6944. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6945. else:
  6946. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6947. if name:
  6948. filenames = [name]
  6949. else:
  6950. try:
  6951. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6952. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6953. except TypeError:
  6954. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6955. if len(filenames) == 0:
  6956. if silent is False:
  6957. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6958. else:
  6959. for filename in filenames:
  6960. if filename != '':
  6961. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6962. def on_filerunscript(self, name=None, silent=False):
  6963. """
  6964. File menu callback for loading and running a TCL script.
  6965. :param silent: if True will not display status messages
  6966. :param name: name of a Tcl script file to be run by FlatCAM
  6967. :return: None
  6968. """
  6969. self.defaults.report_usage("on_filerunscript")
  6970. App.log.debug("on_file_runscript()")
  6971. if name:
  6972. filename = name
  6973. if self.cmd_line_headless != 1:
  6974. self.splash.showMessage('%s: %ssec\n%s' %
  6975. (_("Canvas initialization started.\n"
  6976. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6977. _("Executing ScriptObject file.")
  6978. ),
  6979. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6980. color=QtGui.QColor("gray"))
  6981. else:
  6982. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6983. "All Files (*.*)"
  6984. try:
  6985. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6986. directory=self.get_last_folder(), filter=_filter_)
  6987. except TypeError:
  6988. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6989. # The Qt methods above will return a QString which can cause problems later.
  6990. # So far json.dump() will fail to serialize it.
  6991. filename = str(filename)
  6992. if filename == "":
  6993. if silent is False:
  6994. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6995. else:
  6996. if self.cmd_line_headless != 1:
  6997. if self.ui.shell_dock.isHidden():
  6998. self.ui.shell_dock.show()
  6999. try:
  7000. with open(filename, "r") as tcl_script:
  7001. cmd_line_shellfile_content = tcl_script.read()
  7002. if self.cmd_line_headless != 1:
  7003. self.shell.exec_command(cmd_line_shellfile_content)
  7004. else:
  7005. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7006. if silent is False:
  7007. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7008. except Exception as e:
  7009. log.debug("App.on_filerunscript() -> %s" % str(e))
  7010. sys.exit(2)
  7011. def on_file_saveproject(self, silent=False):
  7012. """
  7013. Callback for menu item File->Save Project. Saves the project to
  7014. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7015. if set to None. The project is saved by calling ``self.save_project()``.
  7016. :param silent: if True will not display status messages
  7017. :return: None
  7018. """
  7019. self.defaults.report_usage("on_file_saveproject")
  7020. if self.project_filename is None:
  7021. self.on_file_saveprojectas()
  7022. else:
  7023. self.worker_task.emit({'fcn': self.save_project,
  7024. 'params': [self.project_filename, silent]})
  7025. if self.defaults["global_open_style"] is False:
  7026. self.file_opened.emit("project", self.project_filename)
  7027. self.file_saved.emit("project", self.project_filename)
  7028. self.set_ui_title(name=self.project_filename)
  7029. self.should_we_save = False
  7030. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7031. """
  7032. Callback for menu item File->Save Project As... Opens a file
  7033. chooser and saves the project to the given file via
  7034. ``self.save_project()``.
  7035. :param make_copy if to be create a copy of the project; boolean
  7036. :param use_thread: if to be run in a separate thread; boolean
  7037. :param quit_action: if to be followed by quiting the application; boolean
  7038. :return: None
  7039. """
  7040. self.defaults.report_usage("on_file_saveprojectas")
  7041. self.date = str(datetime.today()).rpartition('.')[0]
  7042. self.date = ''.join(c for c in self.date if c not in ':-')
  7043. self.date = self.date.replace(' ', '_')
  7044. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7045. try:
  7046. filename, _f = FCFileSaveDialog.get_saved_filename(
  7047. caption=_("Save Project As ..."),
  7048. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  7049. proj=_("Project")),
  7050. filter=filter_
  7051. )
  7052. except TypeError:
  7053. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  7054. filename = str(filename)
  7055. if filename == '':
  7056. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7057. return
  7058. if use_thread is True:
  7059. self.worker_task.emit({'fcn': self.save_project,
  7060. 'params': [filename, quit_action]})
  7061. else:
  7062. self.save_project(filename, quit_action)
  7063. # self.save_project(filename)
  7064. if self.defaults["global_open_style"] is False:
  7065. self.file_opened.emit("project", filename)
  7066. self.file_saved.emit("project", filename)
  7067. if not make_copy:
  7068. self.project_filename = filename
  7069. self.set_ui_title(name=self.project_filename)
  7070. self.should_we_save = False
  7071. def on_file_save_objects_pdf(self, use_thread=True):
  7072. self.date = str(datetime.today()).rpartition('.')[0]
  7073. self.date = ''.join(c for c in self.date if c not in ':-')
  7074. self.date = self.date.replace(' ', '_')
  7075. try:
  7076. obj_selection = self.collection.get_selected()
  7077. if len(obj_selection) == 1:
  7078. obj_name = str(obj_selection[0].options['name'])
  7079. else:
  7080. obj_name = _("FlatCAM objects print")
  7081. except AttributeError as err:
  7082. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7083. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7084. return
  7085. if not obj_selection:
  7086. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7087. return
  7088. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7089. try:
  7090. filename, _f = FCFileSaveDialog.get_saved_filename(
  7091. caption=_("Save Object as PDF ..."),
  7092. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7093. obj_name=obj_name,
  7094. date=self.date),
  7095. filter=filter_
  7096. )
  7097. except TypeError:
  7098. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7099. filename = str(filename)
  7100. if filename == '':
  7101. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7102. return
  7103. if use_thread is True:
  7104. self.proc_container.new(_("Printing PDF ... Please wait."))
  7105. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7106. else:
  7107. self.save_pdf(filename, obj_selection)
  7108. # self.save_project(filename)
  7109. if self.defaults["global_open_style"] is False:
  7110. self.file_opened.emit("pdf", filename)
  7111. self.file_saved.emit("pdf", filename)
  7112. def save_pdf(self, file_name, obj_selection):
  7113. p_size = self.defaults['global_workspaceT']
  7114. orientation = self.defaults['global_workspace_orientation']
  7115. color = 'black'
  7116. transparency_level = 1.0
  7117. self.pagesize = {}
  7118. self.pagesize.update(
  7119. {
  7120. 'Bounds': None,
  7121. 'A0': (841 * mm, 1189 * mm),
  7122. 'A1': (594 * mm, 841 * mm),
  7123. 'A2': (420 * mm, 594 * mm),
  7124. 'A3': (297 * mm, 420 * mm),
  7125. 'A4': (210 * mm, 297 * mm),
  7126. 'A5': (148 * mm, 210 * mm),
  7127. 'A6': (105 * mm, 148 * mm),
  7128. 'A7': (74 * mm, 105 * mm),
  7129. 'A8': (52 * mm, 74 * mm),
  7130. 'A9': (37 * mm, 52 * mm),
  7131. 'A10': (26 * mm, 37 * mm),
  7132. 'B0': (1000 * mm, 1414 * mm),
  7133. 'B1': (707 * mm, 1000 * mm),
  7134. 'B2': (500 * mm, 707 * mm),
  7135. 'B3': (353 * mm, 500 * mm),
  7136. 'B4': (250 * mm, 353 * mm),
  7137. 'B5': (176 * mm, 250 * mm),
  7138. 'B6': (125 * mm, 176 * mm),
  7139. 'B7': (88 * mm, 125 * mm),
  7140. 'B8': (62 * mm, 88 * mm),
  7141. 'B9': (44 * mm, 62 * mm),
  7142. 'B10': (31 * mm, 44 * mm),
  7143. 'C0': (917 * mm, 1297 * mm),
  7144. 'C1': (648 * mm, 917 * mm),
  7145. 'C2': (458 * mm, 648 * mm),
  7146. 'C3': (324 * mm, 458 * mm),
  7147. 'C4': (229 * mm, 324 * mm),
  7148. 'C5': (162 * mm, 229 * mm),
  7149. 'C6': (114 * mm, 162 * mm),
  7150. 'C7': (81 * mm, 114 * mm),
  7151. 'C8': (57 * mm, 81 * mm),
  7152. 'C9': (40 * mm, 57 * mm),
  7153. 'C10': (28 * mm, 40 * mm),
  7154. # American paper sizes
  7155. 'LETTER': (8.5 * inch, 11 * inch),
  7156. 'LEGAL': (8.5 * inch, 14 * inch),
  7157. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7158. # From https://en.wikipedia.org/wiki/Paper_size
  7159. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7160. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7161. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7162. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7163. 'LEDGER': (17 * inch, 11 * inch),
  7164. }
  7165. )
  7166. exported_svg = []
  7167. for obj in obj_selection:
  7168. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7169. scale_factor_x=None, scale_factor_y=None,
  7170. skew_factor_x=None, skew_factor_y=None,
  7171. mirror=None)
  7172. if obj.kind.lower() == 'gerber':
  7173. # color = self.defaults["gerber_plot_fill"][:-2]
  7174. color = obj.fill_color[:-2]
  7175. elif obj.kind.lower() == 'excellon':
  7176. color = '#C40000'
  7177. elif obj.kind.lower() == 'geometry':
  7178. color = self.defaults["global_draw_color"]
  7179. # Change the attributes of the exported SVG
  7180. # We don't need stroke-width
  7181. # We set opacity to maximum
  7182. # We set the colour to WHITE
  7183. root = ET.fromstring(svg_obj)
  7184. for child in root:
  7185. child.set('fill', str(color))
  7186. child.set('opacity', str(transparency_level))
  7187. child.set('stroke', str(color))
  7188. exported_svg.append(ET.tostring(root))
  7189. xmin = Inf
  7190. ymin = Inf
  7191. xmax = -Inf
  7192. ymax = -Inf
  7193. for obj in obj_selection:
  7194. try:
  7195. gxmin, gymin, gxmax, gymax = obj.bounds()
  7196. xmin = min([xmin, gxmin])
  7197. ymin = min([ymin, gymin])
  7198. xmax = max([xmax, gxmax])
  7199. ymax = max([ymax, gymax])
  7200. except Exception as e:
  7201. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7202. # Determine bounding area for svg export
  7203. bounds = [xmin, ymin, xmax, ymax]
  7204. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7205. # This contain the measure units
  7206. uom = obj_selection[0].units.lower()
  7207. # Define a boundary around SVG of about 1.0mm (~39mils)
  7208. if uom in "mm":
  7209. boundary = 1.0
  7210. else:
  7211. boundary = 0.0393701
  7212. # Convert everything to strings for use in the xml doc
  7213. svgwidth = str(size[0] + (2 * boundary))
  7214. svgheight = str(size[1] + (2 * boundary))
  7215. minx = str(bounds[0] - boundary)
  7216. miny = str(bounds[1] + boundary + size[1])
  7217. # Add a SVG Header and footer to the svg output from shapely
  7218. # The transform flips the Y Axis so that everything renders
  7219. # properly within svg apps such as inkscape
  7220. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7221. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7222. svg_header += 'width="' + svgwidth + uom + '" '
  7223. svg_header += 'height="' + svgheight + uom + '" '
  7224. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7225. svg_header += '>'
  7226. svg_header += '<g transform="scale(1,-1)">'
  7227. svg_footer = '</g> </svg>'
  7228. svg_elem = str(svg_header)
  7229. for svg_item in exported_svg:
  7230. svg_elem += str(svg_item)
  7231. svg_elem += str(svg_footer)
  7232. # Parse the xml through a xml parser just to add line feeds
  7233. # and to make it look more pretty for the output
  7234. doc = parse_xml_string(svg_elem)
  7235. doc_final = doc.toprettyxml()
  7236. try:
  7237. if self.defaults['units'].upper() == 'IN':
  7238. unit = inch
  7239. else:
  7240. unit = mm
  7241. doc_final = StringIO(doc_final)
  7242. drawing = svg2rlg(doc_final)
  7243. if p_size == 'Bounds':
  7244. renderPDF.drawToFile(drawing, file_name)
  7245. else:
  7246. if orientation == 'p':
  7247. page_size = portrait(self.pagesize[p_size])
  7248. else:
  7249. page_size = landscape(self.pagesize[p_size])
  7250. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7251. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7252. renderPDF.draw(drawing, my_canvas, 0, 0)
  7253. my_canvas.save()
  7254. except Exception as e:
  7255. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7256. return 'fail'
  7257. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7258. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7259. """
  7260. Exports a Geometry Object to an SVG file.
  7261. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7262. :param filename: Path to the SVG file to save to.
  7263. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7264. :return:
  7265. """
  7266. self.defaults.report_usage("export_svg()")
  7267. if filename is None:
  7268. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7269. is not None else self.defaults["global_last_folder"]
  7270. self.log.debug("export_svg()")
  7271. try:
  7272. obj = self.collection.get_by_name(str(obj_name))
  7273. except Exception:
  7274. # TODO: The return behavior has not been established... should raise exception?
  7275. return "Could not retrieve object: %s" % obj_name
  7276. with self.proc_container.new(_("Exporting SVG")) as proc:
  7277. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7278. # Determine bounding area for svg export
  7279. bounds = obj.bounds()
  7280. size = obj.size()
  7281. # Convert everything to strings for use in the xml doc
  7282. svgwidth = str(size[0])
  7283. svgheight = str(size[1])
  7284. minx = str(bounds[0])
  7285. miny = str(bounds[1] - size[1])
  7286. uom = obj.units.lower()
  7287. # Add a SVG Header and footer to the svg output from shapely
  7288. # The transform flips the Y Axis so that everything renders
  7289. # properly within svg apps such as inkscape
  7290. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7291. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7292. svg_header += 'width="' + svgwidth + uom + '" '
  7293. svg_header += 'height="' + svgheight + uom + '" '
  7294. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7295. svg_header += '<g transform="scale(1,-1)">'
  7296. svg_footer = '</g> </svg>'
  7297. svg_elem = svg_header + exported_svg + svg_footer
  7298. # Parse the xml through a xml parser just to add line feeds
  7299. # and to make it look more pretty for the output
  7300. svgcode = parse_xml_string(svg_elem)
  7301. svgcode = svgcode.toprettyxml()
  7302. try:
  7303. with open(filename, 'w') as fp:
  7304. fp.write(svgcode)
  7305. except PermissionError:
  7306. self.inform.emit('[WARNING] %s' %
  7307. _("Permission denied, saving not possible.\n"
  7308. "Most likely another app is holding the file open and not accessible."))
  7309. return 'fail'
  7310. if self.defaults["global_open_style"] is False:
  7311. self.file_opened.emit("SVG", filename)
  7312. self.file_saved.emit("SVG", filename)
  7313. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7314. def save_source_file(self, obj_name, filename, use_thread=True):
  7315. """
  7316. Exports a FlatCAM Object to an Gerber/Excellon file.
  7317. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7318. :param filename: Path to the Gerber file to save to.
  7319. :param use_thread: if to be run in a separate thread
  7320. :return:
  7321. """
  7322. self.defaults.report_usage("save source file()")
  7323. if filename is None:
  7324. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7325. is not None else self.defaults["global_last_folder"]
  7326. self.log.debug("save source file()")
  7327. obj = self.collection.get_by_name(obj_name)
  7328. file_string = StringIO(obj.source_file)
  7329. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7330. if file_string.getvalue() == '':
  7331. self.inform.emit('[ERROR_NOTCL] %s' %
  7332. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7333. return 'fail'
  7334. try:
  7335. with open(filename, 'w') as file:
  7336. file.writelines('G04*\n')
  7337. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7338. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7339. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7340. file.writelines('G04 Created on : %s*\n' % time_string)
  7341. for line in file_string:
  7342. file.writelines(line)
  7343. except PermissionError:
  7344. self.inform.emit('[WARNING] %s' %
  7345. _("Permission denied, saving not possible.\n"
  7346. "Most likely another app is holding the file open and not accessible."))
  7347. return 'fail'
  7348. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7349. """
  7350. Exports a Excellon Object to an Excellon file.
  7351. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7352. :param filename: Path to the Excellon file to save to.
  7353. :param local_use:
  7354. :param use_thread: if to be run in a separate thread
  7355. :return:
  7356. """
  7357. self.defaults.report_usage("export_excellon()")
  7358. if filename is None:
  7359. if self.defaults["global_last_save_folder"]:
  7360. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7361. else:
  7362. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7363. self.log.debug("export_excellon()")
  7364. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7365. self.defaults["excellon_exp_decimals"]
  7366. )
  7367. if local_use is None:
  7368. try:
  7369. obj = self.collection.get_by_name(str(obj_name))
  7370. except Exception:
  7371. return "Could not retrieve object: %s" % obj_name
  7372. else:
  7373. obj = local_use
  7374. if not isinstance(obj, ExcellonObject):
  7375. self.inform.emit('[ERROR_NOTCL] %s' %
  7376. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7377. return
  7378. # updated units
  7379. eunits = self.defaults["excellon_exp_units"]
  7380. ewhole = self.defaults["excellon_exp_integer"]
  7381. efract = self.defaults["excellon_exp_decimals"]
  7382. ezeros = self.defaults["excellon_exp_zeros"]
  7383. eformat = self.defaults["excellon_exp_format"]
  7384. slot_type = self.defaults["excellon_exp_slot_type"]
  7385. fc_units = self.defaults['units'].upper()
  7386. if fc_units == 'MM':
  7387. factor = 1 if eunits == 'METRIC' else 0.03937
  7388. else:
  7389. factor = 25.4 if eunits == 'METRIC' else 1
  7390. def make_excellon():
  7391. try:
  7392. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7393. header = 'M48\n'
  7394. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7395. (str(self.version), str(self.version_date))
  7396. header += ';Filename: %s' % str(obj_name) + '\n'
  7397. header += ';Created on : %s' % time_str + '\n'
  7398. if eformat == 'dec':
  7399. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7400. header += eunits + '\n'
  7401. for tool in obj.tools:
  7402. if eunits == 'METRIC':
  7403. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7404. tool=str(tool),
  7405. dec=2)
  7406. else:
  7407. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7408. tool=str(tool),
  7409. dec=4)
  7410. else:
  7411. if ezeros == 'LZ':
  7412. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7413. form='ndec', e_zeros='LZ', factor=factor,
  7414. slot_type=slot_type)
  7415. header += '%s,%s\n' % (eunits, 'LZ')
  7416. header += format_exc
  7417. for tool in obj.tools:
  7418. if eunits == 'METRIC':
  7419. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7420. tool=str(tool),
  7421. dec=2)
  7422. else:
  7423. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7424. tool=str(tool),
  7425. dec=4)
  7426. else:
  7427. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7428. form='ndec', e_zeros='TZ', factor=factor,
  7429. slot_type=slot_type)
  7430. header += '%s,%s\n' % (eunits, 'TZ')
  7431. header += format_exc
  7432. for tool in obj.tools:
  7433. if eunits == 'METRIC':
  7434. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7435. tool=str(tool),
  7436. dec=2)
  7437. else:
  7438. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7439. tool=str(tool),
  7440. dec=4)
  7441. header += '%\n'
  7442. footer = 'M30\n'
  7443. exported_excellon = header
  7444. exported_excellon += excellon_code
  7445. exported_excellon += footer
  7446. if local_use is None:
  7447. try:
  7448. with open(filename, 'w') as fp:
  7449. fp.write(exported_excellon)
  7450. except PermissionError:
  7451. self.inform.emit('[WARNING] %s' %
  7452. _("Permission denied, saving not possible.\n"
  7453. "Most likely another app is holding the file open and not accessible."))
  7454. return 'fail'
  7455. if self.defaults["global_open_style"] is False:
  7456. self.file_opened.emit("Excellon", filename)
  7457. self.file_saved.emit("Excellon", filename)
  7458. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7459. else:
  7460. return exported_excellon
  7461. except Exception as e:
  7462. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7463. return 'fail'
  7464. if use_thread is True:
  7465. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7466. def job_thread_exc(app_obj):
  7467. ret = make_excellon()
  7468. if ret == 'fail':
  7469. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7470. return
  7471. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7472. else:
  7473. eret = make_excellon()
  7474. if eret == 'fail':
  7475. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7476. return 'fail'
  7477. if local_use is not None:
  7478. return eret
  7479. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7480. """
  7481. Exports a Gerber Object to an Gerber file.
  7482. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7483. :param filename: Path to the Gerber file to save to.
  7484. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7485. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7486. :param use_thread: if to be run in a separate thread
  7487. :return:
  7488. """
  7489. self.defaults.report_usage("export_gerber()")
  7490. if filename is None:
  7491. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7492. is not None else self.defaults["global_last_folder"]
  7493. self.log.debug("export_gerber()")
  7494. if local_use is None:
  7495. try:
  7496. obj = self.collection.get_by_name(str(obj_name))
  7497. except Exception:
  7498. return "Could not retrieve object: %s" % obj_name
  7499. else:
  7500. obj = local_use
  7501. # updated units
  7502. gunits = self.defaults["gerber_exp_units"]
  7503. gwhole = self.defaults["gerber_exp_integer"]
  7504. gfract = self.defaults["gerber_exp_decimals"]
  7505. gzeros = self.defaults["gerber_exp_zeros"]
  7506. fc_units = self.defaults['units'].upper()
  7507. if fc_units == 'MM':
  7508. factor = 1 if gunits == 'MM' else 0.03937
  7509. else:
  7510. factor = 25.4 if gunits == 'MM' else 1
  7511. def make_gerber():
  7512. try:
  7513. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7514. header = 'G04*\n'
  7515. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7516. (str(self.version), str(self.version_date))
  7517. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7518. header += 'G04 Created on : %s*' % time_str + '\n'
  7519. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7520. header += "%MO{units}*%\n".format(units=gunits)
  7521. for apid in obj.apertures:
  7522. if obj.apertures[apid]['type'] == 'C':
  7523. header += "%ADD{apid}{type},{size}*%\n".format(
  7524. apid=str(apid),
  7525. type='C',
  7526. size=(factor * obj.apertures[apid]['size'])
  7527. )
  7528. elif obj.apertures[apid]['type'] == 'R':
  7529. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7530. apid=str(apid),
  7531. type='R',
  7532. width=(factor * obj.apertures[apid]['width']),
  7533. height=(factor * obj.apertures[apid]['height'])
  7534. )
  7535. elif obj.apertures[apid]['type'] == 'O':
  7536. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7537. apid=str(apid),
  7538. type='O',
  7539. width=(factor * obj.apertures[apid]['width']),
  7540. height=(factor * obj.apertures[apid]['height'])
  7541. )
  7542. header += '\n'
  7543. # obsolete units but some software may need it
  7544. if gunits == 'IN':
  7545. header += 'G70*\n'
  7546. else:
  7547. header += 'G71*\n'
  7548. # Absolute Mode
  7549. header += 'G90*\n'
  7550. header += 'G01*\n'
  7551. # positive polarity
  7552. header += '%LPD*%\n'
  7553. footer = 'M02*\n'
  7554. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7555. exported_gerber = header
  7556. exported_gerber += gerber_code
  7557. exported_gerber += footer
  7558. if local_use is None:
  7559. try:
  7560. with open(filename, 'w') as fp:
  7561. fp.write(exported_gerber)
  7562. except PermissionError:
  7563. self.inform.emit('[WARNING] %s' %
  7564. _("Permission denied, saving not possible.\n"
  7565. "Most likely another app is holding the file open and not accessible."))
  7566. return 'fail'
  7567. if self.defaults["global_open_style"] is False:
  7568. self.file_opened.emit("Gerber", filename)
  7569. self.file_saved.emit("Gerber", filename)
  7570. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7571. else:
  7572. return exported_gerber
  7573. except Exception as e:
  7574. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7575. return 'fail'
  7576. if use_thread is True:
  7577. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7578. def job_thread_grb(app_obj):
  7579. ret = make_gerber()
  7580. if ret == 'fail':
  7581. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7582. return
  7583. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7584. else:
  7585. gret = make_gerber()
  7586. if gret == 'fail':
  7587. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7588. return 'fail'
  7589. if local_use is not None:
  7590. return gret
  7591. def export_dxf(self, obj_name, filename, use_thread=True):
  7592. """
  7593. Exports a Geometry Object to an DXF file.
  7594. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7595. :param filename: Path to the DXF file to save to.
  7596. :param use_thread: if to be run in a separate thread
  7597. :return:
  7598. """
  7599. self.defaults.report_usage("export_dxf()")
  7600. if filename is None:
  7601. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7602. is not None else self.defaults["global_last_folder"]
  7603. self.log.debug("export_dxf()")
  7604. try:
  7605. obj = self.collection.get_by_name(str(obj_name))
  7606. except Exception:
  7607. # TODO: The return behavior has not been established... should raise exception?
  7608. return "Could not retrieve object: %s" % obj_name
  7609. def make_dxf():
  7610. try:
  7611. dxf_code = obj.export_dxf()
  7612. dxf_code.saveas(filename)
  7613. if self.defaults["global_open_style"] is False:
  7614. self.file_opened.emit("DXF", filename)
  7615. self.file_saved.emit("DXF", filename)
  7616. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7617. except Exception:
  7618. return 'fail'
  7619. if use_thread is True:
  7620. with self.proc_container.new(_("Exporting DXF")) as proc:
  7621. def job_thread_exc(app_obj):
  7622. ret_dxf_val = make_dxf()
  7623. if ret_dxf_val == 'fail':
  7624. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7625. return
  7626. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7627. else:
  7628. ret = make_dxf()
  7629. if ret == 'fail':
  7630. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7631. return
  7632. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7633. """
  7634. Adds a new Geometry Object to the projects and populates
  7635. it with shapes extracted from the SVG file.
  7636. :param plot: If True then the resulting object will be plotted on canvas
  7637. :param filename: Path to the SVG file.
  7638. :param geo_type: Type of FlatCAM object that will be created from SVG
  7639. :param outname: The name given to the resulting FlatCAM object
  7640. :return:
  7641. """
  7642. self.defaults.report_usage("import_svg()")
  7643. log.debug("App.import_svg()")
  7644. obj_type = ""
  7645. if geo_type is None or geo_type == "geometry":
  7646. obj_type = "geometry"
  7647. elif geo_type == "gerber":
  7648. obj_type = "gerber"
  7649. else:
  7650. self.inform.emit('[ERROR_NOTCL] %s' %
  7651. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7652. return
  7653. units = self.defaults['units'].upper()
  7654. def obj_init(geo_obj, app_obj):
  7655. geo_obj.import_svg(filename, obj_type, units=units)
  7656. geo_obj.multigeo = False
  7657. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7658. with self.proc_container.new(_("Importing SVG")) as proc:
  7659. # Object name
  7660. name = outname or filename.split('/')[-1].split('\\')[-1]
  7661. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7662. if ret == 'fail':
  7663. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7664. return 'fail'
  7665. # Register recent file
  7666. self.file_opened.emit("svg", filename)
  7667. # GUI feedback
  7668. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7669. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7670. """
  7671. Adds a new Geometry Object to the projects and populates
  7672. it with shapes extracted from the DXF file.
  7673. :param filename: Path to the DXF file.
  7674. :param geo_type: Type of FlatCAM object that will be created from DXF
  7675. :param outname: Name for the imported Geometry
  7676. :param plot: If True then the resulting object will be plotted on canvas
  7677. :return:
  7678. """
  7679. self.defaults.report_usage("import_dxf()")
  7680. obj_type = ""
  7681. if geo_type is None or geo_type == "geometry":
  7682. obj_type = "geometry"
  7683. elif geo_type == "gerber":
  7684. obj_type = geo_type
  7685. else:
  7686. self.inform.emit('[ERROR_NOTCL] %s' %
  7687. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7688. return
  7689. units = self.defaults['units'].upper()
  7690. def obj_init(geo_obj, app_obj):
  7691. geo_obj.import_dxf(filename, obj_type, units=units)
  7692. geo_obj.multigeo = False
  7693. with self.proc_container.new(_("Importing DXF")):
  7694. # Object name
  7695. name = outname or filename.split('/')[-1].split('\\')[-1]
  7696. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7697. if ret == 'fail':
  7698. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7699. return 'fail'
  7700. # Register recent file
  7701. self.file_opened.emit("dxf", filename)
  7702. # GUI feedback
  7703. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7704. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7705. """
  7706. Opens a Gerber file, parses it and creates a new object for
  7707. it in the program. Thread-safe.
  7708. :param outname: Name of the resulting object. None causes the
  7709. name to be that of the file. Str.
  7710. :param filename: Gerber file filename
  7711. :type filename: str
  7712. :param plot: boolean, to plot or not the resulting object
  7713. :param from_tcl: True if run from Tcl Shell
  7714. :return: None
  7715. """
  7716. # How the object should be initialized
  7717. def obj_init(gerber_obj, app_obj):
  7718. assert isinstance(gerber_obj, GerberObject), \
  7719. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7720. # Opening the file happens here
  7721. try:
  7722. gerber_obj.parse_file(filename)
  7723. except IOError:
  7724. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7725. return "fail"
  7726. except ParseError as err:
  7727. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7728. app_obj.log.error(str(err))
  7729. return "fail"
  7730. except Exception as e:
  7731. log.debug("App.open_gerber() --> %s" % str(e))
  7732. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7733. msg += traceback.format_exc()
  7734. app_obj.inform.emit(msg)
  7735. return "fail"
  7736. if gerber_obj.is_empty():
  7737. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7738. _("Object is not Gerber file or empty. Aborting object creation."))
  7739. return "fail"
  7740. App.log.debug("open_gerber()")
  7741. with self.proc_container.new(_("Opening Gerber")):
  7742. # Object name
  7743. name = outname or filename.split('/')[-1].split('\\')[-1]
  7744. # # ## Object creation # ##
  7745. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7746. if ret_val == 'fail':
  7747. if from_tcl:
  7748. filename = self.defaults['global_tcl_path'] + '/' + name
  7749. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7750. if ret_val == 'fail':
  7751. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7752. return 'fail'
  7753. # Register recent file
  7754. self.file_opened.emit("gerber", filename)
  7755. # GUI feedback
  7756. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7757. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7758. """
  7759. Opens an Excellon file, parses it and creates a new object for
  7760. it in the program. Thread-safe.
  7761. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7762. :param filename: Excellon file filename
  7763. :type filename: str
  7764. :param plot: boolean, to plot or not the resulting object
  7765. :param from_tcl: True if run from Tcl Shell
  7766. :return: None
  7767. """
  7768. App.log.debug("open_excellon()")
  7769. # How the object should be initialized
  7770. def obj_init(excellon_obj, app_obj):
  7771. try:
  7772. ret = excellon_obj.parse_file(filename=filename)
  7773. if ret == "fail":
  7774. log.debug("Excellon parsing failed.")
  7775. self.inform.emit('[ERROR_NOTCL] %s' %
  7776. _("This is not Excellon file."))
  7777. return "fail"
  7778. except IOError:
  7779. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7780. (_("Cannot open file"), filename))
  7781. log.debug("Could not open Excellon object.")
  7782. return "fail"
  7783. except Exception:
  7784. msg = '[ERROR_NOTCL] %s' % \
  7785. _("An internal error has occurred. See shell.\n")
  7786. msg += traceback.format_exc()
  7787. app_obj.inform.emit(msg)
  7788. return "fail"
  7789. ret = excellon_obj.create_geometry()
  7790. if ret == 'fail':
  7791. log.debug("Could not create geometry for Excellon object.")
  7792. return "fail"
  7793. for tool in excellon_obj.tools:
  7794. if excellon_obj.tools[tool]['solid_geometry']:
  7795. return
  7796. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7797. return "fail"
  7798. with self.proc_container.new(_("Opening Excellon.")):
  7799. # Object name
  7800. name = outname or filename.split('/')[-1].split('\\')[-1]
  7801. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7802. if ret_val == 'fail':
  7803. if from_tcl:
  7804. filename = self.defaults['global_tcl_path'] + '/' + name
  7805. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7806. if ret_val == 'fail':
  7807. self.inform.emit('[ERROR_NOTCL] %s' %
  7808. _('Open Excellon file failed. Probable not an Excellon file.'))
  7809. return
  7810. # Register recent file
  7811. self.file_opened.emit("excellon", filename)
  7812. # GUI feedback
  7813. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7814. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7815. """
  7816. Opens a G-gcode file, parses it and creates a new object for
  7817. it in the program. Thread-safe.
  7818. :param filename: G-code file filename
  7819. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7820. :param force_parsing:
  7821. :param plot: If True plot the object on canvas
  7822. :param from_tcl: True if run from Tcl Shell
  7823. :return: None
  7824. """
  7825. App.log.debug("open_gcode()")
  7826. # How the object should be initialized
  7827. def obj_init(job_obj, app_obj_):
  7828. """
  7829. :param job_obj: the resulting object
  7830. :type app_obj_: App
  7831. """
  7832. assert isinstance(app_obj_, App), \
  7833. "Initializer expected App, got %s" % type(app_obj_)
  7834. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7835. try:
  7836. f = open(filename)
  7837. gcode = f.read()
  7838. f.close()
  7839. except IOError:
  7840. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7841. return "fail"
  7842. job_obj.gcode = gcode
  7843. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7844. if gcode_ret == "fail":
  7845. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7846. return "fail"
  7847. job_obj.create_geometry()
  7848. with self.proc_container.new(_("Opening G-Code.")):
  7849. # Object name
  7850. name = outname or filename.split('/')[-1].split('\\')[-1]
  7851. # New object creation and file processing
  7852. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7853. if ret_val == 'fail':
  7854. if from_tcl:
  7855. filename = self.defaults['global_tcl_path'] + '/' + name
  7856. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7857. if ret_val == 'fail':
  7858. self.inform.emit('[ERROR_NOTCL] %s' %
  7859. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7860. "Try to load it from File menu.\n "
  7861. "Attempting to create a FlatCAM CNCJob Object from "
  7862. "G-Code file failed during processing"))
  7863. return "fail"
  7864. # Register recent file
  7865. self.file_opened.emit("cncjob", filename)
  7866. # GUI feedback
  7867. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7868. def open_hpgl2(self, filename, outname=None):
  7869. """
  7870. Opens a HPGL2 file, parses it and creates a new object for
  7871. it in the program. Thread-safe.
  7872. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7873. :param filename: HPGL2 file filename
  7874. :return: None
  7875. """
  7876. filename = filename
  7877. # How the object should be initialized
  7878. def obj_init(geo_obj, app_obj):
  7879. assert isinstance(geo_obj, GeometryObject), \
  7880. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7881. # Opening the file happens here
  7882. obj = HPGL2(self)
  7883. try:
  7884. HPGL2.parse_file(obj, filename)
  7885. except IOError:
  7886. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7887. return "fail"
  7888. except ParseError as err:
  7889. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7890. app_obj.log.error(str(err))
  7891. return "fail"
  7892. except Exception as e:
  7893. log.debug("App.open_hpgl2() --> %s" % str(e))
  7894. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7895. msg += traceback.format_exc()
  7896. app_obj.inform.emit(msg)
  7897. return "fail"
  7898. geo_obj.multigeo = True
  7899. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7900. geo_obj.tools = deepcopy(obj.tools)
  7901. geo_obj.source_file = deepcopy(obj.source_file)
  7902. del obj
  7903. if not geo_obj.solid_geometry:
  7904. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7905. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7906. return "fail"
  7907. App.log.debug("open_hpgl2()")
  7908. with self.proc_container.new(_("Opening HPGL2")):
  7909. # Object name
  7910. name = outname or filename.split('/')[-1].split('\\')[-1]
  7911. # # ## Object creation # ##
  7912. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7913. if ret == 'fail':
  7914. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7915. return 'fail'
  7916. # Register recent file
  7917. self.file_opened.emit("geometry", filename)
  7918. # GUI feedback
  7919. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7920. def open_script(self, filename, outname=None, silent=False):
  7921. """
  7922. Opens a Script file, parses it and creates a new object for
  7923. it in the program. Thread-safe.
  7924. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7925. :param filename: Script file filename
  7926. :param silent: If True there will be no messages printed to StatusBar
  7927. :return: None
  7928. """
  7929. def obj_init(script_obj, app_obj):
  7930. assert isinstance(script_obj, ScriptObject), \
  7931. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7932. if silent is False:
  7933. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7934. try:
  7935. script_obj.parse_file(filename)
  7936. except IOError:
  7937. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7938. return "fail"
  7939. except ParseError as err:
  7940. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7941. app_obj.log.error(str(err))
  7942. return "fail"
  7943. except Exception as e:
  7944. log.debug("App.open_script() -> %s" % str(e))
  7945. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7946. msg += traceback.format_exc()
  7947. app_obj.inform.emit(msg)
  7948. return "fail"
  7949. App.log.debug("open_script()")
  7950. with self.proc_container.new(_("Opening TCL Script...")):
  7951. # Object name
  7952. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7953. # Object creation
  7954. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7955. if ret_val == 'fail':
  7956. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7957. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7958. if ret_val == 'fail':
  7959. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7960. return 'fail'
  7961. # Register recent file
  7962. self.file_opened.emit("script", filename)
  7963. # GUI feedback
  7964. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7965. def open_config_file(self, filename, run_from_arg=None):
  7966. """
  7967. Loads a config file from the specified file.
  7968. :param filename: Name of the file from which to load.
  7969. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7970. :return: None
  7971. """
  7972. App.log.debug("Opening config file: " + filename)
  7973. if run_from_arg:
  7974. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7975. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7976. _("Opening FlatCAM Config file.")),
  7977. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7978. color=QtGui.QColor("gray"))
  7979. # # add the tab if it was closed
  7980. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7981. # # first clear previous text in text editor (if any)
  7982. # self.ui.text_editor_tab.code_editor.clear()
  7983. #
  7984. # # Switch plot_area to CNCJob tab
  7985. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7986. # close the Code editor if already open
  7987. if self.toggle_codeeditor:
  7988. self.on_toggle_code_editor()
  7989. self.on_toggle_code_editor()
  7990. try:
  7991. if filename:
  7992. f = QtCore.QFile(filename)
  7993. if f.open(QtCore.QIODevice.ReadOnly):
  7994. stream = QtCore.QTextStream(f)
  7995. code_edited = stream.readAll()
  7996. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7997. f.close()
  7998. except IOError:
  7999. App.log.error("Failed to open config file: %s" % filename)
  8000. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8001. (_("Failed to open config file"), filename))
  8002. return
  8003. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8004. """
  8005. Loads a project from the specified file.
  8006. 1) Loads and parses file
  8007. 2) Registers the file as recently opened.
  8008. 3) Calls on_file_new()
  8009. 4) Updates options
  8010. 5) Calls new_object() with the object's from_dict() as init method.
  8011. 6) Calls plot_all() if plot=True
  8012. :param filename: Name of the file from which to load.
  8013. :param run_from_arg: True if run for arguments
  8014. :param plot: If True plot all objects in the project
  8015. :param cli: Run from command line
  8016. :param from_tcl: True if run from Tcl Sehll
  8017. :return: None
  8018. """
  8019. App.log.debug("Opening project: " + filename)
  8020. # block autosaving while a project is loaded
  8021. self.block_autosave = True
  8022. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8023. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8024. if cli is None:
  8025. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8026. if run_from_arg:
  8027. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8028. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8029. _("Opening FlatCAM Project file.")),
  8030. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8031. color=QtGui.QColor("gray"))
  8032. # Open and parse an uncompressed Project file
  8033. try:
  8034. f = open(filename, 'r')
  8035. except IOError:
  8036. if from_tcl:
  8037. name = filename.split('/')[-1].split('\\')[-1]
  8038. filename = self.defaults['global_tcl_path'] + '/' + name
  8039. try:
  8040. f = open(filename, 'r')
  8041. except IOError:
  8042. log.error("Failed to open project file: %s" % filename)
  8043. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8044. return
  8045. else:
  8046. log.error("Failed to open project file: %s" % filename)
  8047. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8048. return
  8049. try:
  8050. d = json.load(f, object_hook=dict2obj)
  8051. except Exception as e:
  8052. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8053. (filename, str(e)))
  8054. f.close()
  8055. # Open and parse a compressed Project file
  8056. try:
  8057. with lzma.open(filename) as f:
  8058. file_content = f.read().decode('utf-8')
  8059. d = json.loads(file_content, object_hook=dict2obj)
  8060. except Exception as e:
  8061. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8062. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8063. return
  8064. # Clear the current project
  8065. # # NOT THREAD SAFE # ##
  8066. if run_from_arg is True:
  8067. pass
  8068. elif cli is True:
  8069. self.delete_selection_shape()
  8070. else:
  8071. self.on_file_new()
  8072. # Project options
  8073. self.options.update(d['options'])
  8074. self.project_filename = filename
  8075. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8076. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8077. if cli is None:
  8078. self.set_screen_units(self.options["units"])
  8079. # Re create objects
  8080. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8081. for obj in d['objs']:
  8082. try:
  8083. def obj_init(obj_inst, app_inst):
  8084. obj_inst.from_dict(obj)
  8085. App.log.debug("Recreating from opened project an %s object: %s" %
  8086. (obj['kind'].capitalize(), obj['options']['name']))
  8087. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8088. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8089. if cli is None:
  8090. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8091. obj['kind'].upper(),
  8092. obj['options']['name']
  8093. )
  8094. )
  8095. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8096. except Exception as e:
  8097. print('App.open_project() --> ' + str(e))
  8098. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8099. self.should_we_save = False
  8100. self.file_opened.emit("project", filename)
  8101. # restore autosaving after a project was loaded
  8102. self.block_autosave = False
  8103. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8104. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8105. if cli is None:
  8106. self.set_ui_title(name=self.project_filename)
  8107. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8108. def plot_all(self, fit_view=True, use_thread=True):
  8109. """
  8110. Re-generates all plots from all objects.
  8111. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8112. :param use_thread: if True will use threading for plotting the objects
  8113. :return: None
  8114. """
  8115. self.log.debug("Plot_all()")
  8116. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8117. for plot_obj in self.collection.get_list():
  8118. def worker_task(obj):
  8119. with self.proc_container.new("Plotting"):
  8120. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8121. if fit_view is True:
  8122. self.object_plotted.emit(obj)
  8123. if use_thread is True:
  8124. # Send to worker
  8125. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8126. else:
  8127. worker_task(plot_obj)
  8128. def register_folder(self, filename):
  8129. """
  8130. Register the last folder used by the app to open something
  8131. :param filename: the last folder is extracted from the filename
  8132. :return: None
  8133. """
  8134. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8135. def register_save_folder(self, filename):
  8136. """
  8137. Register the last folder used by the app to save something
  8138. :param filename: the last folder is extracted from the filename
  8139. :return: None
  8140. """
  8141. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8142. # def set_progress_bar(self, percentage, text=""):
  8143. # """
  8144. # Set a progress bar to a value (percentage)
  8145. #
  8146. # :param percentage: Value set to the progressbar
  8147. # :param text: Not used
  8148. # :return: None
  8149. # """
  8150. # self.ui.progress_bar.setValue(int(percentage))
  8151. def setup_recent_items(self):
  8152. """
  8153. Setup a dictionary with the recent files accessed, organized by type
  8154. :return:
  8155. """
  8156. icons = {
  8157. "gerber": self.resource_location + "/flatcam_icon16.png",
  8158. "excellon": self.resource_location + "/drill16.png",
  8159. 'geometry': self.resource_location + "/geometry16.png",
  8160. "cncjob": self.resource_location + "/cnc16.png",
  8161. "script": self.resource_location + "/script_new24.png",
  8162. "document": self.resource_location + "/notes16_1.png",
  8163. "project": self.resource_location + "/project16.png",
  8164. "svg": self.resource_location + "/geometry16.png",
  8165. "dxf": self.resource_location + "/dxf16.png",
  8166. "pdf": self.resource_location + "/pdf32.png",
  8167. "image": self.resource_location + "/image16.png"
  8168. }
  8169. try:
  8170. image_opener = self.image_tool.import_image
  8171. except AttributeError:
  8172. image_opener = None
  8173. openers = {
  8174. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8175. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8176. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8177. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8178. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8179. "document": None,
  8180. 'project': self.open_project,
  8181. 'svg': self.import_svg,
  8182. 'dxf': self.import_dxf,
  8183. 'image': image_opener,
  8184. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8185. }
  8186. # Open recent file for files
  8187. try:
  8188. f = open(self.data_path + '/recent.json')
  8189. except IOError:
  8190. App.log.error("Failed to load recent item list.")
  8191. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8192. return
  8193. try:
  8194. self.recent = json.load(f)
  8195. except json.errors.JSONDecodeError:
  8196. App.log.error("Failed to parse recent item list.")
  8197. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8198. f.close()
  8199. return
  8200. f.close()
  8201. # Open recent file for projects
  8202. try:
  8203. fp = open(self.data_path + '/recent_projects.json')
  8204. except IOError:
  8205. App.log.error("Failed to load recent project item list.")
  8206. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8207. return
  8208. try:
  8209. self.recent_projects = json.load(fp)
  8210. except json.errors.JSONDecodeError:
  8211. App.log.error("Failed to parse recent project item list.")
  8212. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8213. fp.close()
  8214. return
  8215. fp.close()
  8216. # Closure needed to create callbacks in a loop.
  8217. # Otherwise late binding occurs.
  8218. def make_callback(func, fname):
  8219. def opener():
  8220. func(fname)
  8221. return opener
  8222. def reset_recent_files():
  8223. # Reset menu
  8224. self.ui.recent.clear()
  8225. self.recent = []
  8226. try:
  8227. ff = open(self.data_path + '/recent.json', 'w')
  8228. except IOError:
  8229. App.log.error("Failed to open recent items file for writing.")
  8230. return
  8231. json.dump(self.recent, ff)
  8232. def reset_recent_projects():
  8233. # Reset menu
  8234. self.ui.recent_projects.clear()
  8235. self.recent_projects = []
  8236. try:
  8237. frp = open(self.data_path + '/recent_projects.json', 'w')
  8238. except IOError:
  8239. App.log.error("Failed to open recent projects items file for writing.")
  8240. return
  8241. json.dump(self.recent, frp)
  8242. # Reset menu
  8243. self.ui.recent.clear()
  8244. self.ui.recent_projects.clear()
  8245. # Create menu items for projects
  8246. for recent in self.recent_projects:
  8247. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8248. if recent['kind'] == 'project':
  8249. try:
  8250. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8251. # Attach callback
  8252. o = make_callback(openers[recent["kind"]], recent['filename'])
  8253. action.triggered.connect(o)
  8254. self.ui.recent_projects.addAction(action)
  8255. except KeyError:
  8256. App.log.error("Unsupported file type: %s" % recent["kind"])
  8257. # Last action in Recent Files menu is one that Clear the content
  8258. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8259. (_("Clear Recent projects")), self)
  8260. clear_action_proj.triggered.connect(reset_recent_projects)
  8261. self.ui.recent_projects.addSeparator()
  8262. self.ui.recent_projects.addAction(clear_action_proj)
  8263. # Create menu items for files
  8264. for recent in self.recent:
  8265. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8266. if recent['kind'] != 'project':
  8267. try:
  8268. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8269. # Attach callback
  8270. o = make_callback(openers[recent["kind"]], recent['filename'])
  8271. action.triggered.connect(o)
  8272. self.ui.recent.addAction(action)
  8273. except KeyError:
  8274. App.log.error("Unsupported file type: %s" % recent["kind"])
  8275. # Last action in Recent Files menu is one that Clear the content
  8276. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8277. (_("Clear Recent files")), self)
  8278. clear_action.triggered.connect(reset_recent_files)
  8279. self.ui.recent.addSeparator()
  8280. self.ui.recent.addAction(clear_action)
  8281. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8282. # self.ui.menufilerecent.set_submenu(recent_menu)
  8283. # recent_menu.show_all()
  8284. # self.ui.recent.show()
  8285. self.log.debug("Recent items list has been populated.")
  8286. def setup_component_editor(self):
  8287. """
  8288. Default text for the Selected tab when is not taken by the Object UI.
  8289. :return:
  8290. """
  8291. # label = QtWidgets.QLabel("Choose an item from Project")
  8292. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8293. sel_title = QtWidgets.QTextEdit(
  8294. _('<b>Shortcut Key List</b>'))
  8295. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8296. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8297. f_settings = QSettings("Open Source", "FlatCAM")
  8298. if f_settings.contains("notebook_font_size"):
  8299. fsize = f_settings.value('notebook_font_size', type=int)
  8300. else:
  8301. fsize = 12
  8302. tsize = fsize + int(fsize / 2)
  8303. # selected_text = (_('''
  8304. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8305. # </p>
  8306. #
  8307. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8308. # The normal flow when working in FlatCAM is the following:</span></p>
  8309. #
  8310. # <ol>
  8311. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8312. # file into
  8313. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8314. # even dragging and dropping the files on the GUI.<br />
  8315. # <br />
  8316. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8317. # drop of the
  8318. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8319. # &nbsp;</li>
  8320. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8321. # and then
  8322. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8323. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8324. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8325. # <br />
  8326. # If the selection of the object is done on the canvas by single click instead, and the
  8327. # <strong>SELECTED TAB</strong>
  8328. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8329. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8330. # it even if it was out of focus.<br />
  8331. # <br />
  8332. # You can change the parameters in this screen and the flow direction is like this:<br />
  8333. # <br />
  8334. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8335. # <strong> Geometry Object
  8336. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8337. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8338. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8339. # </ol>
  8340. #
  8341. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8342. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8343. # <strong>F3</strong>.</span></p>
  8344. #
  8345. # ''').format(fsize=fsize, tsize=tsize))
  8346. selected_text = '''
  8347. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8348. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8349. {s1}</span></p>
  8350. <ol>
  8351. <li><span style="font-size:{fsize}px">{s2}<br />
  8352. <br />
  8353. {s3}</span><br />
  8354. &nbsp;</li>
  8355. <li><span style="font-size:{fsize}px">{s4}<br />
  8356. &nbsp;</li>
  8357. <br />
  8358. <li><span style="font-size:{fsize}px">{s5}<br />
  8359. &nbsp;</li>
  8360. <br />
  8361. <li><span style="font-size:{fsize}px">{s6}<br />
  8362. <br />
  8363. {s7}</span></li>
  8364. </ol>
  8365. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8366. '''.format(
  8367. title=_("Selected Tab - Choose an Item from Project Tab"),
  8368. subtitle=_("Details"),
  8369. s1=_("The normal flow when working in FlatCAM is the following:"),
  8370. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8371. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8372. "files on the GUI."),
  8373. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8374. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8375. "actions offered within the app."),
  8376. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8377. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8378. "SELECTED TAB will be updated with the object properties according to its kind: "
  8379. "Gerber, Excellon, Geometry or CNCJob object."),
  8380. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8381. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8382. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8383. "the SELECTED TAB and populate it even if it was out of focus."),
  8384. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8385. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8386. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8387. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8388. "(again, done in SELECTED TAB) --> Save GCode."),
  8389. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8390. "or through its own key shortcut: <b>F3</b>."),
  8391. tsize=tsize,
  8392. fsize=fsize
  8393. )
  8394. sel_title.setText(selected_text)
  8395. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8396. self.ui.selected_scroll_area.setWidget(sel_title)
  8397. def setup_obj_classes(self):
  8398. """
  8399. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8400. class.
  8401. :return: None
  8402. """
  8403. FlatCAMObj.app = self
  8404. ObjectCollection.app = self
  8405. Gerber.app = self
  8406. Excellon.app = self
  8407. Geometry.app = self
  8408. CNCjob.app = self
  8409. FCProcess.app = self
  8410. FCProcessContainer.app = self
  8411. OptionsGroupUI.app = self
  8412. def version_check(self):
  8413. """
  8414. Checks for the latest version of the program. Alerts the
  8415. user if theirs is outdated. This method is meant to be run
  8416. in a separate thread.
  8417. :return: None
  8418. """
  8419. self.log.debug("version_check()")
  8420. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8421. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8422. App.version_url,
  8423. str(self.defaults['global_serial']),
  8424. str(self.version),
  8425. str(self.os),
  8426. urllib.parse.urlencode(self.defaults["global_stats"])
  8427. )
  8428. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8429. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8430. # urllib.parse.urlencode(self.defaults["global_stats"])
  8431. else:
  8432. # no_stats dict; just so it won't break things on website
  8433. no_ststs_dict = {}
  8434. no_ststs_dict["global_ststs"] = {}
  8435. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8436. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8437. App.log.debug("Checking for updates @ %s" % full_url)
  8438. # ## Get the data
  8439. try:
  8440. f = urllib.request.urlopen(full_url)
  8441. except Exception:
  8442. # App.log.warning("Failed checking for latest version. Could not connect.")
  8443. self.log.warning("Failed checking for latest version. Could not connect.")
  8444. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8445. return
  8446. try:
  8447. data = json.load(f)
  8448. except Exception as e:
  8449. App.log.error("Could not parse information about latest version.")
  8450. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8451. App.log.debug("json.load(): %s" % str(e))
  8452. f.close()
  8453. return
  8454. f.close()
  8455. # ## Latest version?
  8456. if self.version >= data["version"]:
  8457. App.log.debug("FlatCAM is up to date!")
  8458. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8459. return
  8460. App.log.debug("Newer version available.")
  8461. self.message.emit(
  8462. _("Newer Version Available"),
  8463. '%s<br><br>><b>%s</b><br>%s' % (
  8464. _("There is a newer version of FlatCAM available for download:"),
  8465. str(data["name"]),
  8466. str(data["message"])
  8467. ),
  8468. _("info")
  8469. )
  8470. def on_plotcanvas_setup(self, container=None):
  8471. """
  8472. This is doing the setup for the plot area (canvas).
  8473. :param container: QT Widget where to install the canvas
  8474. :return: None
  8475. """
  8476. if container:
  8477. plot_container = container
  8478. else:
  8479. plot_container = self.ui.right_layout
  8480. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8481. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8482. self.is_legacy = True
  8483. self.defaults["global_graphic_engine"] = "2D"
  8484. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8485. else:
  8486. try:
  8487. self.plotcanvas = PlotCanvas(plot_container, self)
  8488. except Exception as er:
  8489. msg_txt = traceback.format_exc()
  8490. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8491. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8492. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8493. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8494. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8495. msg += msg_txt
  8496. self.inform.emit(msg)
  8497. return 'fail'
  8498. # So it can receive key presses
  8499. self.plotcanvas.native.setFocus()
  8500. if self.is_legacy is False:
  8501. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8502. # Set the mouse button for panning
  8503. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8504. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8505. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8506. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8507. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8508. # Keys over plot enabled
  8509. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8510. if self.defaults['global_cursor_type'] == 'small':
  8511. self.app_cursor = self.plotcanvas.new_cursor()
  8512. else:
  8513. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8514. if self.ui.grid_snap_btn.isChecked():
  8515. self.app_cursor.enabled = True
  8516. else:
  8517. self.app_cursor.enabled = False
  8518. if self.is_legacy is False:
  8519. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8520. else:
  8521. # will use the default Matplotlib axes
  8522. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8523. def on_zoom_fit(self, event):
  8524. """
  8525. Callback for zoom-fit request. This can be either from the corresponding
  8526. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8527. with axes limits from the geometry bounds of all objects.
  8528. :param event: Ignored.
  8529. :return: None
  8530. """
  8531. if self.is_legacy is False:
  8532. self.plotcanvas.fit_view()
  8533. else:
  8534. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8535. width = xmax - xmin
  8536. height = ymax - ymin
  8537. xmin -= 0.05 * width
  8538. xmax += 0.05 * width
  8539. ymin -= 0.05 * height
  8540. ymax += 0.05 * height
  8541. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8542. def on_zoom_in(self):
  8543. """
  8544. Callback for zoom-in request.
  8545. :return:
  8546. """
  8547. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8548. def on_zoom_out(self):
  8549. """
  8550. Callback for zoom-out request.
  8551. :return:
  8552. """
  8553. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8554. def disable_all_plots(self):
  8555. self.defaults.report_usage("disable_all_plots()")
  8556. self.disable_plots(self.collection.get_list())
  8557. self.inform.emit('[success] %s' %
  8558. _("All plots disabled."))
  8559. def disable_other_plots(self):
  8560. self.defaults.report_usage("disable_other_plots()")
  8561. self.disable_plots(self.collection.get_non_selected())
  8562. self.inform.emit('[success] %s' %
  8563. _("All non selected plots disabled."))
  8564. def enable_all_plots(self):
  8565. self.defaults.report_usage("enable_all_plots()")
  8566. self.enable_plots(self.collection.get_list())
  8567. self.inform.emit('[success] %s' %
  8568. _("All plots enabled."))
  8569. def on_enable_sel_plots(self):
  8570. log.debug("App.on_enable_sel_plot()")
  8571. object_list = self.collection.get_selected()
  8572. self.enable_plots(objects=object_list)
  8573. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8574. def on_disable_sel_plots(self):
  8575. log.debug("App.on_disable_sel_plot()")
  8576. # self.inform.emit(_("Disabling plots ..."))
  8577. object_list = self.collection.get_selected()
  8578. self.disable_plots(objects=object_list)
  8579. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8580. def enable_plots(self, objects):
  8581. """
  8582. Enable plots
  8583. :param objects: list of Objects to be enabled
  8584. :return:
  8585. """
  8586. log.debug("Enabling plots ...")
  8587. # self.inform.emit(_("Working ..."))
  8588. for obj in objects:
  8589. if obj.options['plot'] is False:
  8590. obj.options.set_change_callback(lambda x: None)
  8591. obj.options['plot'] = True
  8592. try:
  8593. # only the Gerber obj has on_plot_cb_click() method
  8594. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8595. # disable this cb while disconnected,
  8596. # in case the operation takes time the user is not allowed to change it
  8597. obj.ui.plot_cb.setDisabled(True)
  8598. except AttributeError:
  8599. pass
  8600. obj.set_form_item("plot")
  8601. try:
  8602. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8603. obj.ui.plot_cb.setDisabled(False)
  8604. except AttributeError:
  8605. pass
  8606. obj.options.set_change_callback(obj.on_options_change)
  8607. def worker_task(objs):
  8608. with self.proc_container.new(_("Enabling plots ...")):
  8609. for plot_obj in objs:
  8610. # obj.options['plot'] = True
  8611. if isinstance(plot_obj, CNCJobObject):
  8612. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8613. else:
  8614. plot_obj.plot(visible=True)
  8615. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8616. # self.plots_updated.emit()
  8617. def disable_plots(self, objects):
  8618. """
  8619. Disables plots
  8620. :param objects: list of Objects to be disabled
  8621. :return:
  8622. """
  8623. # if no objects selected then do nothing
  8624. if not self.collection.get_selected():
  8625. return
  8626. log.debug("Disabling plots ...")
  8627. # self.inform.emit(_("Working ..."))
  8628. for obj in objects:
  8629. if obj.options['plot'] is True:
  8630. obj.options.set_change_callback(lambda x: None)
  8631. obj.options['plot'] = False
  8632. try:
  8633. # only the Gerber obj has on_plot_cb_click() method
  8634. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8635. obj.ui.plot_cb.setDisabled(True)
  8636. except AttributeError:
  8637. pass
  8638. obj.set_form_item("plot")
  8639. try:
  8640. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8641. obj.ui.plot_cb.setDisabled(False)
  8642. except AttributeError:
  8643. pass
  8644. obj.options.set_change_callback(obj.on_options_change)
  8645. try:
  8646. self.delete_selection_shape()
  8647. except Exception as e:
  8648. log.debug("App.disable_plots() --> %s" % str(e))
  8649. # self.plots_updated.emit()
  8650. def worker_task(objs):
  8651. with self.proc_container.new(_("Disabling plots ...")):
  8652. for plot_obj in objs:
  8653. # obj.options['plot'] = True
  8654. if isinstance(plot_obj, CNCJobObject):
  8655. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8656. else:
  8657. plot_obj.plot(visible=False)
  8658. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8659. def toggle_plots(self, objects):
  8660. """
  8661. Toggle plots visibility
  8662. :param objects: list of Objects for which to be toggled the visibility
  8663. :return: None
  8664. """
  8665. # if no objects selected then do nothing
  8666. if not self.collection.get_selected():
  8667. return
  8668. log.debug("Toggling plots ...")
  8669. self.inform.emit(_("Working ..."))
  8670. for obj in objects:
  8671. if obj.options['plot'] is False:
  8672. obj.options['plot'] = True
  8673. else:
  8674. obj.options['plot'] = False
  8675. self.plots_updated.emit()
  8676. def clear_plots(self):
  8677. """
  8678. Clear the plots
  8679. :return: None
  8680. """
  8681. objects = self.collection.get_list()
  8682. for obj in objects:
  8683. obj.clear(obj == objects[-1])
  8684. # Clear pool to free memory
  8685. self.clear_pool()
  8686. def on_set_color_action_triggered(self):
  8687. """
  8688. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8689. :return:
  8690. """
  8691. new_color = self.defaults['gerber_plot_fill']
  8692. clicked_action = self.sender()
  8693. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8694. act_name = clicked_action.text()
  8695. sel_obj_list = self.collection.get_selected()
  8696. if not sel_obj_list:
  8697. return
  8698. # a default value, I just chose this one
  8699. alpha_level = 'BF'
  8700. for sel_obj in sel_obj_list:
  8701. if sel_obj.kind == 'excellon':
  8702. alpha_level = str(hex(
  8703. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8704. elif sel_obj.kind == 'gerber':
  8705. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8706. elif sel_obj.kind == 'geometry':
  8707. alpha_level = 'FF'
  8708. else:
  8709. log.debug(
  8710. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8711. continue
  8712. sel_obj.alpha_level = alpha_level
  8713. if act_name == _('Red'):
  8714. new_color = '#FF0000' + alpha_level
  8715. if act_name == _('Blue'):
  8716. new_color = '#0000FF' + alpha_level
  8717. if act_name == _('Yellow'):
  8718. new_color = '#FFDF00' + alpha_level
  8719. if act_name == _('Green'):
  8720. new_color = '#00FF00' + alpha_level
  8721. if act_name == _('Purple'):
  8722. new_color = '#FF00FF' + alpha_level
  8723. if act_name == _('Brown'):
  8724. new_color = '#A52A2A' + alpha_level
  8725. if act_name == _('White'):
  8726. new_color = '#FFFFFF' + alpha_level
  8727. if act_name == _('Black'):
  8728. new_color = '#000000' + alpha_level
  8729. if act_name == _('Custom'):
  8730. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8731. c_dialog = QtWidgets.QColorDialog()
  8732. plot_fill_color = c_dialog.getColor(initial=new_color)
  8733. if plot_fill_color.isValid() is False:
  8734. return
  8735. new_color = str(plot_fill_color.name()) + alpha_level
  8736. if act_name == _("Default"):
  8737. for sel_obj in sel_obj_list:
  8738. if sel_obj.kind == 'excellon':
  8739. new_color = self.defaults['excellon_plot_fill']
  8740. new_line_color = self.defaults['excellon_plot_line']
  8741. elif sel_obj.kind == 'gerber':
  8742. new_color = self.defaults['gerber_plot_fill']
  8743. new_line_color = self.defaults['gerber_plot_line']
  8744. elif sel_obj.kind == 'geometry':
  8745. new_color = self.defaults['geometry_plot_line']
  8746. new_line_color = self.defaults['geometry_plot_line']
  8747. else:
  8748. log.debug(
  8749. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8750. continue
  8751. sel_obj.fill_color = new_color
  8752. sel_obj.outline_color = new_line_color
  8753. sel_obj.shapes.redraw(
  8754. update_colors=(new_color, new_line_color)
  8755. )
  8756. return
  8757. if act_name == _("Opacity"):
  8758. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8759. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8760. if ok_button:
  8761. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8762. for sel_obj in sel_obj_list:
  8763. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8764. sel_obj.shapes.redraw(
  8765. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8766. )
  8767. return
  8768. new_line_color = color_variant(new_color[:7], 0.7)
  8769. if act_name == _("White"):
  8770. new_line_color = color_variant("#dedede", 0.7)
  8771. for sel_obj in sel_obj_list:
  8772. sel_obj.fill_color = new_color
  8773. sel_obj.outline_color = new_line_color
  8774. sel_obj.shapes.redraw(
  8775. update_colors=(new_color, new_line_color)
  8776. )
  8777. def generate_cnc_job(self, objects):
  8778. """
  8779. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8780. :param objects: Selected objects in the Project Tab
  8781. :return:
  8782. """
  8783. self.defaults.report_usage("generate_cnc_job()")
  8784. # for obj in objects:
  8785. # obj.generatecncjob()
  8786. for obj in objects:
  8787. obj.on_generatecnc_button_click()
  8788. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8789. """
  8790. Saves the current project to the specified file.
  8791. :param filename: Name of the file in which to save.
  8792. :type filename: str
  8793. :param quit_action: if the project saving will be followed by an app quit; boolean
  8794. :param silent: if True will not display status messages
  8795. :param from_tcl True is run from Tcl Shell
  8796. :return: None
  8797. """
  8798. self.log.debug("save_project()")
  8799. self.save_in_progress = True
  8800. with self.proc_container.new(_("Saving FlatCAM Project")):
  8801. # Capture the latest changes
  8802. # Current object
  8803. try:
  8804. current_object = self.collection.get_active()
  8805. if current_object:
  8806. current_object.read_form()
  8807. except Exception as e:
  8808. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8809. pass
  8810. # Serialize the whole project
  8811. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8812. "options": self.options,
  8813. "version": self.version}
  8814. if self.defaults["global_save_compressed"] is True:
  8815. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8816. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8817. # # Write
  8818. f.write(g)
  8819. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8820. else:
  8821. # Open file
  8822. try:
  8823. f = open(filename, 'w')
  8824. except IOError:
  8825. App.log.error("Failed to open file for saving: %s", filename)
  8826. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8827. return
  8828. # Write
  8829. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8830. f.close()
  8831. # verification of the saved project
  8832. # Open and parse
  8833. try:
  8834. saved_f = open(filename, 'r')
  8835. except IOError:
  8836. if silent is False:
  8837. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8838. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8839. return
  8840. try:
  8841. saved_d = json.load(saved_f, object_hook=dict2obj)
  8842. except Exception:
  8843. if silent is False:
  8844. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8845. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8846. f.close()
  8847. return
  8848. saved_f.close()
  8849. if silent is False:
  8850. if 'version' in saved_d:
  8851. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8852. else:
  8853. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8854. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8855. tb_settings = QSettings("Open Source", "FlatCAM")
  8856. lock_state = self.ui.lock_action.isChecked()
  8857. tb_settings.setValue('toolbar_lock', lock_state)
  8858. # This will write the setting to the platform specific storage.
  8859. del tb_settings
  8860. # if quit:
  8861. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8862. # t.start()
  8863. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8864. def start_delayed_quit(self, delay, filename, should_quit=None):
  8865. """
  8866. :param delay: period of checking if project file size is more than zero; in seconds
  8867. :param filename: the name of the project file to be checked periodically for size more than zero
  8868. :param should_quit: if the task finished will be followed by an app quit; boolean
  8869. :return:
  8870. """
  8871. to_quit = should_quit
  8872. self.save_timer = QtCore.QTimer()
  8873. self.save_timer.setInterval(delay)
  8874. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8875. self.save_timer.start()
  8876. def check_project_file_size(self, filename, should_quit=None):
  8877. """
  8878. :param filename: the name of the project file to be checked periodically for size more than zero
  8879. :param should_quit: will quit the app if True; boolean
  8880. :return:
  8881. """
  8882. try:
  8883. if os.stat(filename).st_size > 0:
  8884. self.save_in_progress = False
  8885. self.save_timer.stop()
  8886. if should_quit:
  8887. self.app_quit.emit()
  8888. except Exception:
  8889. traceback.print_exc()
  8890. def save_project_auto(self):
  8891. """
  8892. Called periodically to save the project.
  8893. 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
  8894. # progress.
  8895. :return:
  8896. """
  8897. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8898. self.on_file_saveproject()
  8899. def save_project_auto_update(self):
  8900. """
  8901. Update the auto save time interval value.
  8902. :return:
  8903. """
  8904. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8905. try:
  8906. if self.autosave_timer.isActive():
  8907. self.autosave_timer.stop()
  8908. except Exception:
  8909. pass
  8910. if self.defaults['global_autosave'] is True:
  8911. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8912. self.autosave_timer.start()
  8913. def on_options_app2project(self):
  8914. """
  8915. Callback for Options->Transfer Options->App=>Project. Copies options
  8916. from application defaults to project defaults.
  8917. :return: None
  8918. """
  8919. self.defaults.report_usage("on_options_app2project")
  8920. self.preferencesUiManager.defaults_read_form()
  8921. self.options.update(self.defaults)
  8922. def toggle_shell(self):
  8923. """
  8924. Toggle shell: if is visible close it, if it is closed then open it
  8925. :return: None
  8926. """
  8927. self.defaults.report_usage("toggle_shell()")
  8928. if self.ui.shell_dock.isVisible():
  8929. self.ui.shell_dock.hide()
  8930. self.plotcanvas.native.setFocus()
  8931. else:
  8932. self.ui.shell_dock.show()
  8933. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8934. # self.shell._edit.setFocus()
  8935. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8936. # HACK - simulate a mouse click - alternative
  8937. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8938. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8939. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8940. # no_km)
  8941. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8942. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8943. # no_km)
  8944. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8945. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8946. """
  8947. Shows a message on the FlatCAM Shell
  8948. :param msg: Message to display.
  8949. :param show: Opens the shell.
  8950. :param error: Shows the message as an error.
  8951. :param warning: Shows the message as an warning.
  8952. :param success: Shows the message as an success.
  8953. :param selected: Indicate that something was selected on canvas
  8954. :return: None
  8955. """
  8956. if show:
  8957. self.ui.shell_dock.show()
  8958. try:
  8959. if error:
  8960. self.shell.append_error(msg + "\n")
  8961. elif warning:
  8962. self.shell.append_warning(msg + "\n")
  8963. elif success:
  8964. self.shell.append_success(msg + "\n")
  8965. elif selected:
  8966. self.shell.append_selected(msg + "\n")
  8967. else:
  8968. self.shell.append_output(msg + "\n")
  8969. except AttributeError:
  8970. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8971. class ArgsThread(QtCore.QObject):
  8972. open_signal = pyqtSignal(list)
  8973. start = pyqtSignal()
  8974. if sys.platform == 'win32':
  8975. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8976. else:
  8977. address = ('/tmp/testipc', 'AF_UNIX')
  8978. def __init__(self):
  8979. super(ArgsThread, self).__init__()
  8980. self.listener = None
  8981. self.thread_exit = False
  8982. self.start.connect(self.run)
  8983. def my_loop(self, address):
  8984. try:
  8985. self.listener = Listener(*address)
  8986. while self.thread_exit is False:
  8987. conn = self.listener.accept()
  8988. self.serve(conn)
  8989. except socket.error:
  8990. try:
  8991. conn = Client(*address)
  8992. conn.send(sys.argv)
  8993. conn.send('close')
  8994. # close the current instance only if there are args
  8995. if len(sys.argv) > 1:
  8996. try:
  8997. self.listener.close()
  8998. except Exception:
  8999. pass
  9000. sys.exit()
  9001. except ConnectionRefusedError:
  9002. if sys.platform == 'win32':
  9003. pass
  9004. else:
  9005. os.system('rm /tmp/testipc')
  9006. self.listener = Listener(*address)
  9007. while True:
  9008. conn = self.listener.accept()
  9009. self.serve(conn)
  9010. def serve(self, conn):
  9011. while self.thread_exit is False:
  9012. msg = conn.recv()
  9013. if msg == 'close':
  9014. break
  9015. self.open_signal.emit(msg)
  9016. conn.close()
  9017. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9018. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9019. @pyqtSlot()
  9020. def run(self):
  9021. self.my_loop(self.address)
  9022. # end of file