FlatCAMApp.py 484 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from PyQt5.QtCore import pyqtSlot, Qt
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Diverse
  37. from FlatCAMCommon import LoudDict, color_variant, ExclusionAreas
  38. from FlatCAMBookmark import BookmarkManager
  39. from FlatCAMDB import ToolsDB2
  40. from vispy.gloo.util import _screenshot
  41. from vispy.io import write_png
  42. # FlatCAM Objects
  43. from defaults import FlatCAMDefaults
  44. from flatcamGUI.preferences.OptionsGroupUI import OptionsGroupUI
  45. from flatcamGUI.preferences.PreferencesUIManager import PreferencesUIManager
  46. from flatcamObjects.ObjectCollection import *
  47. from flatcamObjects.FlatCAMObj import FlatCAMObj
  48. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  49. from flatcamObjects.FlatCAMDocument import DocumentObject
  50. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  51. from flatcamObjects.FlatCAMGeometry import GeometryObject
  52. from flatcamObjects.FlatCAMGerber import GerberObject
  53. from flatcamObjects.FlatCAMScript import ScriptObject
  54. # FlatCAM Parsing files
  55. from flatcamParsers.ParseExcellon import Excellon
  56. from flatcamParsers.ParseGerber import Gerber
  57. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  58. # FlatCAM GUI
  59. from flatcamGUI.PlotCanvas import *
  60. from flatcamGUI.PlotCanvasLegacy import *
  61. from flatcamGUI.FlatCAMGUI import *
  62. from flatcamGUI.GUIElements import FCFileSaveDialog
  63. # FlatCAM Pre-processors
  64. from FlatCAMPostProc import load_preprocessors
  65. # FlatCAM Editors
  66. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  67. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  68. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  69. from flatcamEditors.FlatCAMTextEditor import TextEditor
  70. from flatcamParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from FlatCAMProcess import *
  73. from FlatCAMWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from flatcamTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import FlatCAMTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = 8.993
  138. version_date = "2020/08/01"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by:
  169. # * App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. plots_updated = QtCore.pyqtSignal()
  188. # Emitted by new_object() and passes the new object as argument, plot flag.
  189. # on_object_created() adds the object to the collection, plots on appropriate flag
  190. # and emits new_object_available.
  191. object_created = QtCore.pyqtSignal(object, bool, bool)
  192. # Emitted when a object has been changed (like scaled, mirrored)
  193. object_changed = QtCore.pyqtSignal(object)
  194. # Emitted after object has been plotted.
  195. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  196. object_plotted = QtCore.pyqtSignal(object)
  197. # Emitted when a new object has been added or deleted from/to the collection
  198. object_status_changed = QtCore.pyqtSignal(object, str, str)
  199. message = QtCore.pyqtSignal(str, str, str)
  200. # Emmited when shell command is finished(one command only)
  201. shell_command_finished = QtCore.pyqtSignal(object)
  202. # Emitted when multiprocess pool has been recreated
  203. pool_recreated = QtCore.pyqtSignal(object)
  204. # Emitted when an unhandled exception happens
  205. # in the worker task.
  206. thread_exception = QtCore.pyqtSignal(object)
  207. # used to signal that there are arguments for the app
  208. args_at_startup = QtCore.pyqtSignal(list)
  209. # a reusable signal to replot a list of objects
  210. # should be disconnected after use so it can be reused
  211. replot_signal = pyqtSignal(list)
  212. # signal emitted when jumping
  213. jump_signal = pyqtSignal(tuple)
  214. # signal emitted when jumping
  215. locate_signal = pyqtSignal(tuple, str)
  216. # close app signal
  217. close_app_signal = pyqtSignal()
  218. # will perform the cleanup operation after a Graceful Exit
  219. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  220. # graphic residues behind
  221. cleanup = pyqtSignal()
  222. def __init__(self, user_defaults=True):
  223. """
  224. Starts the application.
  225. :return: app
  226. :rtype: App
  227. """
  228. super().__init__()
  229. App.log.info("FlatCAM Starting...")
  230. self.main_thread = QtWidgets.QApplication.instance().thread()
  231. # ############################################################################################################
  232. # ################# Setup the listening thread for another instance launching with args ######################
  233. # ############################################################################################################
  234. if sys.platform == 'win32' or sys.platform == 'linux':
  235. # make sure the thread is stored by using a self. otherwise it's garbage collected
  236. self.th = QtCore.QThread()
  237. self.th.start(priority=QtCore.QThread.LowestPriority)
  238. self.new_launch = ArgsThread()
  239. self.new_launch.open_signal[list].connect(self.on_startup_args)
  240. self.new_launch.moveToThread(self.th)
  241. self.new_launch.start.emit()
  242. # ############################################################################################################
  243. # # ######################################## OS-specific #####################################################
  244. # ############################################################################################################
  245. portable = False
  246. # Folder for user settings.
  247. if sys.platform == 'win32':
  248. if platform.architecture()[0] == '32bit':
  249. App.log.debug("Win32!")
  250. else:
  251. App.log.debug("Win64!")
  252. # #######################################################################################################
  253. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  254. # #######################################################################################################
  255. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  256. try:
  257. with open(config_file, 'r'):
  258. pass
  259. except FileNotFoundError:
  260. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  261. try:
  262. with open(config_file, 'r') as f:
  263. try:
  264. for line in f:
  265. param = str(line).replace('\n', '').rpartition('=')
  266. if param[0] == 'portable':
  267. try:
  268. portable = eval(param[2])
  269. except NameError:
  270. portable = False
  271. if param[0] == 'headless':
  272. if param[2].lower() == 'true':
  273. self.cmd_line_headless = 1
  274. else:
  275. self.cmd_line_headless = None
  276. except Exception as e:
  277. log.debug('App.__init__() -->%s' % str(e))
  278. return
  279. except FileNotFoundError as e:
  280. log.debug(str(e))
  281. pass
  282. if portable is False:
  283. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  284. else:
  285. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  286. self.os = 'windows'
  287. else: # Linux/Unix/MacOS
  288. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  289. self.os = 'unix'
  290. # ############################################################################################################
  291. # ################################# Setup folders and files ##################################################
  292. # ############################################################################################################
  293. if not os.path.exists(self.data_path):
  294. os.makedirs(self.data_path)
  295. App.log.debug('Created data folder: ' + self.data_path)
  296. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  297. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  298. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  299. if not os.path.exists(self.preprocessorpaths):
  300. os.makedirs(self.preprocessorpaths)
  301. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  302. # create geo_tools_db.FlatDB file if there is none
  303. try:
  304. f = open(self.data_path + '/geo_tools_db.FlatDB')
  305. f.close()
  306. except IOError:
  307. App.log.debug('Creating empty geo_tool_db.FlatDB')
  308. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  309. json.dump({}, f)
  310. f.close()
  311. # create current_defaults.FlatConfig file if there is none
  312. try:
  313. f = open(self.data_path + '/current_defaults.FlatConfig')
  314. f.close()
  315. except IOError:
  316. App.log.debug('Creating empty current_defaults.FlatConfig')
  317. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  318. json.dump({}, f)
  319. f.close()
  320. # Write factory_defaults.FlatConfig file to disk
  321. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  322. # create a recent files json file if there is none
  323. try:
  324. f = open(self.data_path + '/recent.json')
  325. f.close()
  326. except IOError:
  327. App.log.debug('Creating empty recent.json')
  328. f = open(self.data_path + '/recent.json', 'w')
  329. json.dump([], f)
  330. f.close()
  331. # create a recent projects json file if there is none
  332. try:
  333. fp = open(self.data_path + '/recent_projects.json')
  334. fp.close()
  335. except IOError:
  336. App.log.debug('Creating empty recent_projects.json')
  337. fp = open(self.data_path + '/recent_projects.json', 'w')
  338. json.dump([], fp)
  339. fp.close()
  340. # Application directory. CHDIR to it. Otherwise, trying to load
  341. # GUI icons will fail as their path is relative.
  342. # This will fail under cx_freeze ...
  343. self.app_home = os.path.dirname(os.path.realpath(__file__))
  344. App.log.debug("Application path is " + self.app_home)
  345. App.log.debug("Started in " + os.getcwd())
  346. # cx_freeze workaround
  347. if os.path.isfile(self.app_home):
  348. self.app_home = os.path.dirname(self.app_home)
  349. os.chdir(self.app_home)
  350. # ############################################################################################################
  351. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  352. # ############################################################################################################
  353. self.defaults = FlatCAMDefaults()
  354. self.defaults["root_folder_path"] = self.app_home
  355. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  356. if user_defaults:
  357. self.defaults.load(filename=current_defaults_path)
  358. if self.defaults['units'] == 'MM':
  359. self.decimals = int(self.defaults['decimals_metric'])
  360. else:
  361. self.decimals = int(self.defaults['decimals_inch'])
  362. if self.defaults["global_gray_icons"] is False:
  363. self.resource_location = 'assets/resources'
  364. else:
  365. self.resource_location = 'assets/resources/dark_resources'
  366. self.current_units = self.defaults['units']
  367. # ###########################################################################################################
  368. # #################################### SETUP OBJECT CLASSES #################################################
  369. # ###########################################################################################################
  370. self.setup_obj_classes()
  371. # ###########################################################################################################
  372. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  373. # ###########################################################################################################
  374. self.pool = Pool()
  375. # ###########################################################################################################
  376. # ###################################### Setting the Splash Screen ##########################################
  377. # ###########################################################################################################
  378. splash_settings = QSettings("Open Source", "FlatCAM")
  379. if splash_settings.contains("splash_screen"):
  380. show_splash = splash_settings.value("splash_screen")
  381. else:
  382. splash_settings.setValue('splash_screen', 1)
  383. # This will write the setting to the platform specific storage.
  384. del splash_settings
  385. show_splash = 1
  386. if show_splash and self.cmd_line_headless != 1:
  387. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  388. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  389. # self.splash.setMask(splash_pix.mask())
  390. # move splashscreen to the current monitor
  391. desktop = QtWidgets.QApplication.desktop()
  392. screen = desktop.screenNumber(QtGui.QCursor.pos())
  393. current_screen_center = desktop.availableGeometry(screen).center()
  394. self.splash.move(current_screen_center - self.splash.rect().center())
  395. self.splash.show()
  396. self.splash.showMessage(_("FlatCAM is initializing ..."),
  397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  398. color=QtGui.QColor("gray"))
  399. else:
  400. show_splash = 0
  401. # ###########################################################################################################
  402. # ######################################### Initialize GUI ##################################################
  403. # ###########################################################################################################
  404. # FlatCAM colors used in plotting
  405. self.FC_light_green = '#BBF268BF'
  406. self.FC_dark_green = '#006E20BF'
  407. self.FC_light_blue = '#a5a5ffbf'
  408. self.FC_dark_blue = '#0000ffbf'
  409. self.ui = FlatCAMGUI(self)
  410. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  411. if theme_settings.contains("theme"):
  412. theme = theme_settings.value('theme', type=str)
  413. else:
  414. theme = 'white'
  415. if self.defaults["global_cursor_color_enabled"]:
  416. self.cursor_color_3D = self.defaults["global_cursor_color"]
  417. else:
  418. if theme == 'white':
  419. self.cursor_color_3D = 'black'
  420. else:
  421. self.cursor_color_3D = 'gray'
  422. # update the defaults dict with the setting in QSetting
  423. self.defaults['global_theme'] = theme
  424. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  425. self.ui.final_save.connect(self.final_save)
  426. # restore the toolbar view
  427. self.restore_toolbar_view()
  428. # restore the GUI geometry
  429. self.restore_main_win_geom()
  430. # set FlatCAM units in the Status bar
  431. self.set_screen_units(self.defaults['units'])
  432. # ###########################################################################################################
  433. # ########################################### AUTOSAVE SETUP ################################################
  434. # ###########################################################################################################
  435. self.block_autosave = False
  436. self.autosave_timer = QtCore.QTimer(self)
  437. self.save_project_auto_update()
  438. self.autosave_timer.timeout.connect(self.save_project_auto)
  439. # ###########################################################################################################
  440. # #################################### LOAD PREPROCESSORS ###################################################
  441. # ###########################################################################################################
  442. # ----------------------------------------- WARNING --------------------------------------------------------
  443. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  444. # That's because the number of preprocessors can vary and here the comboboxes are populated
  445. # -----------------------------------------------------------------------------------------------------------
  446. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  447. # the preprocessor file
  448. self.preprocessors = load_preprocessors(self)
  449. # make sure that always the 'default' preprocessor is the first item in the dictionary
  450. if 'default' in self.preprocessors.keys():
  451. new_ppp_dict = {}
  452. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  453. default_pp = self.preprocessors.pop('default')
  454. new_ppp_dict['default'] = default_pp
  455. # then add the rest of the keys
  456. for name, val_class in self.preprocessors.items():
  457. new_ppp_dict[name] = val_class
  458. # and now put back the ordered dict with 'default' key first
  459. self.preprocessors = new_ppp_dict
  460. for name in list(self.preprocessors.keys()):
  461. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  462. if name.partition('_')[0] == 'Paste':
  463. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  464. continue
  465. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  466. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  467. if name == 'hpgl':
  468. continue
  469. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  470. # ###########################################################################################################
  471. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  472. # ###########################################################################################################
  473. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  474. inform=self.inform)
  475. self.preferencesUiManager.defaults_write_form()
  476. # When the self.defaults dictionary changes will update the Preferences GUI forms
  477. self.defaults.set_change_callback(self.on_defaults_dict_change)
  478. # ###########################################################################################################
  479. # ##################################### FIRST RUN SECTION ###################################################
  480. # ################################ It's done only once after install #####################################
  481. # ###########################################################################################################
  482. if self.defaults["first_run"] is True:
  483. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  484. initial_lay = 'minimal'
  485. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  486. # Set the combobox in Preferences to the current layout
  487. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  488. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  489. # after the first run, this object should be False
  490. self.defaults["first_run"] = False
  491. self.preferencesUiManager.save_defaults(silent=True)
  492. # ###########################################################################################################
  493. # ############################################ Data #########################################################
  494. # ###########################################################################################################
  495. self.recent = []
  496. self.recent_projects = []
  497. self.clipboard = QtWidgets.QApplication.clipboard()
  498. self.project_filename = None
  499. self.toggle_units_ignore = False
  500. # ###########################################################################################################
  501. # ########################################## LOAD LANGUAGES ################################################
  502. # ###########################################################################################################
  503. self.languages = fcTranslate.load_languages()
  504. for name in sorted(self.languages.values()):
  505. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  506. # ###########################################################################################################
  507. # ####################################### APPLY APP LANGUAGE ################################################
  508. # ###########################################################################################################
  509. ret_val = fcTranslate.apply_language('strings')
  510. if ret_val == "no language":
  511. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  512. log.debug("Could not find the Language files. The App strings are missing.")
  513. else:
  514. # make the current language the current selection on the language combobox
  515. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  516. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  517. # ###########################################################################################################
  518. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  519. # ###########################################################################################################
  520. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  521. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  522. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  523. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  524. self.defaults.propagate_defaults()
  525. # ###########################################################################################################
  526. # ######################################## UPDATE THE OPTIONS ###############################################
  527. # ###########################################################################################################
  528. self.options = LoudDict()
  529. # -----------------------------------------------------------------------------------------------------------
  530. # Update the self.options from the self.defaults
  531. # The self.defaults holds the application defaults while the self.options holds the object defaults
  532. # -----------------------------------------------------------------------------------------------------------
  533. # Copy app defaults to project options
  534. for def_key, def_val in self.defaults.items():
  535. self.options[def_key] = deepcopy(def_val)
  536. self.preferencesUiManager.show_preferences_gui()
  537. # ### End of Data ####
  538. # ###########################################################################################################
  539. # #################################### SETUP OBJECT COLLECTION ##############################################
  540. # ###########################################################################################################
  541. self.collection = ObjectCollection(self)
  542. self.ui.project_tab_layout.addWidget(self.collection.view)
  543. # ### Adjust tabs width ## ##
  544. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  545. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  546. self.collection.view.setMinimumWidth(290)
  547. self.log.debug("Finished creating Object Collection.")
  548. # ###########################################################################################################
  549. # ######################################## SETUP Plot Area ##################################################
  550. # ###########################################################################################################
  551. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  552. if self.defaults["global_graphic_engine"] == '3D':
  553. self.is_legacy = False
  554. else:
  555. self.is_legacy = True
  556. # Event signals disconnect id holders
  557. self.mp = None
  558. self.mm = None
  559. self.mr = None
  560. self.mdc = None
  561. self.mp_zc = None
  562. self.kp = None
  563. # Matplotlib axis
  564. self.axes = None
  565. if show_splash:
  566. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  567. "Canvas initialization started."),
  568. alignment=Qt.AlignBottom | Qt.AlignLeft,
  569. color=QtGui.QColor("gray"))
  570. start_plot_time = time.time() # debug
  571. self.plotcanvas = None
  572. self.app_cursor = None
  573. self.hover_shapes = None
  574. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  575. # setup the PlotCanvas
  576. self.on_plotcanvas_setup()
  577. end_plot_time = time.time()
  578. self.used_time = end_plot_time - start_plot_time
  579. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  580. if show_splash:
  581. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  582. "Canvas initialization started.\n"
  583. "Canvas initialization finished in"), '%.2f' % self.used_time),
  584. alignment=Qt.AlignBottom | Qt.AlignLeft,
  585. color=QtGui.QColor("gray"))
  586. self.ui.splitter.setStretchFactor(1, 2)
  587. # ###########################################################################################################
  588. # ############################################### SYS TRAY ##################################################
  589. # ###########################################################################################################
  590. if self.defaults["global_systray_icon"]:
  591. self.parent_w = QtWidgets.QWidget()
  592. if self.cmd_line_headless == 1:
  593. self.trayIcon = FlatCAMSystemTray(app=self,
  594. icon=QtGui.QIcon(self.resource_location +
  595. '/flatcam_icon32_green.png'),
  596. headless=True,
  597. parent=self.parent_w)
  598. else:
  599. self.trayIcon = FlatCAMSystemTray(app=self,
  600. icon=QtGui.QIcon(self.resource_location +
  601. '/flatcam_icon32_green.png'),
  602. parent=self.parent_w)
  603. # ###########################################################################################################
  604. # ############################################### Worker SETUP ##############################################
  605. # ###########################################################################################################
  606. if self.defaults["global_worker_number"]:
  607. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  608. else:
  609. self.workers = WorkerStack(workers_number=2)
  610. self.worker_task.connect(self.workers.add_task)
  611. self.log.debug("Finished creating Workers crew.")
  612. # ###########################################################################################################
  613. # ############################################# Activity Monitor ###########################################
  614. # ###########################################################################################################
  615. self.activity_view = FlatCAMActivityView(app=self)
  616. self.ui.infobar.addWidget(self.activity_view)
  617. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  618. # ###########################################################################################################
  619. # ############################################# Signal handling #############################################
  620. # ###########################################################################################################
  621. # ########################################## Custom signals ################################################
  622. # signal for displaying messages in status bar
  623. self.inform.connect(self.info)
  624. # signal to be called when the app is quiting
  625. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  626. self.message.connect(self.message_dialog)
  627. # self.progress.connect(self.set_progress_bar)
  628. # signals that are emitted when object state changes
  629. self.object_created.connect(self.on_object_created)
  630. self.object_changed.connect(self.on_object_changed)
  631. self.object_plotted.connect(self.on_object_plotted)
  632. self.plots_updated.connect(self.on_plots_updated)
  633. # signals emitted when file state change
  634. self.file_opened.connect(self.register_recent)
  635. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  636. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  637. # ########################################## Standard signals ###############################################
  638. # ### Menu
  639. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  640. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  641. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  642. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  643. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  644. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  645. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  646. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  647. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  648. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  649. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  650. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  651. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  652. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  653. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  654. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  655. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  656. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  657. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  658. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  659. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  660. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  661. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  662. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  663. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  664. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  665. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  666. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  667. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  668. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  669. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  670. self.ui.menufile_exit.triggered.connect(self.final_save)
  671. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  672. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  673. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  674. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  675. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  676. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  677. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  678. self.ui.menueditdelete.triggered.connect(self.on_delete)
  679. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  680. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  681. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  682. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  683. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  684. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  685. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  686. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  687. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  688. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  689. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  690. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  691. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  692. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  693. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  694. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  695. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  696. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  697. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  698. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  699. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  700. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  701. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  702. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  703. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  704. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  705. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  706. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  707. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  708. self.ui.menuview_replot.triggered.connect(self.plot_all)
  709. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  710. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  711. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  712. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  713. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  714. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  715. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  716. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  717. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  718. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  719. self.ui.menuhelp_about.triggered.connect(self.on_about)
  720. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  721. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  722. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  723. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  724. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  725. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  726. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  727. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  728. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  729. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  730. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  731. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  732. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  733. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  734. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  735. # ToolBar signals
  736. self.connect_toolbar_signals()
  737. # Notebook and Plot Tab Area signals
  738. # make the right click on the notebook tab and plot tab area tab raise a menu
  739. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  740. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  741. self.on_tab_setup_context_menu()
  742. # activate initial state
  743. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  744. # Context Menu
  745. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  746. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  747. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  748. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  749. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  750. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  751. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  752. self.ui.clearplot.triggered.connect(self.clear_plots)
  753. self.ui.replot.triggered.connect(self.plot_all)
  754. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  755. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  756. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  757. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  758. self.ui.popmenu_move.triggered.connect(self.obj_move)
  759. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  760. # Project Context Menu -> Color Setting
  761. for act in self.ui.menuprojectcolor.actions():
  762. act.triggered.connect(self.on_set_color_action_triggered)
  763. # ###########################################################################################################
  764. # #################################### GUI PREFERENCES SIGNALS ##############################################
  765. # ###########################################################################################################
  766. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  767. lambda: self.on_toggle_units(no_pref=False))
  768. # ##################################### Workspace Setting Signals ###########################################
  769. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  770. self.on_workspace_modified)
  771. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  772. self.on_workspace_modified
  773. )
  774. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  775. # ###########################################################################################################
  776. # ######################################## GUI SETTINGS SIGNALS #############################################
  777. # ###########################################################################################################
  778. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  779. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  780. # ######################################## Tools related signals ############################################
  781. # Film Tool
  782. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  783. self.on_film_color_entry)
  784. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  785. self.on_film_color_button)
  786. # QRCode Tool
  787. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  788. self.on_qrcode_fill_color_entry)
  789. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  790. self.on_qrcode_fill_color_button)
  791. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  792. self.on_qrcode_back_color_entry)
  793. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  794. self.on_qrcode_back_color_button)
  795. # portability changed signal
  796. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  797. # Object list
  798. self.collection.view.activated.connect(self.on_row_activated)
  799. self.collection.item_selected.connect(self.on_row_selected)
  800. self.object_status_changed.connect(self.on_collection_updated)
  801. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  802. # Export Excellon parameters.
  803. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  804. self.on_update_exc_export
  805. )
  806. # call it once to make sure it is updated at startup
  807. self.on_update_exc_export(state=self.defaults["excellon_update"])
  808. # when there are arguments at application startup this get launched
  809. self.args_at_startup[list].connect(self.on_startup_args)
  810. # ###########################################################################################################
  811. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  812. # ###########################################################################################################
  813. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  814. lambda: self.restore_extensions(ext_type='excellon'))
  815. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  816. lambda: self.restore_extensions(ext_type='gcode'))
  817. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  818. lambda: self.restore_extensions(ext_type='gerber'))
  819. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  820. lambda: self.delete_all_extensions(ext_type='excellon'))
  821. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  822. lambda: self.delete_all_extensions(ext_type='gcode'))
  823. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  824. lambda: self.delete_all_extensions(ext_type='gerber'))
  825. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  826. lambda: self.add_extension(ext_type='excellon'))
  827. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  828. lambda: self.add_extension(ext_type='gcode'))
  829. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  830. lambda: self.add_extension(ext_type='gerber'))
  831. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  832. lambda: self.del_extension(ext_type='excellon'))
  833. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  834. lambda: self.del_extension(ext_type='gcode'))
  835. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  836. lambda: self.del_extension(ext_type='gerber'))
  837. # connect the 'Apply' buttons from the Preferences/File Associations
  838. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  839. lambda: self.on_register_files(obj_type='excellon'))
  840. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  841. lambda: self.on_register_files(obj_type='gcode'))
  842. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  843. lambda: self.on_register_files(obj_type='gerber'))
  844. # ###########################################################################################################
  845. # ########################################### KEYWORDS SIGNALS ##############################################
  846. # ###########################################################################################################
  847. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  848. lambda: self.restore_extensions(ext_type='keyword'))
  849. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  850. lambda: self.delete_all_extensions(ext_type='keyword'))
  851. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  852. lambda: self.add_extension(ext_type='keyword'))
  853. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  854. lambda: self.del_extension(ext_type='keyword'))
  855. # connect the abort_all_tasks related slots to the related signals
  856. self.proc_container.idle_flag.connect(self.app_is_idle)
  857. # signal emitted when a tab is closed in the Plot Area
  858. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  859. # signal to close the application
  860. self.close_app_signal.connect(self.kill_app)
  861. # ################################# FINISHED CONNECTING SIGNALS #############################################
  862. # ###########################################################################################################
  863. # ###########################################################################################################
  864. # ###########################################################################################################
  865. self.log.debug("Finished connecting Signals.")
  866. # ###########################################################################################################
  867. # ########################################## Other setups ###################################################
  868. # ###########################################################################################################
  869. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  870. # depending on from where those tools are called different actions can be done
  871. self.call_source = 'app'
  872. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  873. self.tool_tab_locked = False
  874. # decide if to show or hide the Notebook side of the screen at startup
  875. if self.defaults["global_project_at_startup"] is True:
  876. self.ui.splitter.setSizes([1, 1])
  877. else:
  878. self.ui.splitter.setSizes([0, 1])
  879. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  880. self.setup_component_editor()
  881. # ###########################################################################################################
  882. # ####################################### Auto-complete KEYWORDS ############################################
  883. # ###########################################################################################################
  884. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  885. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  886. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  887. 'export_exc',
  888. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  889. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  890. 'interiors', 'isolate', 'join_excellon',
  891. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  892. 'mirror', 'ncc',
  893. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  894. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  895. 'options', 'origin',
  896. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  897. 'save', 'save_project',
  898. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  899. 'skew', 'subtract_poly', 'subtract_rectangle',
  900. 'version', 'write_gcode'
  901. ]
  902. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  903. 'Paste_1',
  904. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  905. 'Toolchange_manual', 'True', 'Users',
  906. 'all', 'auto', 'axis',
  907. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  908. 'contour', 'default',
  909. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  910. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  911. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  912. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  913. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  914. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  915. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  916. 'spacing_columns',
  917. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  918. 'toolchange_xy', 'toolchangez', 'travelz',
  919. 'tooldia', 'use_threads', 'value',
  920. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  921. ]
  922. self.tcl_keywords = [
  923. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  924. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  925. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  926. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  927. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  928. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  929. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  930. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  931. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  932. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  933. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  934. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  935. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  936. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  937. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  938. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  939. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  940. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  941. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  942. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  943. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  944. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  945. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  946. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  947. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  948. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  949. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  950. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  951. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  952. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  953. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  954. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  955. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  956. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  957. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  958. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  959. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  960. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  961. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  962. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  963. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  964. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  965. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  966. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  967. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  968. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  969. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  970. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  971. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  972. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  973. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  974. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  975. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  976. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  977. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  978. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  979. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  980. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  981. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  982. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  983. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  984. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  985. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  986. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  987. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  988. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  989. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  990. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  991. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  992. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  993. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  994. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  995. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  996. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  997. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  998. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  999. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1000. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1001. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1002. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1003. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1004. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1005. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1006. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1007. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1008. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1009. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1010. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1011. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1012. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1013. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1014. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1015. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1016. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1017. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1018. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1019. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1020. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1021. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1022. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1023. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1024. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1025. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1026. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1027. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1028. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1029. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1030. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1031. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1032. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1033. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1034. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1035. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1036. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1037. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1038. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1039. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1040. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1041. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1042. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1043. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1044. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1045. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1046. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1047. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1048. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1049. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1050. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1051. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1052. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1053. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1054. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1055. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1056. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1057. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1058. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1059. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1060. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1061. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1062. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1063. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1064. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1065. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1066. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1067. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1068. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1069. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1070. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1071. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1072. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1073. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1074. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1075. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1076. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1077. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1078. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1079. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1080. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1081. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1082. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1083. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1084. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1085. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1086. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1087. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1088. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1089. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1090. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1091. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1092. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1093. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1094. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1095. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1096. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1097. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1098. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1099. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1100. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1101. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1102. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1103. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1104. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1105. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1106. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1107. ]
  1108. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1109. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1110. # ###########################################################################################################
  1111. # ############################################## Shell SETUP ################################################
  1112. # ###########################################################################################################
  1113. self.shell = FCShell(app=self, version=self.version)
  1114. self.ui.shell_dock.setWidget(self.shell)
  1115. self.log.debug("TCL Shell has been initialized.")
  1116. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1117. if self.defaults["global_shell_at_startup"]:
  1118. self.ui.shell_dock.show()
  1119. else:
  1120. self.ui.shell_dock.hide()
  1121. # ###########################################################################################################
  1122. # ########################################## Tools and Plugins ##############################################
  1123. # ###########################################################################################################
  1124. self.dblsidedtool = None
  1125. self.distance_tool = None
  1126. self.distance_min_tool = None
  1127. self.panelize_tool = None
  1128. self.film_tool = None
  1129. self.paste_tool = None
  1130. self.calculator_tool = None
  1131. self.rules_tool = None
  1132. self.sub_tool = None
  1133. self.move_tool = None
  1134. self.cutout_tool = None
  1135. self.ncclear_tool = None
  1136. self.optimal_tool = None
  1137. self.paint_tool = None
  1138. self.transform_tool = None
  1139. self.properties_tool = None
  1140. self.pdf_tool = None
  1141. self.image_tool = None
  1142. self.pcb_wizard_tool = None
  1143. self.cal_exc_tool = None
  1144. self.qrcode_tool = None
  1145. self.copper_thieving_tool = None
  1146. self.fiducial_tool = None
  1147. self.edrills_tool = None
  1148. self.align_objects_tool = None
  1149. self.punch_tool = None
  1150. self.invert_tool = None
  1151. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1152. try:
  1153. self.install_tools()
  1154. except AttributeError as e:
  1155. log.debug("App.__init__() install tools() --> %s" % str(e))
  1156. # ###########################################################################################################
  1157. # ############################################ SETUP RECENT ITEMS ###########################################
  1158. # ###########################################################################################################
  1159. self.setup_recent_items()
  1160. # ###########################################################################################################
  1161. # ######################################### BookMarks Manager ###############################################
  1162. # ###########################################################################################################
  1163. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1164. self.install_bookmarks()
  1165. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1166. # ###########################################################################################################
  1167. # ########################################### Tools Database ################################################
  1168. # ###########################################################################################################
  1169. self.tools_db_tab = None
  1170. # ### System Font Parsing ###
  1171. # self.f_parse = ParseFont(self)
  1172. # self.parse_system_fonts()
  1173. # ###########################################################################################################
  1174. # ######################################### Check for updates ###############################################
  1175. # ###########################################################################################################
  1176. # Separate thread (Not worker)
  1177. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1178. if (self.beta is False or self.beta is None) and \
  1179. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1180. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1181. # self.thr2 = QtCore.QThread()
  1182. self.worker_task.emit({'fcn': self.version_check,
  1183. 'params': []})
  1184. # self.thr2.start(QtCore.QThread.LowPriority)
  1185. # ###########################################################################################################
  1186. # ##################################### Register files with FlatCAM; #######################################
  1187. # ################################### It works only for Windows for now ####################################
  1188. # ###########################################################################################################
  1189. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1190. self.on_register_files()
  1191. # ###########################################################################################################
  1192. # ######################################## Variables for global usage #######################################
  1193. # ###########################################################################################################
  1194. # hold the App units
  1195. self.units = 'MM'
  1196. # coordinates for relative position display
  1197. self.rel_point1 = (0, 0)
  1198. self.rel_point2 = (0, 0)
  1199. # variable to store coordinates
  1200. self.pos = (0, 0)
  1201. self.pos_canvas = (0, 0)
  1202. self.pos_jump = (0, 0)
  1203. # variable to store mouse coordinates
  1204. self.mouse = [0, 0]
  1205. # variable to store the delta positions on cavnas
  1206. self.dx = 0
  1207. self.dy = 0
  1208. # decide if we have a double click or single click
  1209. self.doubleclick = False
  1210. # store here the is_dragging value
  1211. self.event_is_dragging = False
  1212. # variable to store if a command is active (then the var is not None) and which one it is
  1213. self.command_active = None
  1214. # variable to store the status of moving selection action
  1215. # None value means that it's not an selection action
  1216. # True value = a selection from left to right
  1217. # False value = a selection from right to left
  1218. self.selection_type = None
  1219. # List to store the objects that are currently loaded in FlatCAM
  1220. # This list is updated on each object creation or object delete
  1221. self.all_objects_list = []
  1222. self.objects_under_the_click_list = []
  1223. # List to store the objects that are selected
  1224. self.sel_objects_list = []
  1225. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1226. self.key_modifiers = None
  1227. # Variable to hold the status of the axis
  1228. self.toggle_axis = True
  1229. # Variable to hold the status of the grid lines
  1230. self.toggle_grid_lines = True
  1231. # Variable to store the status of the fullscreen event
  1232. self.toggle_fscreen = False
  1233. # Variable to store the status of the code editor
  1234. self.toggle_codeeditor = False
  1235. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1236. self.click_noproject = False
  1237. self.cursor = None
  1238. # Variable to store the GCODE that was edited
  1239. self.gcode_edited = ""
  1240. self.text_editor_tab = None
  1241. # reference for the self.ui.code_editor
  1242. self.reference_code_editor = None
  1243. self.script_code = ''
  1244. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1245. self.tools_db_changed_flag = False
  1246. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1247. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1248. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1249. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1250. 'tsm']
  1251. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1252. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1253. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1254. 'sbp', 'tap', 'xpi']
  1255. self.svg_list = ['svg']
  1256. self.dxf_list = ['dxf']
  1257. self.pdf_list = ['pdf']
  1258. self.prj_list = ['flatprj']
  1259. self.conf_list = ['flatconfig']
  1260. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1261. # flag for polygons not cleared
  1262. self.poly_not_cleared = False
  1263. # VisPy visuals
  1264. self.isHovering = False
  1265. self.notHovering = True
  1266. # Window geometry
  1267. self.x_pos = None
  1268. self.y_pos = None
  1269. self.width = None
  1270. self.height = None
  1271. # when True, the app has to return from any thread
  1272. self.abort_flag = False
  1273. # set the value used in the Windows Title
  1274. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1275. # this holds a widget that is installed in the Plot Area when View Source option is used
  1276. self.source_editor_tab = None
  1277. self.pagesize = {}
  1278. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1279. # VisPy visuals
  1280. if self.is_legacy is False:
  1281. try:
  1282. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1283. except AttributeError:
  1284. self.tool_shapes = None
  1285. else:
  1286. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1287. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1288. # used in the delayed shutdown self.start_delayed_quit() method
  1289. self.save_timer = None
  1290. # ###########################################################################################################
  1291. # ################################## ADDING FlatCAM EDITORS section #########################################
  1292. # ###########################################################################################################
  1293. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1294. # at the first launch of the App , the editors will not be functional.
  1295. try:
  1296. self.geo_editor = FlatCAMGeoEditor(self)
  1297. except AttributeError:
  1298. pass
  1299. try:
  1300. self.exc_editor = FlatCAMExcEditor(self)
  1301. except AttributeError:
  1302. pass
  1303. try:
  1304. self.grb_editor = FlatCAMGrbEditor(self)
  1305. except AttributeError:
  1306. pass
  1307. self.log.debug("Finished adding FlatCAM Editor's.")
  1308. self.set_ui_title(name=_("New Project - Not saved"))
  1309. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1310. current_platform = platform.architecture()[0]
  1311. if current_platform != '64bit':
  1312. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1313. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1314. # ###########################################################################################################
  1315. # ########################################### EXCLUSION AREAS ###############################################
  1316. # ###########################################################################################################
  1317. self.exc_areas = ExclusionAreas(app=self)
  1318. # ###########################################################################################################
  1319. # ##################################### Finished the CONSTRUCTOR ############################################
  1320. # ###########################################################################################################
  1321. App.log.debug("END of constructor. Releasing control.")
  1322. # ###########################################################################################################
  1323. # ########################################## SHOW GUI #######################################################
  1324. # ###########################################################################################################
  1325. # if the app is not started as headless, show it
  1326. if self.cmd_line_headless != 1:
  1327. if show_splash:
  1328. # finish the splash
  1329. self.splash.finish(self.ui)
  1330. mgui_settings = QSettings("Open Source", "FlatCAM")
  1331. if mgui_settings.contains("maximized_gui"):
  1332. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1333. if maximized_ui is True:
  1334. self.ui.showMaximized()
  1335. else:
  1336. self.ui.show()
  1337. else:
  1338. self.ui.show()
  1339. if self.defaults["global_systray_icon"]:
  1340. self.trayIcon.show()
  1341. else:
  1342. log.warning("******************* RUNNING HEADLESS *******************")
  1343. # ###########################################################################################################
  1344. # ######################################## START-UP ARGUMENTS ###############################################
  1345. # ###########################################################################################################
  1346. # test if the program was started with a script as parameter
  1347. if self.cmd_line_shellvar:
  1348. try:
  1349. cnt = 0
  1350. command_tcl = 0
  1351. for i in self.cmd_line_shellvar.split(','):
  1352. if i is not None:
  1353. # noinspection PyBroadException
  1354. try:
  1355. command_tcl = eval(i)
  1356. except Exception:
  1357. command_tcl = i
  1358. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1359. cnt += 1
  1360. # if there are Windows paths then replace the path separator with a Unix like one
  1361. if sys.platform == 'win32':
  1362. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1363. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1364. except Exception as ext:
  1365. print("ERROR: ", ext)
  1366. sys.exit(2)
  1367. if self.cmd_line_shellfile:
  1368. if self.cmd_line_headless != 1:
  1369. if self.ui.shell_dock.isHidden():
  1370. self.ui.shell_dock.show()
  1371. try:
  1372. with open(self.cmd_line_shellfile, "r") as myfile:
  1373. # if show_splash:
  1374. # self.splash.showMessage('%s: %ssec\n%s' % (
  1375. # _("Canvas initialization started.\n"
  1376. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1377. # _("Executing Tcl Script ...")),
  1378. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1379. # color=QtGui.QColor("gray"))
  1380. cmd_line_shellfile_text = myfile.read()
  1381. if self.cmd_line_headless != 1:
  1382. self.shell.exec_command(cmd_line_shellfile_text)
  1383. else:
  1384. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1385. except Exception as ext:
  1386. print("ERROR: ", ext)
  1387. sys.exit(2)
  1388. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1389. # the path/file_name must be enclosed in quotes if it contain spaces
  1390. if App.args:
  1391. self.args_at_startup.emit(App.args)
  1392. if self.defaults.old_defaults_found is True:
  1393. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1394. "Please reboot the application to update."))
  1395. self.defaults.old_defaults_found = False
  1396. # ######################################### INIT FINISHED #######################################################
  1397. # #################################################################################################################
  1398. # #################################################################################################################
  1399. # #################################################################################################################
  1400. # #################################################################################################################
  1401. # #################################################################################################################
  1402. @staticmethod
  1403. def copy_and_overwrite(from_path, to_path):
  1404. """
  1405. From here:
  1406. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1407. :param from_path: source path
  1408. :param to_path: destination path
  1409. :return: None
  1410. """
  1411. if os.path.exists(to_path):
  1412. shutil.rmtree(to_path)
  1413. try:
  1414. shutil.copytree(from_path, to_path)
  1415. except FileNotFoundError:
  1416. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1417. shutil.copytree(from_new_path, to_path)
  1418. def on_startup_args(self, args, silent=False):
  1419. """
  1420. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1421. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1422. :param args: a list containing the application args at startup
  1423. :return: None
  1424. """
  1425. if args is not None:
  1426. args_to_process = args
  1427. else:
  1428. args_to_process = App.args
  1429. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1430. for argument in args_to_process:
  1431. if '.FlatPrj'.lower() in argument.lower():
  1432. try:
  1433. project_name = str(argument)
  1434. if project_name == "":
  1435. if silent is False:
  1436. self.inform.emit(_("Cancelled."))
  1437. else:
  1438. # self.open_project(project_name)
  1439. run_from_arg = True
  1440. # self.worker_task.emit({'fcn': self.open_project,
  1441. # 'params': [project_name, run_from_arg]})
  1442. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1443. except Exception as e:
  1444. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1445. elif '.FlatConfig'.lower() in argument.lower():
  1446. try:
  1447. file_name = str(argument)
  1448. if file_name == "":
  1449. if silent is False:
  1450. self.inform.emit(_("Open Config file failed."))
  1451. else:
  1452. run_from_arg = True
  1453. # self.worker_task.emit({'fcn': self.open_config_file,
  1454. # 'params': [file_name, run_from_arg]})
  1455. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1456. except Exception as e:
  1457. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1458. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1459. try:
  1460. file_name = str(argument)
  1461. if file_name == "":
  1462. if silent is False:
  1463. self.inform.emit(_("Open Script file failed."))
  1464. else:
  1465. if silent is False:
  1466. self.on_fileopenscript(name=file_name)
  1467. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1468. self.on_filerunscript(name=file_name)
  1469. except Exception as e:
  1470. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1471. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1472. log.debug("App.on_startup_args() --> Quit event.")
  1473. sys.exit()
  1474. elif 'save'.lower() in argument.lower():
  1475. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1476. self.preferencesUiManager.save_defaults()
  1477. else:
  1478. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1479. proc_arg = argument.lower()
  1480. for ext in exc_list:
  1481. proc_ext = ext.replace(' ', '')
  1482. proc_ext = '.%s' % proc_ext
  1483. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1484. file_name = str(argument)
  1485. if file_name == "":
  1486. if silent is False:
  1487. self.inform.emit(_("Open Excellon file failed."))
  1488. else:
  1489. self.on_fileopenexcellon(name=file_name, signal=None)
  1490. return
  1491. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1492. for ext in gco_list:
  1493. proc_ext = ext.replace(' ', '')
  1494. proc_ext = '.%s' % proc_ext
  1495. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1496. file_name = str(argument)
  1497. if file_name == "":
  1498. if silent is False:
  1499. self.inform.emit(_("Open GCode file failed."))
  1500. else:
  1501. self.on_fileopengcode(name=file_name, signal=None)
  1502. return
  1503. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1504. for ext in grb_list:
  1505. proc_ext = ext.replace(' ', '')
  1506. proc_ext = '.%s' % proc_ext
  1507. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1508. file_name = str(argument)
  1509. if file_name == "":
  1510. if silent is False:
  1511. self.inform.emit(_("Open Gerber file failed."))
  1512. else:
  1513. self.on_fileopengerber(name=file_name, signal=None)
  1514. return
  1515. # if it reached here without already returning then the app was registered with a file that it does not
  1516. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1517. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1518. # for arg in args_to_process:
  1519. # if 'FlatCAM.exe' in arg:
  1520. # continue
  1521. # else:
  1522. # sys.exit(2)
  1523. def set_ui_title(self, name):
  1524. """
  1525. Sets the title of the main window.
  1526. :param name: String that store the project path and project name
  1527. :return: None
  1528. """
  1529. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1530. (self.version,
  1531. ('BETA' if self.beta else ''),
  1532. platform.architecture()[0],
  1533. self.engine,
  1534. name)
  1535. )
  1536. def on_app_restart(self):
  1537. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1538. # be left in the SySTray
  1539. try:
  1540. self.trayIcon.hide()
  1541. except Exception:
  1542. pass
  1543. fcTranslate.restart_program(app=self)
  1544. def clear_pool(self):
  1545. """
  1546. Clear the multiprocessing pool and calls garbage collector.
  1547. :return: None
  1548. """
  1549. self.pool.close()
  1550. self.pool = Pool()
  1551. self.pool_recreated.emit(self.pool)
  1552. gc.collect()
  1553. def install_tools(self):
  1554. """
  1555. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1556. Instantiation of the Tools classes.
  1557. The order that the tools are installed is important as they can depend on each other install position.
  1558. :return: None
  1559. """
  1560. self.distance_tool = Distance(self)
  1561. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1562. before=self.ui.menueditorigin,
  1563. separator=False)
  1564. self.distance_min_tool = DistanceMin(self)
  1565. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1566. pos=self.ui.menuedit,
  1567. before=self.ui.menueditorigin,
  1568. separator=True)
  1569. self.dblsidedtool = DblSidedTool(self)
  1570. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1571. self.cal_exc_tool = ToolCalibration(self)
  1572. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1573. before=self.dblsidedtool.menuAction,
  1574. separator=False)
  1575. self.align_objects_tool = AlignObjects(self)
  1576. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1577. self.edrills_tool = ToolExtractDrills(self)
  1578. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1579. self.panelize_tool = Panelize(self)
  1580. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1581. self.film_tool = Film(self)
  1582. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1583. self.paste_tool = SolderPaste(self)
  1584. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1585. self.calculator_tool = ToolCalculator(self)
  1586. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1587. self.sub_tool = ToolSub(self)
  1588. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1589. pos=self.ui.menutool, separator=True)
  1590. self.rules_tool = RulesCheck(self)
  1591. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1592. pos=self.ui.menutool, separator=False)
  1593. self.optimal_tool = ToolOptimal(self)
  1594. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1595. pos=self.ui.menutool, separator=True)
  1596. self.move_tool = ToolMove(self)
  1597. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1598. before=self.ui.menueditorigin, separator=True)
  1599. self.cutout_tool = CutOut(self)
  1600. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1601. before=self.sub_tool.menuAction)
  1602. self.ncclear_tool = NonCopperClear(self)
  1603. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1604. before=self.sub_tool.menuAction, separator=True)
  1605. self.paint_tool = ToolPaint(self)
  1606. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1607. before=self.sub_tool.menuAction, separator=True)
  1608. self.copper_thieving_tool = ToolCopperThieving(self)
  1609. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1610. pos=self.ui.menutool)
  1611. self.fiducial_tool = ToolFiducials(self)
  1612. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1613. pos=self.ui.menutool)
  1614. self.qrcode_tool = QRCode(self)
  1615. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1616. pos=self.ui.menutool)
  1617. self.punch_tool = ToolPunchGerber(self)
  1618. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1619. self.invert_tool = ToolInvertGerber(self)
  1620. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1621. self.transform_tool = ToolTransform(self)
  1622. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1623. pos=self.ui.menuoptions, separator=True)
  1624. self.properties_tool = Properties(self)
  1625. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1626. pos=self.ui.menuoptions)
  1627. self.pdf_tool = ToolPDF(self)
  1628. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1629. pos=self.ui.menufileimport,
  1630. separator=True)
  1631. self.image_tool = ToolImage(self)
  1632. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1633. pos=self.ui.menufileimport,
  1634. separator=True)
  1635. self.pcb_wizard_tool = PcbWizard(self)
  1636. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1637. pos=self.ui.menufileimport)
  1638. self.log.debug("Tools are installed.")
  1639. def remove_tools(self):
  1640. """
  1641. Will remove all the actions in the Tool menu.
  1642. :return: None
  1643. """
  1644. for act in self.ui.menutool.actions():
  1645. self.ui.menutool.removeAction(act)
  1646. def init_tools(self):
  1647. """
  1648. Initialize the Tool tab in the notebook side of the central widget.
  1649. Remove the actions in the Tools menu.
  1650. Instantiate again the FlatCAM tools (plugins).
  1651. All this is required when changing the layout: standard, compact etc.
  1652. :return: None
  1653. """
  1654. log.debug("init_tools()")
  1655. # delete the data currently in the Tools Tab and the Tab itself
  1656. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1657. if widget is not None:
  1658. widget.deleteLater()
  1659. self.ui.notebook.removeTab(2)
  1660. # rebuild the Tools Tab
  1661. self.ui.tool_tab = QtWidgets.QWidget()
  1662. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1663. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1664. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1665. self.ui.tool_scroll_area = VerticalScrollArea()
  1666. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1667. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1668. # first remove all of them
  1669. self.remove_tools()
  1670. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1671. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1672. '&Command Line\tS')
  1673. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1674. # third install all of them
  1675. try:
  1676. self.install_tools()
  1677. except AttributeError:
  1678. pass
  1679. self.log.debug("Tools are initialized.")
  1680. # def parse_system_fonts(self):
  1681. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1682. # 'params': []})
  1683. def connect_toolbar_signals(self):
  1684. """
  1685. Reconnect the signals to the actions in the toolbar.
  1686. This has to be done each time after the FlatCAM tools are removed/installed.
  1687. :return: None
  1688. """
  1689. # Toolbar
  1690. # File Toolbar Signals
  1691. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1692. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1693. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1694. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1695. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1696. # View Toolbar Signals
  1697. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1698. self.ui.replot_btn.triggered.connect(self.plot_all)
  1699. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1700. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1701. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1702. # Edit Toolbar Signals
  1703. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1704. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1705. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1706. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1707. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1708. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1709. self.ui.delete_btn.triggered.connect(self.on_delete)
  1710. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1711. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1712. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1713. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1714. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1715. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1716. # Scripting Toolbar Signals
  1717. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1718. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1719. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1720. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1721. # Tools Toolbar Signals
  1722. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1723. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1724. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1725. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1726. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1727. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1728. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1729. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1730. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1731. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1732. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1733. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1734. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1735. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1736. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1737. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1738. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1739. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1740. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1741. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1742. def object2editor(self):
  1743. """
  1744. Send the current Geometry or Excellon object (if any) into the it's editor.
  1745. :return: None
  1746. """
  1747. self.defaults.report_usage("object2editor()")
  1748. # disable the objects menu as it may interfere with the Editors
  1749. self.ui.menuobjects.setDisabled(True)
  1750. edited_object = self.collection.get_active()
  1751. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1752. isinstance(edited_object, ExcellonObject):
  1753. pass
  1754. else:
  1755. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1756. return
  1757. if isinstance(edited_object, GeometryObject):
  1758. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1759. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1760. # we set the notebook to hidden
  1761. # self.ui.splitter.setSizes([0, 1])
  1762. if edited_object.multigeo is True:
  1763. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1764. if len(sel_rows) > 1:
  1765. self.inform.emit('[WARNING_NOTCL] %s' %
  1766. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1767. "is not possible.\n"
  1768. "Edit only one geometry at a time."))
  1769. # determine the tool dia of the selected tool
  1770. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1771. # now find the key in the edited_object.tools that has this tooldia
  1772. multi_tool = 1
  1773. for tool in edited_object.tools:
  1774. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1775. multi_tool = tool
  1776. break
  1777. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1778. else:
  1779. self.geo_editor.edit_fcgeometry(edited_object)
  1780. # set call source to the Editor we go into
  1781. self.call_source = 'geo_editor'
  1782. elif isinstance(edited_object, ExcellonObject):
  1783. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1784. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1785. if self.ui.splitter.sizes()[0] == 0:
  1786. self.ui.splitter.setSizes([1, 1])
  1787. self.exc_editor.edit_fcexcellon(edited_object)
  1788. # set call source to the Editor we go into
  1789. self.call_source = 'exc_editor'
  1790. elif isinstance(edited_object, GerberObject):
  1791. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1792. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1793. if self.ui.splitter.sizes()[0] == 0:
  1794. self.ui.splitter.setSizes([1, 1])
  1795. self.grb_editor.edit_fcgerber(edited_object)
  1796. # set call source to the Editor we go into
  1797. self.call_source = 'grb_editor'
  1798. # reset the following variables so the UI is built again after edit
  1799. edited_object.ui_build = False
  1800. edited_object.build_aperture_storage = False
  1801. # make sure that we can't select another object while in Editor Mode:
  1802. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1803. self.ui.project_frame.setDisabled(True)
  1804. # delete any selection shape that might be active as they are not relevant in Editor
  1805. self.delete_selection_shape()
  1806. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1807. self.ui.plot_tab_area.protectTab(0)
  1808. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1809. self.should_we_save = True
  1810. def editor2object(self, cleanup=None):
  1811. """
  1812. Transfers the Geometry or Excellon from it's editor to the current object.
  1813. :return: None
  1814. """
  1815. self.defaults.report_usage("editor2object()")
  1816. # re-enable the objects menu that was disabled on entry in Editor mode
  1817. self.ui.menuobjects.setDisabled(False)
  1818. # do not update a geometry or excellon object unless it comes out of an editor
  1819. if self.call_source != 'app':
  1820. edited_obj = self.collection.get_active()
  1821. if cleanup is None:
  1822. msgbox = QtWidgets.QMessageBox()
  1823. msgbox.setText(_("Do you want to save the edited object?"))
  1824. msgbox.setWindowTitle(_("Close Editor"))
  1825. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1826. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1827. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1828. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1829. msgbox.setDefaultButton(bt_yes)
  1830. msgbox.exec_()
  1831. response = msgbox.clickedButton()
  1832. if response == bt_yes:
  1833. # clean the Tools Tab
  1834. self.ui.tool_scroll_area.takeWidget()
  1835. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1836. self.ui.notebook.setTabText(2, "Tool")
  1837. if isinstance(edited_obj, GeometryObject):
  1838. obj_type = "Geometry"
  1839. if cleanup is None:
  1840. self.geo_editor.update_fcgeometry(edited_obj)
  1841. # self.geo_editor.update_options(edited_obj)
  1842. self.geo_editor.deactivate()
  1843. # restore GUI to the Selected TAB
  1844. # Remove anything else in the GUI
  1845. self.ui.tool_scroll_area.takeWidget()
  1846. # update the geo object options so it is including the bounding box values
  1847. try:
  1848. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1849. edited_obj.options['xmin'] = xmin
  1850. edited_obj.options['ymin'] = ymin
  1851. edited_obj.options['xmax'] = xmax
  1852. edited_obj.options['ymax'] = ymax
  1853. except AttributeError as e:
  1854. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1855. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1856. edited_obj.build_ui()
  1857. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1858. elif isinstance(edited_obj, GerberObject):
  1859. obj_type = "Gerber"
  1860. if cleanup is None:
  1861. self.grb_editor.update_fcgerber()
  1862. self.grb_editor.update_options(edited_obj)
  1863. self.grb_editor.deactivate_grb_editor()
  1864. # delete the old object (the source object) if it was an empty one
  1865. try:
  1866. if len(edited_obj.solid_geometry) == 0:
  1867. old_name = edited_obj.options['name']
  1868. self.collection.set_active(old_name)
  1869. self.collection.delete_active()
  1870. except TypeError:
  1871. # if the solid_geometry is a single Polygon the len() will not work
  1872. # in any case, falling here means that we have something in the solid_geometry, even if only
  1873. # a single Polygon, therefore we pass this
  1874. pass
  1875. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1876. # restore GUI to the Selected TAB
  1877. # Remove anything else in the GUI
  1878. self.ui.selected_scroll_area.takeWidget()
  1879. elif isinstance(edited_obj, ExcellonObject):
  1880. obj_type = "Excellon"
  1881. if cleanup is None:
  1882. self.exc_editor.update_fcexcellon(edited_obj)
  1883. # self.exc_editor.update_options(edited_obj)
  1884. self.exc_editor.deactivate()
  1885. # restore GUI to the Selected TAB
  1886. # Remove anything else in the GUI
  1887. self.ui.tool_scroll_area.takeWidget()
  1888. # delete the old object (the source object) if it was an empty one
  1889. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1890. old_name = edited_obj.options['name']
  1891. self.collection.delete_by_name(name=old_name)
  1892. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1893. else:
  1894. self.inform.emit('[WARNING_NOTCL] %s' %
  1895. _("Select a Gerber, Geometry or Excellon Object to update."))
  1896. return
  1897. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1898. elif response == bt_no:
  1899. # clean the Tools Tab
  1900. self.ui.tool_scroll_area.takeWidget()
  1901. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1902. self.ui.notebook.setTabText(2, "Tool")
  1903. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1904. if isinstance(edited_obj, GeometryObject):
  1905. self.geo_editor.deactivate()
  1906. edited_obj.build_ui()
  1907. elif isinstance(edited_obj, GerberObject):
  1908. self.grb_editor.deactivate_grb_editor()
  1909. edited_obj.build_ui()
  1910. elif isinstance(edited_obj, ExcellonObject):
  1911. self.exc_editor.deactivate()
  1912. edited_obj.build_ui()
  1913. else:
  1914. self.inform.emit('[WARNING_NOTCL] %s' %
  1915. _("Select a Gerber, Geometry or Excellon Object to update."))
  1916. return
  1917. elif response == bt_cancel:
  1918. return
  1919. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1920. # edited_obj.build_ui()
  1921. # Switch notebook to Selected page
  1922. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1923. else:
  1924. if isinstance(edited_obj, GeometryObject):
  1925. self.geo_editor.deactivate()
  1926. elif isinstance(edited_obj, GerberObject):
  1927. self.grb_editor.deactivate_grb_editor()
  1928. elif isinstance(edited_obj, ExcellonObject):
  1929. self.exc_editor.deactivate()
  1930. else:
  1931. self.inform.emit('[WARNING_NOTCL] %s' %
  1932. _("Select a Gerber, Geometry or Excellon Object to update."))
  1933. return
  1934. # if notebook is hidden we show it
  1935. if self.ui.splitter.sizes()[0] == 0:
  1936. self.ui.splitter.setSizes([1, 1])
  1937. # restore the call_source to app
  1938. self.call_source = 'app'
  1939. edited_obj.plot()
  1940. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1941. self.ui.plot_tab_area.protectTab(0)
  1942. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1943. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1944. self.ui.project_frame.setDisabled(False)
  1945. def get_last_folder(self):
  1946. """
  1947. Get the folder path from where the last file was opened.
  1948. :return: String, last opened folder path
  1949. """
  1950. return self.defaults["global_last_folder"]
  1951. def get_last_save_folder(self):
  1952. """
  1953. Get the folder path from where the last file was saved.
  1954. :return: String, last saved folder path
  1955. """
  1956. loc = self.defaults["global_last_save_folder"]
  1957. if loc is None:
  1958. loc = self.defaults["global_last_folder"]
  1959. if loc is None:
  1960. loc = os.path.dirname(__file__)
  1961. return loc
  1962. def info(self, msg):
  1963. """
  1964. Informs the user. Normally on the status bar, optionally
  1965. also on the shell.
  1966. :param msg: Text to write.
  1967. :return: None
  1968. """
  1969. # Type of message in brackets at the beginning of the message.
  1970. match = re.search(r"\[(.*)\](.*)", msg)
  1971. if match:
  1972. level = match.group(1)
  1973. msg_ = match.group(2)
  1974. self.ui.fcinfo.set_status(str(msg_), level=level)
  1975. if level.lower() == "error":
  1976. self.shell_message(msg, error=True, show=True)
  1977. elif level.lower() == "warning":
  1978. self.shell_message(msg, warning=True, show=True)
  1979. elif level.lower() == "error_notcl":
  1980. self.shell_message(msg, error=True, show=False)
  1981. elif level.lower() == "warning_notcl":
  1982. self.shell_message(msg, warning=True, show=False)
  1983. elif level.lower() == "success":
  1984. self.shell_message(msg, success=True, show=False)
  1985. elif level.lower() == "selected":
  1986. self.shell_message(msg, selected=True, show=False)
  1987. else:
  1988. self.shell_message(msg, show=False)
  1989. else:
  1990. self.ui.fcinfo.set_status(str(msg), level="info")
  1991. # make sure that if the message is to clear the infobar with a space
  1992. # is not printed over and over on the shell
  1993. if msg != '':
  1994. self.shell_message(msg)
  1995. def restore_toolbar_view(self):
  1996. """
  1997. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1998. was saved in the defaults dictionary.
  1999. :return: None
  2000. """
  2001. tb = self.defaults["global_toolbar_view"]
  2002. if tb & 1:
  2003. self.ui.toolbarfile.setVisible(True)
  2004. else:
  2005. self.ui.toolbarfile.setVisible(False)
  2006. if tb & 2:
  2007. self.ui.toolbargeo.setVisible(True)
  2008. else:
  2009. self.ui.toolbargeo.setVisible(False)
  2010. if tb & 4:
  2011. self.ui.toolbarview.setVisible(True)
  2012. else:
  2013. self.ui.toolbarview.setVisible(False)
  2014. if tb & 8:
  2015. self.ui.toolbartools.setVisible(True)
  2016. else:
  2017. self.ui.toolbartools.setVisible(False)
  2018. if tb & 16:
  2019. self.ui.exc_edit_toolbar.setVisible(True)
  2020. else:
  2021. self.ui.exc_edit_toolbar.setVisible(False)
  2022. if tb & 32:
  2023. self.ui.geo_edit_toolbar.setVisible(True)
  2024. else:
  2025. self.ui.geo_edit_toolbar.setVisible(False)
  2026. if tb & 64:
  2027. self.ui.grb_edit_toolbar.setVisible(True)
  2028. else:
  2029. self.ui.grb_edit_toolbar.setVisible(False)
  2030. if tb & 128:
  2031. self.ui.snap_toolbar.setVisible(True)
  2032. else:
  2033. self.ui.snap_toolbar.setVisible(False)
  2034. if tb & 256:
  2035. self.ui.toolbarshell.setVisible(True)
  2036. else:
  2037. self.ui.toolbarshell.setVisible(False)
  2038. def on_import_preferences(self):
  2039. """
  2040. Loads the application default settings from a saved file into
  2041. ``self.defaults`` dictionary.
  2042. :return: None
  2043. """
  2044. self.defaults.report_usage("on_import_preferences")
  2045. App.log.debug("App.on_import_preferences()")
  2046. # Show file chooser
  2047. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2048. try:
  2049. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2050. directory=self.data_path,
  2051. filter=filter_)
  2052. except TypeError:
  2053. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2054. filter=filter_)
  2055. filename = str(filename)
  2056. if filename == "":
  2057. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2058. return
  2059. # Load in the defaults from the chosen file
  2060. self.defaults.load(filename=filename)
  2061. self.preferencesUiManager.on_preferences_edited()
  2062. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2063. def on_export_preferences(self):
  2064. """
  2065. Save the defaults dictionary to a file.
  2066. :return: None
  2067. """
  2068. self.defaults.report_usage("on_export_preferences")
  2069. App.log.debug("on_export_preferences()")
  2070. # defaults_file_content = None
  2071. # Show file chooser
  2072. date = str(datetime.today()).rpartition('.')[0]
  2073. date = ''.join(c for c in date if c not in ':-')
  2074. date = date.replace(' ', '_')
  2075. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2076. try:
  2077. filename, _f = FCFileSaveDialog.get_saved_filename(
  2078. caption=_("Export FlatCAM Preferences"),
  2079. directory=self.data_path + '/preferences_' + date,
  2080. filter=filter__
  2081. )
  2082. except TypeError:
  2083. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2084. filename = str(filename)
  2085. if filename == "":
  2086. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2087. return
  2088. # Update options
  2089. self.preferencesUiManager.defaults_read_form()
  2090. self.defaults.propagate_defaults()
  2091. # Save update options
  2092. try:
  2093. self.defaults.write(filename=filename)
  2094. except Exception:
  2095. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2096. return
  2097. if self.defaults["global_open_style"] is False:
  2098. self.file_opened.emit("preferences", filename)
  2099. self.file_saved.emit("preferences", filename)
  2100. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2101. def save_to_file(self, content_to_save, txt_content):
  2102. """
  2103. Save something to a file.
  2104. :return: None
  2105. """
  2106. self.defaults.report_usage("save_to_file")
  2107. App.log.debug("save_to_file()")
  2108. self.date = str(datetime.today()).rpartition('.')[0]
  2109. self.date = ''.join(c for c in self.date if c not in ':-')
  2110. self.date = self.date.replace(' ', '_')
  2111. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2112. path_to_save = self.defaults["global_last_save_folder"] if \
  2113. self.defaults["global_last_save_folder"] is not None else self.data_path
  2114. try:
  2115. filename, _f = FCFileSaveDialog.get_saved_filename(
  2116. caption=_("Save to file"),
  2117. directory=path_to_save + '/file_' + self.date,
  2118. filter=filter__
  2119. )
  2120. except TypeError:
  2121. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2122. filename = str(filename)
  2123. if filename == "":
  2124. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2125. return
  2126. else:
  2127. try:
  2128. with open(filename, 'w') as f:
  2129. ___ = f.read()
  2130. except PermissionError:
  2131. self.inform.emit('[WARNING] %s' %
  2132. _("Permission denied, saving not possible.\n"
  2133. "Most likely another app is holding the file open and not accessible."))
  2134. return
  2135. except IOError:
  2136. App.log.debug('Creating a new file ...')
  2137. f = open(filename, 'w')
  2138. f.close()
  2139. except Exception:
  2140. e = sys.exc_info()[0]
  2141. App.log.error("Could not load the file.")
  2142. App.log.error(str(e))
  2143. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2144. return
  2145. # Save content
  2146. if filename.rpartition('.')[2].lower() == 'html':
  2147. file_content = content_to_save
  2148. else:
  2149. file_content = txt_content
  2150. try:
  2151. with open(filename, "w") as f:
  2152. f.write(file_content)
  2153. except Exception:
  2154. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2155. return
  2156. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2157. def save_geometry(self, x, y, width, height, notebook_width):
  2158. """
  2159. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2160. launch of the application.
  2161. :param x: X position of the main window
  2162. :param y: Y position of the main window
  2163. :param width: width of the main window
  2164. :param height: height of the main window
  2165. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2166. :return: None
  2167. """
  2168. self.defaults["global_def_win_x"] = x
  2169. self.defaults["global_def_win_y"] = y
  2170. self.defaults["global_def_win_w"] = width
  2171. self.defaults["global_def_win_h"] = height
  2172. self.defaults["global_def_notebook_width"] = notebook_width
  2173. self.preferencesUiManager.save_defaults()
  2174. def restore_main_win_geom(self):
  2175. try:
  2176. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2177. self.defaults["global_def_win_y"],
  2178. self.defaults["global_def_win_w"],
  2179. self.defaults["global_def_win_h"])
  2180. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2181. except KeyError as e:
  2182. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2183. def message_dialog(self, title, message, kind="info"):
  2184. """
  2185. Builds and show a custom QMessageBox to be used in FlatCAM.
  2186. :param title: title of the QMessageBox
  2187. :param message: message to be displayed
  2188. :param kind: type of QMessageBox; will display a specific icon.
  2189. :return:
  2190. """
  2191. icon = {"info": QtWidgets.QMessageBox.Information,
  2192. "warning": QtWidgets.QMessageBox.Warning,
  2193. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2194. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2195. dlg.setText(message)
  2196. dlg.exec_()
  2197. def register_recent(self, kind, filename):
  2198. """
  2199. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2200. dictionary.
  2201. :param kind: type of file that was opened
  2202. :param filename: the path and file name for the file that was opened
  2203. :return:
  2204. """
  2205. self.log.debug("register_recent()")
  2206. self.log.debug(" %s" % kind)
  2207. self.log.debug(" %s" % filename)
  2208. record = {'kind': str(kind), 'filename': str(filename)}
  2209. if record in self.recent:
  2210. return
  2211. if record in self.recent_projects:
  2212. return
  2213. if record['kind'] == 'project':
  2214. self.recent_projects.insert(0, record)
  2215. else:
  2216. self.recent.insert(0, record)
  2217. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2218. self.recent.pop()
  2219. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2220. self.recent_projects.pop()
  2221. try:
  2222. f = open(self.data_path + '/recent.json', 'w')
  2223. except IOError:
  2224. App.log.error("Failed to open recent items file for writing.")
  2225. self.inform.emit('[ERROR_NOTCL] %s' %
  2226. _('Failed to open recent files file for writing.'))
  2227. return
  2228. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2229. f.close()
  2230. try:
  2231. fp = open(self.data_path + '/recent_projects.json', 'w')
  2232. except IOError:
  2233. App.log.error("Failed to open recent items file for writing.")
  2234. self.inform.emit('[ERROR_NOTCL] %s' %
  2235. _('Failed to open recent projects file for writing.'))
  2236. return
  2237. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2238. fp.close()
  2239. # Re-build the recent items menu
  2240. self.setup_recent_items()
  2241. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2242. """
  2243. Creates a new specialized FlatCAMObj and attaches it to the application,
  2244. this is, updates the GUI accordingly, any other records and plots it.
  2245. This method is thread-safe.
  2246. Notes:
  2247. * If the name is in use, the self.collection will modify it
  2248. when appending it to the collection. There is no need to handle
  2249. name conflicts here.
  2250. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2251. :type kind: str
  2252. :param name: Name for the object.
  2253. :type name: str
  2254. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2255. The function is called with 2 parameters: the new object and the App instance.
  2256. :type initialize: function
  2257. :param plot: If to plot the resulting object
  2258. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2259. self.collection
  2260. :return: None
  2261. :rtype: None
  2262. """
  2263. App.log.debug("new_object()")
  2264. obj_plot = plot
  2265. obj_autoselected = autoselected
  2266. t0 = time.time() # Debug
  2267. # ## Create object
  2268. classdict = {
  2269. "gerber": GerberObject,
  2270. "excellon": ExcellonObject,
  2271. "cncjob": CNCJobObject,
  2272. "geometry": GeometryObject,
  2273. "script": ScriptObject,
  2274. "document": DocumentObject
  2275. }
  2276. App.log.debug("Calling object constructor...")
  2277. # Object creation/instantiation
  2278. obj = classdict[kind](name)
  2279. obj.units = self.options["units"]
  2280. # IMPORTANT
  2281. # The key names in defaults and options dictionary's are not random:
  2282. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2283. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2284. # copied to self.options. After that, below, depending on the type of
  2285. # object that is created, it will strip the name of the object and the underline (if the original key was
  2286. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2287. # "toolchange"
  2288. for option in self.options:
  2289. if option.find(kind + "_") == 0:
  2290. oname = option[len(kind) + 1:]
  2291. obj.options[oname] = self.options[option]
  2292. obj.isHovering = False
  2293. obj.notHovering = True
  2294. # Initialize as per user request
  2295. # User must take care to implement initialize
  2296. # in a thread-safe way as is is likely that we
  2297. # have been invoked in a separate thread.
  2298. t1 = time.time()
  2299. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2300. try:
  2301. return_value = initialize(obj, self)
  2302. except Exception as e:
  2303. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2304. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2305. msg += traceback.format_exc()
  2306. self.inform.emit(msg)
  2307. return "fail"
  2308. t2 = time.time()
  2309. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2310. if return_value == 'fail':
  2311. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2312. return "fail"
  2313. # Check units and convert if necessary
  2314. # This condition CAN be true because initialize() can change obj.units
  2315. if self.options["units"].upper() != obj.units.upper():
  2316. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2317. obj.convert_units(self.options["units"])
  2318. t3 = time.time()
  2319. self.log.debug("%f seconds converting units." % (t3 - t2))
  2320. # Create the bounding box for the object and then add the results to the obj.options
  2321. # But not for Scripts or for Documents
  2322. if kind != 'document' and kind != 'script':
  2323. try:
  2324. xmin, ymin, xmax, ymax = obj.bounds()
  2325. obj.options['xmin'] = xmin
  2326. obj.options['ymin'] = ymin
  2327. obj.options['xmax'] = xmax
  2328. obj.options['ymax'] = ymax
  2329. except Exception as e:
  2330. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2331. return "fail"
  2332. try:
  2333. if kind == 'excellon':
  2334. obj.fill_color = self.defaults["excellon_plot_fill"]
  2335. obj.outline_color = self.defaults["excellon_plot_line"]
  2336. if kind == 'gerber':
  2337. obj.fill_color = self.defaults["gerber_plot_fill"]
  2338. obj.outline_color = self.defaults["gerber_plot_line"]
  2339. except Exception as e:
  2340. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2341. # update the KeyWords list with the name of the file
  2342. self.myKeywords.append(obj.options['name'])
  2343. log.debug("Moving new object back to main thread.")
  2344. # Move the object to the main thread and let the app know that it is available.
  2345. obj.moveToThread(self.main_thread)
  2346. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2347. return obj
  2348. def new_excellon_object(self):
  2349. """
  2350. Creates a new, blank Excellon object.
  2351. :return: None
  2352. """
  2353. self.defaults.report_usage("new_excellon_object()")
  2354. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2355. def new_geometry_object(self):
  2356. """
  2357. Creates a new, blank and single-tool Geometry object.
  2358. :return: None
  2359. """
  2360. self.defaults.report_usage("new_geometry_object()")
  2361. def initialize(obj, app):
  2362. obj.multitool = False
  2363. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2364. def new_gerber_object(self):
  2365. """
  2366. Creates a new, blank Gerber object.
  2367. :return: None
  2368. """
  2369. self.defaults.report_usage("new_gerber_object()")
  2370. def initialize(grb_obj, app):
  2371. grb_obj.multitool = False
  2372. grb_obj.source_file = []
  2373. grb_obj.multigeo = False
  2374. grb_obj.follow = False
  2375. grb_obj.apertures = {}
  2376. grb_obj.solid_geometry = []
  2377. try:
  2378. grb_obj.options['xmin'] = 0
  2379. grb_obj.options['ymin'] = 0
  2380. grb_obj.options['xmax'] = 0
  2381. grb_obj.options['ymax'] = 0
  2382. except KeyError:
  2383. pass
  2384. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2385. def new_script_object(self):
  2386. """
  2387. Creates a new, blank TCL Script object.
  2388. :return: None
  2389. """
  2390. self.defaults.report_usage("new_script_object()")
  2391. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2392. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2393. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2394. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2395. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2396. # "ListSys, MillDrills,\n" \
  2397. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2398. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2399. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2400. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2401. # "# SubtractRectangle, Version, WriteGCode\n"
  2402. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2403. '# %s:\n' % _('TCL Tutorial is here') + \
  2404. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2405. '# %s:\n' % _("FlatCAM commands list")
  2406. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2407. "(displayed in Tcl Shell).")
  2408. def initialize(obj, app):
  2409. obj.source_file = deepcopy(new_source_file)
  2410. outname = 'new_script'
  2411. self.new_object('script', outname, initialize, plot=False)
  2412. def new_document_object(self):
  2413. """
  2414. Creates a new, blank Document object.
  2415. :return: None
  2416. """
  2417. self.defaults.report_usage("new_document_object()")
  2418. def initialize(obj, app):
  2419. obj.source_file = ""
  2420. self.new_object('document', 'new_document', initialize, plot=False)
  2421. def on_object_created(self, obj, plot, auto_select):
  2422. """
  2423. Event callback for object creation.
  2424. It will add the new object to the collection. After that it will plot the object in a threaded way
  2425. :param obj: The newly created FlatCAM object.
  2426. :param plot: if the newly create object t obe plotted
  2427. :param auto_select: if the newly created object to be autoselected after creation
  2428. :return: None
  2429. """
  2430. t0 = time.time() # DEBUG
  2431. self.log.debug("on_object_created()")
  2432. # The Collection might change the name if there is a collision
  2433. self.collection.append(obj)
  2434. # after adding the object to the collection always update the list of objects that are in the collection
  2435. self.all_objects_list = self.collection.get_list()
  2436. # self.inform.emit('[selected] %s created & selected: %s' %
  2437. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2438. if obj.kind == 'gerber':
  2439. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2440. kind=obj.kind.capitalize(),
  2441. color='green',
  2442. name=str(obj.options['name']), tx=_("created/selected"))
  2443. )
  2444. elif obj.kind == 'excellon':
  2445. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2446. kind=obj.kind.capitalize(),
  2447. color='brown',
  2448. name=str(obj.options['name']), tx=_("created/selected"))
  2449. )
  2450. elif obj.kind == 'cncjob':
  2451. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2452. kind=obj.kind.capitalize(),
  2453. color='blue',
  2454. name=str(obj.options['name']), tx=_("created/selected"))
  2455. )
  2456. elif obj.kind == 'geometry':
  2457. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2458. kind=obj.kind.capitalize(),
  2459. color='red',
  2460. name=str(obj.options['name']), tx=_("created/selected"))
  2461. )
  2462. elif obj.kind == 'script':
  2463. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2464. kind=obj.kind.capitalize(),
  2465. color='orange',
  2466. name=str(obj.options['name']), tx=_("created/selected"))
  2467. )
  2468. elif obj.kind == 'document':
  2469. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2470. kind=obj.kind.capitalize(),
  2471. color='darkCyan',
  2472. name=str(obj.options['name']), tx=_("created/selected"))
  2473. )
  2474. # update the SHELL auto-completer model with the name of the new object
  2475. self.shell._edit.set_model_data(self.myKeywords)
  2476. if auto_select:
  2477. # select the just opened object but deselect the previous ones
  2478. self.collection.set_all_inactive()
  2479. self.collection.set_active(obj.options["name"])
  2480. else:
  2481. self.collection.set_all_inactive()
  2482. # here it is done the object plotting
  2483. def worker_task(t_obj):
  2484. with self.proc_container.new(_("Plotting")):
  2485. if isinstance(t_obj, CNCJobObject):
  2486. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2487. else:
  2488. t_obj.plot()
  2489. t1 = time.time() # DEBUG
  2490. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2491. self.object_plotted.emit(t_obj)
  2492. # Send to worker
  2493. # self.worker.add_task(worker_task, [self])
  2494. if plot is True:
  2495. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2496. def on_object_changed(self, obj):
  2497. """
  2498. Called whenever the geometry of the object was changed in some way.
  2499. This require the update of it's bounding values so it can be the selected on canvas.
  2500. Update the bounding box data from obj.options
  2501. :param obj: the object that was changed
  2502. :return: None
  2503. """
  2504. xmin, ymin, xmax, ymax = obj.bounds()
  2505. obj.options['xmin'] = xmin
  2506. obj.options['ymin'] = ymin
  2507. obj.options['xmax'] = xmax
  2508. obj.options['ymax'] = ymax
  2509. log.debug("Object changed, updating the bounding box data on self.options")
  2510. # delete the old selection shape
  2511. self.delete_selection_shape()
  2512. self.should_we_save = True
  2513. def on_object_plotted(self):
  2514. """
  2515. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2516. :return: None
  2517. """
  2518. self.on_zoom_fit(None)
  2519. def on_about(self):
  2520. """
  2521. Displays the "about" dialog found in the Menu --> Help.
  2522. :return: None
  2523. """
  2524. self.defaults.report_usage("on_about")
  2525. version = self.version
  2526. version_date = self.version_date
  2527. beta = self.beta
  2528. class AboutDialog(QtWidgets.QDialog):
  2529. def __init__(self, app, parent=None):
  2530. QtWidgets.QDialog.__init__(self, parent)
  2531. self.app = app
  2532. # Icon and title
  2533. self.setWindowIcon(parent.app_icon)
  2534. self.setWindowTitle(_("About FlatCAM"))
  2535. self.resize(600, 200)
  2536. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2537. # self.setStyleSheet(
  2538. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2539. # "background-attachment: fixed"
  2540. # )
  2541. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2542. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2543. # palette = QtGui.QPalette()
  2544. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2545. # self.setPalette(palette)
  2546. logo = QtWidgets.QLabel()
  2547. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2548. title = QtWidgets.QLabel(
  2549. "<font size=8><B>FlatCAM</B></font><BR>"
  2550. "{title}<BR>"
  2551. "<BR>"
  2552. "<BR>"
  2553. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2554. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2555. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2556. "<B>{issue}</B></a><BR>".format(
  2557. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2558. devel=_("Development"),
  2559. down=_("DOWNLOAD"),
  2560. issue=_("Issue tracker"))
  2561. )
  2562. title.setOpenExternalLinks(True)
  2563. closebtn = QtWidgets.QPushButton(_("Close"))
  2564. tab_widget = QtWidgets.QTabWidget()
  2565. description_label = QtWidgets.QLabel(
  2566. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2567. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2568. version=version,
  2569. beta=('BETA' if beta else ''),
  2570. date=version_date,
  2571. arch=platform.architecture()[0])
  2572. )
  2573. description_label.setOpenExternalLinks(True)
  2574. lic_lbl_header = QtWidgets.QLabel(
  2575. '%s:<br>%s<br>' % (
  2576. _('Licensed under the MIT license'),
  2577. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2578. "http://www.opensource.org/licenses/mit-license.php</a>"
  2579. )
  2580. )
  2581. lic_lbl_header.setOpenExternalLinks(True)
  2582. lic_lbl_body = QtWidgets.QLabel(
  2583. _(
  2584. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2585. 'of this software and associated documentation files (the "Software"), to deal\n'
  2586. 'in the Software without restriction, including without limitation the rights\n'
  2587. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2588. 'copies of the Software, and to permit persons to whom the Software is\n'
  2589. 'furnished to do so, subject to the following conditions:\n\n'
  2590. 'The above copyright notice and this permission notice shall be included in\n'
  2591. 'all copies or substantial portions of the Software.\n\n'
  2592. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2593. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2594. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2595. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2596. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2597. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2598. 'THE SOFTWARE.'
  2599. )
  2600. )
  2601. attributions_label = QtWidgets.QLabel(
  2602. _(
  2603. 'Some of the icons used are from the following sources:<br>'
  2604. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2605. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2606. 'title="Flaticon">www.flaticon.com</a></div>'
  2607. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2608. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2609. )
  2610. )
  2611. attributions_label.setOpenExternalLinks(True)
  2612. # layouts
  2613. layout1 = QtWidgets.QVBoxLayout()
  2614. layout1_1 = QtWidgets.QHBoxLayout()
  2615. layout1_2 = QtWidgets.QHBoxLayout()
  2616. layout2 = QtWidgets.QHBoxLayout()
  2617. layout3 = QtWidgets.QHBoxLayout()
  2618. self.setLayout(layout1)
  2619. layout1.addLayout(layout1_1)
  2620. layout1.addLayout(layout1_2)
  2621. layout1.addLayout(layout2)
  2622. layout1.addLayout(layout3)
  2623. layout1_1.addStretch()
  2624. layout1_1.addWidget(description_label)
  2625. layout1_2.addWidget(tab_widget)
  2626. self.splash_tab = QtWidgets.QWidget()
  2627. self.splash_tab.setObjectName("splash_about")
  2628. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2629. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2630. tab_widget.addTab(self.splash_tab, _("Splash"))
  2631. self.programmmers_tab = QtWidgets.QWidget()
  2632. self.programmmers_tab.setObjectName("programmers_about")
  2633. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2634. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2635. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2636. self.translators_tab = QtWidgets.QWidget()
  2637. self.translators_tab.setObjectName("translators_about")
  2638. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2639. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2640. tab_widget.addTab(self.translators_tab, _("Translators"))
  2641. self.license_tab = QtWidgets.QWidget()
  2642. self.license_tab.setObjectName("license_about")
  2643. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2644. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2645. tab_widget.addTab(self.license_tab, _("License"))
  2646. self.attributions_tab = QtWidgets.QWidget()
  2647. self.attributions_tab.setObjectName("attributions_about")
  2648. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2649. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2650. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2651. self.splash_tab_layout.addWidget(logo, stretch=0)
  2652. self.splash_tab_layout.addWidget(title, stretch=1)
  2653. pal = QtGui.QPalette()
  2654. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2655. self.prog_grid_lay = QtWidgets.QGridLayout()
  2656. self.prog_grid_lay.setHorizontalSpacing(20)
  2657. self.prog_grid_lay.setColumnStretch(0, 0)
  2658. self.prog_grid_lay.setColumnStretch(2, 1)
  2659. prog_widget = QtWidgets.QWidget()
  2660. prog_widget.setLayout(self.prog_grid_lay)
  2661. prog_scroll = QtWidgets.QScrollArea()
  2662. prog_scroll.setWidget(prog_widget)
  2663. prog_scroll.setWidgetResizable(True)
  2664. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2665. prog_scroll.setPalette(pal)
  2666. self.programmmers_tab_layout.addWidget(prog_scroll)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2704. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2705. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2706. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2707. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2708. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2709. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2710. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2711. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2712. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2713. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2714. self.translator_grid_lay = QtWidgets.QGridLayout()
  2715. self.translator_grid_lay.setColumnStretch(0, 0)
  2716. self.translator_grid_lay.setColumnStretch(1, 0)
  2717. self.translator_grid_lay.setColumnStretch(2, 1)
  2718. self.translator_grid_lay.setColumnStretch(3, 0)
  2719. # trans_widget = QtWidgets.QWidget()
  2720. # trans_widget.setLayout(self.translator_grid_lay)
  2721. # self.translators_tab_layout.addWidget(trans_widget)
  2722. # self.translators_tab_layout.addStretch()
  2723. trans_widget = QtWidgets.QWidget()
  2724. trans_widget.setLayout(self.translator_grid_lay)
  2725. trans_scroll = QtWidgets.QScrollArea()
  2726. trans_scroll.setWidget(trans_widget)
  2727. trans_scroll.setWidgetResizable(True)
  2728. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2729. trans_scroll.setPalette(pal)
  2730. self.translators_tab_layout.addWidget(trans_scroll)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2750. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2751. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2752. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2753. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2754. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2755. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2756. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2757. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2758. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2759. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2760. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2761. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2762. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2763. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2764. self.translator_grid_lay.setColumnStretch(0, 0)
  2765. self.translators_tab_layout.addStretch()
  2766. self.license_tab_layout.addWidget(lic_lbl_header)
  2767. self.license_tab_layout.addWidget(lic_lbl_body)
  2768. self.license_tab_layout.addStretch()
  2769. self.attributions_tab_layout.addWidget(attributions_label)
  2770. self.attributions_tab_layout.addStretch()
  2771. layout3.addStretch()
  2772. layout3.addWidget(closebtn)
  2773. closebtn.clicked.connect(self.accept)
  2774. AboutDialog(app=self, parent=self.ui).exec_()
  2775. def install_bookmarks(self, book_dict=None):
  2776. """
  2777. Install the bookmarks actions in the Help menu -> Bookmarks
  2778. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2779. :return: None
  2780. """
  2781. if book_dict is None:
  2782. self.defaults["global_bookmarks"].update(
  2783. {
  2784. '1': ['FlatCAM', "http://flatcam.org"],
  2785. '2': ['Backup Site', ""]
  2786. }
  2787. )
  2788. else:
  2789. self.defaults["global_bookmarks"].clear()
  2790. self.defaults["global_bookmarks"].update(book_dict)
  2791. # first try to disconnect if somehow they get connected from elsewhere
  2792. for act in self.ui.menuhelp_bookmarks.actions():
  2793. try:
  2794. act.triggered.disconnect()
  2795. except TypeError:
  2796. pass
  2797. # clear all actions except the last one who is the Bookmark manager
  2798. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2799. pass
  2800. else:
  2801. self.ui.menuhelp_bookmarks.removeAction(act)
  2802. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2803. if self.defaults["global_bookmarks"]:
  2804. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2805. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2806. # the JSON is first making the keys as strings (therefore I have to use strings too
  2807. # or do the conversion :(
  2808. # )
  2809. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2810. # the '10' entry jsut after '1' therefore ordering as strings
  2811. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2812. key=lambda x: int(x[0]))
  2813. for entry, bookmark in sorted_bookmarks:
  2814. title = bookmark[0]
  2815. weblink = bookmark[1]
  2816. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2817. act.setText(title)
  2818. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2819. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2820. if title == 'Backup Site' and weblink == "":
  2821. act.triggered.connect(self.on_backup_site)
  2822. else:
  2823. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2824. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2825. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2826. def on_bookmarks_manager(self):
  2827. """
  2828. Adds the bookmark manager in a Tab in Plot Area
  2829. :return:
  2830. """
  2831. for idx in range(self.ui.plot_tab_area.count()):
  2832. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2833. # there can be only one instance of Bookmark Manager at one time
  2834. return
  2835. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2836. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2837. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2838. # add the tab if it was closed
  2839. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2840. # delete the absolute and relative position and messages in the infobar
  2841. self.ui.position_label.setText("")
  2842. self.ui.rel_position_label.setText("")
  2843. # Switch plot_area to preferences page
  2844. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2845. def on_backup_site(self):
  2846. msgbox = QtWidgets.QMessageBox()
  2847. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2848. "1. FlatCAM.org website is down\n"
  2849. "2. Someone forked FlatCAM project and wants to point\n"
  2850. "to his own website\n\n"
  2851. "If you can't get any informations about FlatCAM beta\n"
  2852. "use the YouTube channel link from the Help menu."))
  2853. msgbox.setWindowTitle(_("Alternative website"))
  2854. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2855. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2856. msgbox.setDefaultButton(bt_yes)
  2857. msgbox.exec_()
  2858. # response = msgbox.clickedButton()
  2859. def on_file_savedefaults(self):
  2860. """
  2861. Callback for menu item File->Save Defaults. Saves application default options
  2862. ``self.defaults`` to current_defaults.FlatConfig.
  2863. :return: None
  2864. """
  2865. self.preferencesUiManager.save_defaults()
  2866. def final_save(self):
  2867. """
  2868. Callback for doing a preferences save to file whenever the application is about to quit.
  2869. If the project has changes, it will ask the user to save the project.
  2870. :return: None
  2871. """
  2872. if self.save_in_progress:
  2873. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2874. return
  2875. if self.should_we_save and self.collection.get_list():
  2876. msgbox = QtWidgets.QMessageBox()
  2877. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2878. "\n"
  2879. "Do you want to Save the project?"))
  2880. msgbox.setWindowTitle(_("Save changes"))
  2881. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2882. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2883. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2884. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2885. msgbox.setDefaultButton(bt_yes)
  2886. msgbox.exec_()
  2887. response = msgbox.clickedButton()
  2888. if response == bt_yes:
  2889. try:
  2890. self.trayIcon.hide()
  2891. except Exception:
  2892. pass
  2893. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2894. elif response == bt_no:
  2895. try:
  2896. self.trayIcon.hide()
  2897. except Exception:
  2898. pass
  2899. self.quit_application()
  2900. elif response == bt_cancel:
  2901. return
  2902. else:
  2903. try:
  2904. self.trayIcon.hide()
  2905. except Exception:
  2906. pass
  2907. self.quit_application()
  2908. def quit_application(self):
  2909. """
  2910. Called (as a pyslot or not) when the application is quit.
  2911. :return: None
  2912. """
  2913. self.preferencesUiManager.save_defaults(silent=True)
  2914. log.debug("App.quit_application() --> App Defaults saved.")
  2915. if self.cmd_line_headless != 1:
  2916. # save app state to file
  2917. stgs = QSettings("Open Source", "FlatCAM")
  2918. stgs.setValue('saved_gui_state', self.ui.saveState())
  2919. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2920. stgs.setValue(
  2921. 'language',
  2922. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2923. )
  2924. stgs.setValue(
  2925. 'notebook_font_size',
  2926. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2927. )
  2928. stgs.setValue(
  2929. 'axis_font_size',
  2930. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2931. )
  2932. stgs.setValue(
  2933. 'textbox_font_size',
  2934. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2935. )
  2936. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2937. stgs.setValue(
  2938. 'machinist',
  2939. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2940. )
  2941. # This will write the setting to the platform specific storage.
  2942. del stgs
  2943. log.debug("App.quit_application() --> App UI state saved.")
  2944. # try to quit the Socket opened by ArgsThread class
  2945. try:
  2946. self.new_launch.stop.emit()
  2947. except Exception as err:
  2948. log.debug("App.quit_application() --> %s" % str(err))
  2949. # try to quit the QThread that run ArgsThread class
  2950. try:
  2951. self.th.quit()
  2952. except Exception as e:
  2953. log.debug("App.quit_application() --> %s" % str(e))
  2954. # terminate workers
  2955. self.workers.__del__()
  2956. # quit app by signalling for self.kill_app() method
  2957. # self.close_app_signal.emit()
  2958. QtWidgets.qApp.quit()
  2959. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2960. # we use the following command
  2961. minor_v = sys.version_info.minor
  2962. if minor_v < 8:
  2963. sys.exit(0)
  2964. else:
  2965. os._exit(0) # fix to work with Python 3.8
  2966. @staticmethod
  2967. def kill_app():
  2968. QtWidgets.qApp.quit()
  2969. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2970. # we use the following command
  2971. sys.exit(0)
  2972. def on_portable_checked(self, state):
  2973. """
  2974. Callback called when the checkbox in Preferences GUI is checked.
  2975. It will set the application as portable by creating the preferences and recent files in the
  2976. 'config' folder found in the FlatCAM installation folder.
  2977. :param state: boolean, the state of the checkbox when clicked/checked
  2978. :return:
  2979. """
  2980. line_no = 0
  2981. data = None
  2982. if sys.platform != 'win32':
  2983. # this won't work in Linux or MacOS
  2984. return
  2985. # test if the app was frozen and choose the path for the configuration file
  2986. if getattr(sys, "frozen", False) is True:
  2987. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2988. else:
  2989. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2990. config_file = current_data_path + '\\configuration.txt'
  2991. try:
  2992. with open(config_file, 'r') as f:
  2993. try:
  2994. data = f.readlines()
  2995. except Exception as e:
  2996. log.debug('App.__init__() -->%s' % str(e))
  2997. return
  2998. except FileNotFoundError:
  2999. pass
  3000. for line in data:
  3001. line = line.strip('\n')
  3002. param = str(line).rpartition('=')
  3003. if param[0] == 'portable':
  3004. break
  3005. line_no += 1
  3006. if state:
  3007. data[line_no] = 'portable=True\n'
  3008. # create the new defauults files
  3009. # create current_defaults.FlatConfig file if there is none
  3010. try:
  3011. f = open(current_data_path + '/current_defaults.FlatConfig')
  3012. f.close()
  3013. except IOError:
  3014. App.log.debug('Creating empty current_defaults.FlatConfig')
  3015. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3016. json.dump({}, f)
  3017. f.close()
  3018. # create factory_defaults.FlatConfig file if there is none
  3019. try:
  3020. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3021. f.close()
  3022. except IOError:
  3023. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3024. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3025. json.dump({}, f)
  3026. f.close()
  3027. try:
  3028. f = open(current_data_path + '/recent.json')
  3029. f.close()
  3030. except IOError:
  3031. App.log.debug('Creating empty recent.json')
  3032. f = open(current_data_path + '/recent.json', 'w')
  3033. json.dump([], f)
  3034. f.close()
  3035. try:
  3036. fp = open(current_data_path + '/recent_projects.json')
  3037. fp.close()
  3038. except IOError:
  3039. App.log.debug('Creating empty recent_projects.json')
  3040. fp = open(current_data_path + '/recent_projects.json', 'w')
  3041. json.dump([], fp)
  3042. fp.close()
  3043. # save the current defaults to the new defaults file
  3044. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3045. else:
  3046. data[line_no] = 'portable=False\n'
  3047. with open(config_file, 'w') as f:
  3048. f.writelines(data)
  3049. def on_register_files(self, obj_type=None):
  3050. """
  3051. Called whenever there is a need to register file extensions with FlatCAM.
  3052. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3053. :param obj_type: the type of object to be register for.
  3054. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3055. :return: None
  3056. """
  3057. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3058. new_reg_path = 'Software\\Classes\\'
  3059. # find if the current user is admin
  3060. try:
  3061. is_admin = os.getuid() == 0
  3062. except AttributeError:
  3063. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3064. if is_admin is True:
  3065. root_path = winreg.HKEY_LOCAL_MACHINE
  3066. else:
  3067. root_path = winreg.HKEY_CURRENT_USER
  3068. # create the keys
  3069. def set_reg(name, root_pth, new_reg_path, value):
  3070. try:
  3071. winreg.CreateKey(root_pth, new_reg_path)
  3072. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3073. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3074. return True
  3075. except WindowsError:
  3076. return False
  3077. # delete key in registry
  3078. def delete_reg(root_pth, reg_path, key_to_del):
  3079. key_to_del_path = reg_path + key_to_del
  3080. try:
  3081. winreg.DeleteKey(root_pth, key_to_del_path)
  3082. return True
  3083. except WindowsError:
  3084. return False
  3085. if obj_type is None or obj_type == 'excellon':
  3086. exc_list = \
  3087. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3088. exc_list = [x for x in exc_list if x != '']
  3089. # register all keys in the Preferences window
  3090. for ext in exc_list:
  3091. new_k = new_reg_path + '.%s' % ext
  3092. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3093. # and unregister those that are no longer in the Preferences windows but are in the file
  3094. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3095. if ext not in exc_list:
  3096. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3097. # now write the updated extensions to the self.defaults
  3098. # new_ext = ''
  3099. # for ext in exc_list:
  3100. # new_ext = new_ext + ext + ', '
  3101. # self.defaults["fa_excellon"] = new_ext
  3102. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3103. if obj_type is None or obj_type == 'gcode':
  3104. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3105. gco_list = [x for x in gco_list if x != '']
  3106. # register all keys in the Preferences window
  3107. for ext in gco_list:
  3108. new_k = new_reg_path + '.%s' % ext
  3109. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3110. # and unregister those that are no longer in the Preferences windows but are in the file
  3111. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3112. if ext not in gco_list:
  3113. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3114. # now write the updated extensions to the self.defaults
  3115. # new_ext = ''
  3116. # for ext in gco_list:
  3117. # new_ext = new_ext + ext + ', '
  3118. # self.defaults["fa_gcode"] = new_ext
  3119. self.inform.emit('[success] %s' %
  3120. _("Selected GCode file extensions registered with FlatCAM."))
  3121. if obj_type is None or obj_type == 'gerber':
  3122. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3123. grb_list = [x for x in grb_list if x != '']
  3124. # register all keys in the Preferences window
  3125. for ext in grb_list:
  3126. new_k = new_reg_path + '.%s' % ext
  3127. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3128. # and unregister those that are no longer in the Preferences windows but are in the file
  3129. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3130. if ext not in grb_list:
  3131. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3132. # now write the updated extensions to the self.defaults
  3133. # new_ext = ''
  3134. # for ext in grb_list:
  3135. # new_ext = new_ext + ext + ', '
  3136. # self.defaults["fa_gerber"] = new_ext
  3137. self.inform.emit('[success] %s' %
  3138. _("Selected Gerber file extensions registered with FlatCAM."))
  3139. def add_extension(self, ext_type):
  3140. """
  3141. Add a file extension to the list for a specific object
  3142. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3143. :return:
  3144. """
  3145. if ext_type == 'excellon':
  3146. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3147. if new_ext == '':
  3148. return
  3149. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3150. if new_ext in old_val:
  3151. return
  3152. old_val.append(new_ext)
  3153. old_val.sort()
  3154. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3155. if ext_type == 'gcode':
  3156. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3157. if new_ext == '':
  3158. return
  3159. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3160. if new_ext in old_val:
  3161. return
  3162. old_val.append(new_ext)
  3163. old_val.sort()
  3164. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3165. if ext_type == 'gerber':
  3166. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3167. if new_ext == '':
  3168. return
  3169. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3170. if new_ext in old_val:
  3171. return
  3172. old_val.append(new_ext)
  3173. old_val.sort()
  3174. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3175. if ext_type == 'keyword':
  3176. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3177. if new_kw == '':
  3178. return
  3179. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3180. if new_kw in old_val:
  3181. return
  3182. old_val.append(new_kw)
  3183. old_val.sort()
  3184. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3185. # update the self.myKeywords so the model is updated
  3186. self.autocomplete_kw_list = \
  3187. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3188. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3189. self.shell._edit.set_model_data(self.myKeywords)
  3190. def del_extension(self, ext_type):
  3191. """
  3192. Remove a file extension from the list for a specific object
  3193. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3194. :return:
  3195. """
  3196. if ext_type == 'excellon':
  3197. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3198. if new_ext == '':
  3199. return
  3200. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3201. if new_ext not in old_val:
  3202. return
  3203. old_val.remove(new_ext)
  3204. old_val.sort()
  3205. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3206. if ext_type == 'gcode':
  3207. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3208. if new_ext == '':
  3209. return
  3210. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3211. if new_ext not in old_val:
  3212. return
  3213. old_val.remove(new_ext)
  3214. old_val.sort()
  3215. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3216. if ext_type == 'gerber':
  3217. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3218. if new_ext == '':
  3219. return
  3220. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3221. if new_ext not in old_val:
  3222. return
  3223. old_val.remove(new_ext)
  3224. old_val.sort()
  3225. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3226. if ext_type == 'keyword':
  3227. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3228. if new_kw == '':
  3229. return
  3230. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3231. if new_kw not in old_val:
  3232. return
  3233. old_val.remove(new_kw)
  3234. old_val.sort()
  3235. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3236. # update the self.myKeywords so the model is updated
  3237. self.autocomplete_kw_list = \
  3238. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3239. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3240. self.shell._edit.set_model_data(self.myKeywords)
  3241. def restore_extensions(self, ext_type):
  3242. """
  3243. Restore all file extensions associations with FlatCAM, for a specific object
  3244. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3245. :return:
  3246. """
  3247. if ext_type == 'excellon':
  3248. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3249. # for the ability to open Excellon files with .txt extension
  3250. new_exc_list = deepcopy(self.exc_list)
  3251. try:
  3252. new_exc_list.remove('txt')
  3253. except ValueError:
  3254. pass
  3255. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3256. if ext_type == 'gcode':
  3257. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3258. if ext_type == 'gerber':
  3259. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3260. if ext_type == 'keyword':
  3261. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3262. # update the self.myKeywords so the model is updated
  3263. self.autocomplete_kw_list = self.default_keywords
  3264. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3265. self.shell._edit.set_model_data(self.myKeywords)
  3266. def delete_all_extensions(self, ext_type):
  3267. """
  3268. Delete all file extensions associations with FlatCAM, for a specific object
  3269. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3270. :return:
  3271. """
  3272. if ext_type == 'excellon':
  3273. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3274. if ext_type == 'gcode':
  3275. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3276. if ext_type == 'gerber':
  3277. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3278. if ext_type == 'keyword':
  3279. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3280. # update the self.myKeywords so the model is updated
  3281. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3282. self.shell._edit.set_model_data(self.myKeywords)
  3283. def on_edit_join(self, name=None):
  3284. """
  3285. Callback for Edit->Join. Joins the selected geometry objects into
  3286. a new one.
  3287. :return: None
  3288. """
  3289. self.defaults.report_usage("on_edit_join()")
  3290. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3291. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3292. geo_type_set = set()
  3293. objs = self.collection.get_selected()
  3294. if len(objs) < 2:
  3295. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3296. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3297. return 'fail'
  3298. for obj in objs:
  3299. geo_type_set.add(obj.multigeo)
  3300. # if len(geo_type_list) == 1 means that all list elements are the same
  3301. if len(geo_type_set) != 1:
  3302. self.inform.emit('[ERROR] %s' %
  3303. _("Failed join. The Geometry objects are of different types.\n"
  3304. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3305. "convert from one to another and retry joining \n"
  3306. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3307. "the result may not be what was expected. \n"
  3308. "Check the generated GCODE."))
  3309. return
  3310. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3311. if True in geo_type_set:
  3312. def initialize(geo_obj, app):
  3313. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3314. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3315. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3316. for v in geo_obj.tools.values():
  3317. v['data']['name'] = obj_name_multi
  3318. self.new_object("geometry", obj_name_multi, initialize)
  3319. else:
  3320. def initialize(geo_obj, app):
  3321. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3322. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3323. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3324. for v in geo_obj.tools.values():
  3325. v['data']['name'] = obj_name_single
  3326. self.new_object("geometry", obj_name_single, initialize)
  3327. self.should_we_save = True
  3328. def on_edit_join_exc(self):
  3329. """
  3330. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3331. a new Excellon.
  3332. :return: None
  3333. """
  3334. self.defaults.report_usage("on_edit_join_exc()")
  3335. objs = self.collection.get_selected()
  3336. for obj in objs:
  3337. if not isinstance(obj, ExcellonObject):
  3338. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3339. return
  3340. if len(objs) < 2:
  3341. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3342. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3343. return 'fail'
  3344. def initialize(exc_obj, app):
  3345. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3346. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3347. self.new_object("excellon", 'Combo_Excellon', initialize)
  3348. self.should_we_save = True
  3349. def on_edit_join_grb(self):
  3350. """
  3351. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3352. a new Gerber object.
  3353. :return: None
  3354. """
  3355. self.defaults.report_usage("on_edit_join_grb()")
  3356. objs = self.collection.get_selected()
  3357. for obj in objs:
  3358. if not isinstance(obj, GerberObject):
  3359. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3360. return
  3361. if len(objs) < 2:
  3362. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3363. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3364. return 'fail'
  3365. def initialize(grb_obj, app):
  3366. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3367. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3368. self.new_object("gerber", 'Combo_Gerber', initialize)
  3369. self.should_we_save = True
  3370. def on_convert_singlegeo_to_multigeo(self):
  3371. """
  3372. Called for converting a Geometry object from single-geo to multi-geo.
  3373. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3374. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3375. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3376. the solid-geometry of that tool.
  3377. :return: None
  3378. """
  3379. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3380. obj = self.collection.get_active()
  3381. if obj is None:
  3382. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3383. return
  3384. if not isinstance(obj, GeometryObject):
  3385. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3386. return
  3387. obj.multigeo = True
  3388. for tooluid, dict_value in obj.tools.items():
  3389. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3390. if not isinstance(obj.solid_geometry, list):
  3391. obj.solid_geometry = [obj.solid_geometry]
  3392. # obj.solid_geometry[:] = []
  3393. obj.plot()
  3394. self.should_we_save = True
  3395. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3396. def on_convert_multigeo_to_singlegeo(self):
  3397. """
  3398. Called for converting a Geometry object from multi-geo to single-geo.
  3399. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3400. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3401. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3402. the solid-geometry of that tool.
  3403. :return: None
  3404. """
  3405. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3406. obj = self.collection.get_active()
  3407. if obj is None:
  3408. self.inform.emit('[ERROR_NOTCL] %s' %
  3409. _("Failed. Select a Geometry Object and try again."))
  3410. return
  3411. if not isinstance(obj, GeometryObject):
  3412. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3413. (_("Expected a GeometryObject, got"), type(obj)))
  3414. return
  3415. obj.multigeo = False
  3416. total_solid_geometry = []
  3417. for tooluid, dict_value in obj.tools.items():
  3418. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3419. # clear the original geometry
  3420. dict_value['solid_geometry'][:] = []
  3421. obj.solid_geometry = deepcopy(total_solid_geometry)
  3422. obj.plot()
  3423. self.should_we_save = True
  3424. self.inform.emit('[success] %s' %
  3425. _("A Geometry object was converted to SingleGeo type."))
  3426. def on_defaults_dict_change(self, field):
  3427. """
  3428. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3429. Edit -> Preferences tab window.
  3430. :param field: the key of the self.defaults dictionary that was changed.
  3431. :return: None
  3432. """
  3433. self.preferencesUiManager.defaults_write_form_field(field=field)
  3434. if field == "units":
  3435. self.set_screen_units(self.defaults['units'])
  3436. def set_screen_units(self, units):
  3437. """
  3438. Set the FlatCAM units on the status bar.
  3439. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3440. :return: None
  3441. """
  3442. self.ui.units_label.setText("[" + units.lower() + "]")
  3443. def on_toggle_units_click(self):
  3444. try:
  3445. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3446. except (TypeError, AttributeError):
  3447. pass
  3448. if self.defaults["units"] == 'MM':
  3449. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3450. else:
  3451. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3452. self.on_toggle_units(no_pref=True)
  3453. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3454. lambda: self.on_toggle_units(no_pref=False))
  3455. def on_toggle_units(self, no_pref=False):
  3456. """
  3457. Callback for the Units radio-button change in the Preferences tab.
  3458. Changes the application's default units adn for the project too.
  3459. If changing the project's units, the change propagates to all of
  3460. the objects in the project.
  3461. :return: None
  3462. """
  3463. self.defaults.report_usage("on_toggle_units")
  3464. if self.toggle_units_ignore:
  3465. return
  3466. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3467. # If option is the same, then ignore
  3468. if new_units == self.defaults["units"].upper():
  3469. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3470. return
  3471. # Keys in self.defaults for which to scale their values
  3472. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3473. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3474. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3475. "gerber_editor_ma_high",
  3476. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3477. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3478. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3479. "excellon_feedrate_probe", "excellon_milling_dia",
  3480. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3481. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3482. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3483. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3484. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3485. "geometry_extracut_length", "geometry_z_pdepth",
  3486. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3487. 'cncjob_tooldia',
  3488. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3489. "tools_paintnewdia",
  3490. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3491. "tools_nccnewdia", "tools_ncc_offset_value",
  3492. "tools_2sided_drilldia",
  3493. "tools_film_boundary", "tools_film_scale_stroke",
  3494. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3495. "tools_cutout_depthperpass",
  3496. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3497. "tools_panelize_spacing_rows",
  3498. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3499. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3500. "tools_transform_buffer_dis",
  3501. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3502. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3503. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3504. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3505. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3506. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3507. "tools_cr_h2h_val", "tools_cr_dh_val",
  3508. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3509. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3510. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3511. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3512. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3513. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3514. "tools_copper_thieving_mask_clearance",
  3515. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3516. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3517. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3518. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3519. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3520. "tools_invert_margin",
  3521. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3522. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3523. def scale_defaults(sfactor):
  3524. for dim in dimensions:
  3525. if dim in [
  3526. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3527. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3528. 'tools_transform_mirror_point'
  3529. ]:
  3530. if self.defaults[dim] is None or self.defaults[dim] == '':
  3531. continue
  3532. try:
  3533. coordinates = self.defaults[dim].split(",")
  3534. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3535. coords_xy[0] *= sfactor
  3536. coords_xy[1] *= sfactor
  3537. self.defaults[dim] = "%.*f, %.*f" % (
  3538. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3539. except Exception as e:
  3540. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3541. elif dim in [
  3542. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3543. ]:
  3544. if self.defaults[dim] is None or self.defaults[dim] == '':
  3545. continue
  3546. try:
  3547. self.defaults[dim] = float(self.defaults[dim])
  3548. tools_diameters = [self.defaults[dim]]
  3549. except ValueError:
  3550. try:
  3551. tools_string = self.defaults[dim].split(",")
  3552. tools_diameters = [eval(a) for a in tools_string if a != '']
  3553. except Exception as e:
  3554. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3555. continue
  3556. self.defaults[dim] = ''
  3557. td_len = len(tools_diameters)
  3558. if td_len > 1:
  3559. for t in range(td_len):
  3560. tools_diameters[t] *= sfactor
  3561. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3562. else:
  3563. tools_diameters[0] *= sfactor
  3564. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3565. elif dim in ['global_gridx', 'global_gridy']:
  3566. # format the number of decimals to the one specified in self.decimals
  3567. try:
  3568. val = float(self.defaults[dim]) * sfactor
  3569. except Exception as e:
  3570. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3571. continue
  3572. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3573. else:
  3574. # the number of decimals for the rest is kept unchanged
  3575. if self.defaults[dim]:
  3576. try:
  3577. val = float(self.defaults[dim]) * sfactor
  3578. except Exception as e:
  3579. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3580. continue
  3581. self.defaults[dim] = val
  3582. # The scaling factor depending on choice of units.
  3583. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3584. # Changing project units. Warn user.
  3585. msgbox = QtWidgets.QMessageBox()
  3586. msgbox.setWindowTitle(_("Toggle Units"))
  3587. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3588. msgbox.setText(_("Changing the units of the project\n"
  3589. "will scale all objects.\n\n"
  3590. "Do you want to continue?"))
  3591. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3592. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3593. msgbox.setDefaultButton(bt_ok)
  3594. msgbox.exec_()
  3595. response = msgbox.clickedButton()
  3596. if response == bt_ok:
  3597. if no_pref is False:
  3598. self.preferencesUiManager.defaults_read_form()
  3599. scale_defaults(factor)
  3600. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3601. self.defaults["units"] = new_units
  3602. # update the defaults from form, some may assume that the conversion is enough and it's not
  3603. self.on_options_app2project()
  3604. # update the objects
  3605. for obj in self.collection.get_list():
  3606. obj.convert_units(new_units)
  3607. # make that the properties stored in the object are also updated
  3608. self.object_changed.emit(obj)
  3609. # rebuild the object UI
  3610. obj.build_ui()
  3611. # change this only if the workspace is active
  3612. if self.defaults['global_workspace'] is True:
  3613. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3614. # adjust the grid values on the main toolbar
  3615. val_x = float(self.defaults['global_gridx']) * factor
  3616. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3617. current = self.collection.get_active()
  3618. if current is not None:
  3619. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3620. if not isinstance(current, GeometryObject):
  3621. current.to_form()
  3622. # replot all objects
  3623. self.plot_all()
  3624. # set the status labels to reflect the current FlatCAM units
  3625. self.set_screen_units(new_units)
  3626. # signal to the app that we changed the object properties and it should save the project
  3627. self.should_we_save = True
  3628. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3629. else:
  3630. # Undo toggling
  3631. self.toggle_units_ignore = True
  3632. if self.defaults['units'].upper() == 'MM':
  3633. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3634. else:
  3635. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3636. self.toggle_units_ignore = False
  3637. # store the grid values so they are not changed in the next step
  3638. val_x = float(self.defaults['global_gridx'])
  3639. val_y = float(self.defaults['global_gridy'])
  3640. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3641. self.preferencesUiManager.defaults_read_form()
  3642. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3643. # in self.defaults from the GUI elements but
  3644. # I don't want it for the grid values, so I update them here
  3645. self.defaults['global_gridx'] = val_x
  3646. self.defaults['global_gridy'] = val_y
  3647. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3648. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3649. def on_fullscreen(self, disable=False):
  3650. self.defaults.report_usage("on_fullscreen()")
  3651. flags = self.ui.windowFlags()
  3652. if self.toggle_fscreen is False and disable is False:
  3653. # self.ui.showFullScreen()
  3654. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3655. a = self.ui.geometry()
  3656. self.x_pos = a.x()
  3657. self.y_pos = a.y()
  3658. self.width = a.width()
  3659. self.height = a.height()
  3660. # set new geometry to full desktop rect
  3661. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3662. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3663. # everything else will not work without this hack. This happen in Windows.
  3664. # https://bugreports.qt.io/browse/QTBUG-41309
  3665. desktop = QtWidgets.QApplication.desktop()
  3666. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3667. rec = desktop.screenGeometry(screen)
  3668. x = rec.x() - 1
  3669. y = rec.y() - 1
  3670. h = rec.height() + 2
  3671. w = rec.width() + 2
  3672. self.ui.setGeometry(x, y, w, h)
  3673. self.ui.show()
  3674. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3675. tb.setVisible(False)
  3676. self.ui.snap_toolbar.setVisible(True) # This is always visible
  3677. # self.ui.splitter_left.setVisible(False)
  3678. self.ui.splitter.setSizes([0, 1])
  3679. self.toggle_fscreen = True
  3680. elif self.toggle_fscreen is True or disable is True:
  3681. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3682. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3683. self.ui.showNormal()
  3684. self.restore_toolbar_view()
  3685. # self.ui.splitter_left.setVisible(True)
  3686. self.toggle_fscreen = False
  3687. def on_toggle_plotarea(self):
  3688. self.defaults.report_usage("on_toggle_plotarea()")
  3689. try:
  3690. name = self.ui.plot_tab_area.widget(0).objectName()
  3691. except AttributeError:
  3692. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3693. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3694. self.ui.plot_tab_area.protectTab(0)
  3695. return
  3696. if name != 'plotarea_tab':
  3697. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3698. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3699. self.ui.plot_tab_area.protectTab(0)
  3700. else:
  3701. self.ui.plot_tab_area.closeTab(0)
  3702. def on_toggle_notebook(self):
  3703. if self.ui.splitter.sizes()[0] == 0:
  3704. self.ui.splitter.setSizes([1, 1])
  3705. self.ui.menu_toggle_nb.setChecked(True)
  3706. else:
  3707. self.ui.splitter.setSizes([0, 1])
  3708. self.ui.menu_toggle_nb.setChecked(False)
  3709. def on_toggle_axis(self):
  3710. self.defaults.report_usage("on_toggle_axis()")
  3711. if self.toggle_axis is False:
  3712. if self.is_legacy is False:
  3713. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3714. parent=self.plotcanvas.view.scene)
  3715. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3716. parent=self.plotcanvas.view.scene)
  3717. else:
  3718. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3719. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3720. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3721. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3722. self.plotcanvas.canvas.draw()
  3723. self.toggle_axis = True
  3724. else:
  3725. if self.is_legacy is False:
  3726. self.plotcanvas.v_line.parent = None
  3727. self.plotcanvas.h_line.parent = None
  3728. else:
  3729. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3730. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3731. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3732. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3733. self.plotcanvas.canvas.draw()
  3734. self.toggle_axis = False
  3735. def on_toggle_grid(self):
  3736. self.defaults.report_usage("on_toggle_grid()")
  3737. self.ui.grid_snap_btn.trigger()
  3738. def on_toggle_grid_lines(self):
  3739. self.defaults.report_usage("on_toggle_grd_lines()")
  3740. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3741. if tt_settings.contains("theme"):
  3742. theme = tt_settings.value('theme', type=str)
  3743. else:
  3744. theme = 'white'
  3745. if self.toggle_grid_lines is False:
  3746. if self.is_legacy is False:
  3747. if theme == 'white':
  3748. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3749. else:
  3750. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3751. else:
  3752. self.plotcanvas.axes.grid(True)
  3753. try:
  3754. self.plotcanvas.canvas.draw()
  3755. except IndexError:
  3756. pass
  3757. pass
  3758. self.toggle_grid_lines = True
  3759. else:
  3760. if self.is_legacy is False:
  3761. if theme == 'white':
  3762. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3763. else:
  3764. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3765. else:
  3766. self.plotcanvas.axes.grid(False)
  3767. try:
  3768. self.plotcanvas.canvas.draw()
  3769. except IndexError:
  3770. pass
  3771. self.toggle_grid_lines = False
  3772. if self.is_legacy is False:
  3773. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3774. # - perhaps is a bug in VisPy implementation
  3775. if self.grid_status() is True:
  3776. self.app_cursor.enabled = False
  3777. self.app_cursor.enabled = True
  3778. else:
  3779. self.app_cursor.enabled = True
  3780. self.app_cursor.enabled = False
  3781. def on_update_exc_export(self, state):
  3782. """
  3783. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3784. if the update_excellon_cb checkbox is checked
  3785. :param state: state of the checkbox whose signals is tied to his slot
  3786. :return:
  3787. """
  3788. if state:
  3789. # first try to disconnect
  3790. try:
  3791. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3792. disconnect(self.on_excellon_format_changed)
  3793. except TypeError:
  3794. pass
  3795. try:
  3796. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3797. disconnect(self.on_excellon_format_changed)
  3798. except TypeError:
  3799. pass
  3800. try:
  3801. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3802. disconnect(self.on_excellon_format_changed)
  3803. except TypeError:
  3804. pass
  3805. try:
  3806. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3807. disconnect(self.on_excellon_format_changed)
  3808. except TypeError:
  3809. pass
  3810. try:
  3811. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3812. disconnect(self.on_excellon_zeros_changed)
  3813. except TypeError:
  3814. pass
  3815. try:
  3816. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3817. disconnect(self.on_excellon_zeros_changed)
  3818. except TypeError:
  3819. pass
  3820. # the connect them
  3821. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3822. self.on_excellon_format_changed)
  3823. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3824. self.on_excellon_format_changed)
  3825. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3826. self.on_excellon_format_changed)
  3827. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3828. self.on_excellon_format_changed)
  3829. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3830. self.on_excellon_zeros_changed)
  3831. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3832. self.on_excellon_units_changed)
  3833. else:
  3834. # disconnect the signals
  3835. try:
  3836. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3837. disconnect(self.on_excellon_format_changed)
  3838. except TypeError:
  3839. pass
  3840. try:
  3841. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3842. disconnect(self.on_excellon_format_changed)
  3843. except TypeError:
  3844. pass
  3845. try:
  3846. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3847. disconnect(self.on_excellon_format_changed)
  3848. except TypeError:
  3849. pass
  3850. try:
  3851. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3852. disconnect(self.on_excellon_format_changed)
  3853. except TypeError:
  3854. pass
  3855. try:
  3856. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3857. disconnect(self.on_excellon_zeros_changed)
  3858. except TypeError:
  3859. pass
  3860. try:
  3861. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3862. disconnect(self.on_excellon_zeros_changed)
  3863. except TypeError:
  3864. pass
  3865. def on_excellon_format_changed(self):
  3866. """
  3867. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3868. :return: None
  3869. """
  3870. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3871. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3872. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3873. )
  3874. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3875. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3876. )
  3877. else:
  3878. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3879. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3880. )
  3881. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3882. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3883. )
  3884. def on_excellon_zeros_changed(self):
  3885. """
  3886. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3887. :return: None
  3888. """
  3889. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3890. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3891. )
  3892. def on_excellon_units_changed(self):
  3893. """
  3894. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3895. :return: None
  3896. """
  3897. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3898. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3899. )
  3900. self.on_excellon_format_changed()
  3901. def on_film_color_entry(self):
  3902. self.defaults['tools_film_color'] = \
  3903. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3904. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3905. "background-color:%s;"
  3906. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3907. )
  3908. def on_film_color_button(self):
  3909. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3910. c_dialog = QtWidgets.QColorDialog()
  3911. film_color = c_dialog.getColor(initial=current_color)
  3912. if film_color.isValid() is False:
  3913. return
  3914. # if new color is different then mark that the Preferences are changed
  3915. if film_color != current_color:
  3916. self.preferencesUiManager.on_preferences_edited()
  3917. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3918. "background-color:%s;"
  3919. "border-color: dimgray" % str(film_color.name())
  3920. )
  3921. new_val_sel = str(film_color.name())
  3922. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3923. self.defaults['tools_film_color'] = new_val_sel
  3924. def on_qrcode_fill_color_entry(self):
  3925. self.defaults['tools_qrcode_fill_color'] = \
  3926. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3927. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3928. "background-color:%s;"
  3929. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3930. )
  3931. def on_qrcode_fill_color_button(self):
  3932. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3933. c_dialog = QtWidgets.QColorDialog()
  3934. fill_color = c_dialog.getColor(initial=current_color)
  3935. if fill_color.isValid() is False:
  3936. return
  3937. # if new color is different then mark that the Preferences are changed
  3938. if fill_color != current_color:
  3939. self.preferencesUiManager.on_preferences_edited()
  3940. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3941. "background-color:%s;"
  3942. "border-color: dimgray" % str(fill_color.name())
  3943. )
  3944. new_val_sel = str(fill_color.name())
  3945. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3946. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3947. def on_qrcode_back_color_entry(self):
  3948. self.defaults['tools_qrcode_back_color'] = \
  3949. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3950. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3951. "background-color:%s;"
  3952. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3953. )
  3954. def on_qrcode_back_color_button(self):
  3955. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3956. c_dialog = QtWidgets.QColorDialog()
  3957. back_color = c_dialog.getColor(initial=current_color)
  3958. if back_color.isValid() is False:
  3959. return
  3960. # if new color is different then mark that the Preferences are changed
  3961. if back_color != current_color:
  3962. self.preferencesUiManager.on_preferences_edited()
  3963. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3964. "background-color:%s;"
  3965. "border-color: dimgray" % str(back_color.name())
  3966. )
  3967. new_val_sel = str(back_color.name())
  3968. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3969. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3970. def on_tab_rmb_click(self, checked):
  3971. self.ui.notebook.set_detachable(val=checked)
  3972. self.defaults["global_tabs_detachable"] = checked
  3973. self.ui.plot_tab_area.set_detachable(val=checked)
  3974. self.defaults["global_tabs_detachable"] = checked
  3975. def on_tab_setup_context_menu(self):
  3976. initial_checked = self.defaults["global_tabs_detachable"]
  3977. action_name = str(_("Detachable Tabs"))
  3978. action = QtWidgets.QAction(self)
  3979. action.setCheckable(True)
  3980. action.setText(action_name)
  3981. action.setChecked(initial_checked)
  3982. self.ui.notebook.tabBar.addAction(action)
  3983. self.ui.plot_tab_area.tabBar.addAction(action)
  3984. try:
  3985. action.triggered.disconnect()
  3986. except TypeError:
  3987. pass
  3988. action.triggered.connect(self.on_tab_rmb_click)
  3989. def on_deselect_all(self):
  3990. self.collection.set_all_inactive()
  3991. self.delete_selection_shape()
  3992. def on_workspace_modified(self):
  3993. # self.save_defaults(silent=True)
  3994. if self.is_legacy is True:
  3995. self.plotcanvas.delete_workspace()
  3996. self.preferencesUiManager.defaults_read_form()
  3997. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3998. def on_workspace(self):
  3999. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4000. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4001. else:
  4002. self.plotcanvas.delete_workspace()
  4003. self.preferencesUiManager.defaults_read_form()
  4004. # self.save_defaults(silent=True)
  4005. def on_workspace_toggle(self):
  4006. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4007. try:
  4008. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4009. except TypeError:
  4010. pass
  4011. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4012. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4013. self.on_workspace()
  4014. def on_cursor_type(self, val):
  4015. """
  4016. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4017. :return: None
  4018. """
  4019. self.app_cursor.enabled = False
  4020. if val == 'small':
  4021. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4022. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4023. self.app_cursor = self.plotcanvas.new_cursor()
  4024. else:
  4025. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4026. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4027. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4028. if self.ui.grid_snap_btn.isChecked():
  4029. self.app_cursor.enabled = True
  4030. else:
  4031. self.app_cursor.enabled = False
  4032. def on_tool_add_keypress(self):
  4033. # ## Current application units in Upper Case
  4034. self.units = self.defaults['units'].upper()
  4035. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4036. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4037. if notebook_widget_name == 'selected_tab':
  4038. if self.collection.get_active().kind == 'geometry':
  4039. # Tool add works for Geometry only if Advanced is True in Preferences
  4040. if self.defaults["global_app_level"] == 'a':
  4041. tool_add_popup = FCInputDialog(title="New Tool ...",
  4042. text='Enter a Tool Diameter:',
  4043. min=0.0000, max=99.9999, decimals=4)
  4044. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4045. val, ok = tool_add_popup.get_value()
  4046. if ok:
  4047. if float(val) == 0:
  4048. self.inform.emit('[WARNING_NOTCL] %s' %
  4049. _("Please enter a tool diameter with non-zero value, in Float format."))
  4050. return
  4051. self.collection.get_active().on_tool_add(dia=float(val))
  4052. else:
  4053. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4054. else:
  4055. msgbox = QtWidgets.QMessageBox()
  4056. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4057. "Go to Preferences -> General - Show Advanced Options."))
  4058. msgbox.setWindowTitle("Tool adding ...")
  4059. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4060. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4061. msgbox.setDefaultButton(bt_ok)
  4062. msgbox.exec_()
  4063. # work only if the notebook tab on focus is the Tools_Tab
  4064. if notebook_widget_name == 'tool_tab':
  4065. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4066. # and only if the tool is NCC Tool
  4067. if tool_widget == self.ncclear_tool.toolName:
  4068. self.ncclear_tool.on_add_tool_by_key()
  4069. # and only if the tool is Paint Area Tool
  4070. elif tool_widget == self.paint_tool.toolName:
  4071. self.paint_tool.on_add_tool_by_key()
  4072. # and only if the tool is Solder Paste Dispensing Tool
  4073. elif tool_widget == self.paste_tool.toolName:
  4074. self.paste_tool.on_add_tool_by_key()
  4075. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4076. # See description below.
  4077. def on_delete_keypress(self):
  4078. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4079. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4080. if notebook_widget_name == 'selected_tab':
  4081. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4082. self.collection.get_active().on_tool_delete()
  4083. # work only if the notebook tab on focus is the Tools_Tab
  4084. elif notebook_widget_name == 'tool_tab':
  4085. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4086. # and only if the tool is NCC Tool
  4087. if tool_widget == self.ncclear_tool.toolName:
  4088. self.ncclear_tool.on_tool_delete()
  4089. # and only if the tool is Paint Tool
  4090. elif tool_widget == self.paint_tool.toolName:
  4091. self.paint_tool.on_tool_delete()
  4092. # and only if the tool is Solder Paste Dispensing Tool
  4093. elif tool_widget == self.paste_tool.toolName:
  4094. self.paste_tool.on_tool_delete()
  4095. else:
  4096. self.on_delete()
  4097. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4098. # some screens you have to be careful where you hover with your mouse.
  4099. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4100. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4101. # Complicated, I know :)
  4102. def on_delete(self, force_deletion=False):
  4103. """
  4104. Delete the currently selected FlatCAMObjs.
  4105. :param force_deletion: used by Tcl command
  4106. :return: None
  4107. """
  4108. self.defaults.report_usage("on_delete()")
  4109. response = None
  4110. bt_ok = None
  4111. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4112. # a geometry object before we update it.
  4113. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4114. and self.grb_editor.editor_active is False:
  4115. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4116. msgbox = QtWidgets.QMessageBox()
  4117. msgbox.setWindowTitle(_("Delete objects"))
  4118. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4119. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4120. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4121. "the selected objects?"))
  4122. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4123. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4124. msgbox.setDefaultButton(bt_ok)
  4125. msgbox.exec_()
  4126. response = msgbox.clickedButton()
  4127. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4128. response = bt_ok
  4129. if response == bt_ok:
  4130. if self.collection.get_active():
  4131. self.log.debug("App.on_delete()")
  4132. for obj_active in self.collection.get_selected():
  4133. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4134. if obj_active.kind == 'gerber':
  4135. for el in obj_active.mark_shapes:
  4136. obj_active.mark_shapes[el].clear(update=True)
  4137. obj_active.mark_shapes[el].enabled = False
  4138. # obj_active.mark_shapes[el] = None
  4139. del el
  4140. elif isinstance(obj_active, CNCJobObject):
  4141. try:
  4142. obj_active.text_col.enabled = False
  4143. del obj_active.text_col
  4144. obj_active.annotation.clear(update=True)
  4145. del obj_active.annotation
  4146. except AttributeError as e:
  4147. log.debug(
  4148. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4149. )
  4150. while self.collection.get_selected():
  4151. self.delete_first_selected()
  4152. self.inform.emit('%s...' % _("Object(s) deleted"))
  4153. # make sure that the selection shape is deleted, too
  4154. self.delete_selection_shape()
  4155. # if there are no longer objects delete also the exclusion areas shapes
  4156. if not self.collection.get_list():
  4157. self.exc_areas.clear_shapes()
  4158. else:
  4159. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4160. else:
  4161. self.inform.emit(_("Save the work in Editor and try again ..."))
  4162. def delete_first_selected(self):
  4163. # Keep this for later
  4164. try:
  4165. sel_obj = self.collection.get_active()
  4166. name = sel_obj.options["name"]
  4167. isPlotted = sel_obj.options["plot"]
  4168. except AttributeError:
  4169. self.log.debug("Nothing selected for deletion")
  4170. return
  4171. if self.is_legacy is True:
  4172. # Remove plot only if the object was plotted otherwise delaxes will fail
  4173. if isPlotted:
  4174. try:
  4175. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4176. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4177. except Exception as e:
  4178. log.debug("App.delete_first_selected() --> %s" % str(e))
  4179. self.plotcanvas.auto_adjust_axes()
  4180. # Remove from dictionary
  4181. self.collection.delete_active()
  4182. # Clear form
  4183. self.setup_component_editor()
  4184. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4185. def on_set_origin(self):
  4186. """
  4187. Set the origin to the left mouse click position
  4188. :return: None
  4189. """
  4190. # display the message for the user
  4191. # and ask him to click on the desired position
  4192. self.defaults.report_usage("on_set_origin()")
  4193. def origin_replot():
  4194. def worker_task():
  4195. with self.proc_container.new('%s...' % _("Plotting")):
  4196. for obj in self.collection.get_list():
  4197. obj.plot()
  4198. self.plotcanvas.fit_view()
  4199. if self.is_legacy:
  4200. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4201. else:
  4202. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4203. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4204. self.inform.emit(_('Click to set the origin ...'))
  4205. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4206. # first disconnect it as it may have been used by something else
  4207. try:
  4208. self.replot_signal.disconnect()
  4209. except TypeError:
  4210. pass
  4211. self.replot_signal[list].connect(origin_replot)
  4212. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4213. """
  4214. :param event:
  4215. :param location:
  4216. :param noplot:
  4217. :param use_thread:
  4218. :return:
  4219. """
  4220. noplot_sig = noplot
  4221. def worker_task():
  4222. with self.proc_container.new(_("Setting Origin...")):
  4223. obj_list = self.collection.get_list()
  4224. for obj in obj_list:
  4225. obj.offset((x, y))
  4226. self.object_changed.emit(obj)
  4227. # Update the object bounding box options
  4228. a, b, c, d = obj.bounds()
  4229. obj.options['xmin'] = a
  4230. obj.options['ymin'] = b
  4231. obj.options['xmax'] = c
  4232. obj.options['ymax'] = d
  4233. self.inform.emit('[success] %s...' % _('Origin set'))
  4234. for obj in obj_list:
  4235. out_name = obj.options["name"]
  4236. if obj.kind == 'gerber':
  4237. obj.source_file = self.export_gerber(
  4238. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4239. elif obj.kind == 'excellon':
  4240. obj.source_file = self.export_excellon(
  4241. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4242. if noplot_sig is False:
  4243. self.replot_signal.emit([])
  4244. if location is not None:
  4245. if len(location) != 2:
  4246. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4247. return 'fail'
  4248. x, y = location
  4249. if use_thread is True:
  4250. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4251. else:
  4252. worker_task()
  4253. self.should_we_save = True
  4254. return
  4255. if event.button == 1:
  4256. if self.is_legacy is False:
  4257. event_pos = event.pos
  4258. else:
  4259. event_pos = (event.xdata, event.ydata)
  4260. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4261. if self.grid_status():
  4262. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4263. else:
  4264. pos = pos_canvas
  4265. x = 0 - pos[0]
  4266. y = 0 - pos[1]
  4267. if use_thread is True:
  4268. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4269. else:
  4270. worker_task()
  4271. self.should_we_save = True
  4272. def on_move2origin(self, use_thread=True):
  4273. """
  4274. Move selected objects to origin.
  4275. :param use_thread: Control if to use threaded operation. Boolean.
  4276. :return:
  4277. """
  4278. def worker_task():
  4279. with self.proc_container.new(_("Moving to Origin...")):
  4280. obj_list = self.collection.get_selected()
  4281. if not obj_list:
  4282. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4283. return
  4284. xminlist = []
  4285. yminlist = []
  4286. # first get a bounding box to fit all
  4287. for obj in obj_list:
  4288. xmin, ymin, xmax, ymax = obj.bounds()
  4289. xminlist.append(xmin)
  4290. yminlist.append(ymin)
  4291. # get the minimum x,y for all objects selected
  4292. x = min(xminlist)
  4293. y = min(yminlist)
  4294. for obj in obj_list:
  4295. obj.offset((-x, -y))
  4296. self.object_changed.emit(obj)
  4297. # Update the object bounding box options
  4298. a, b, c, d = obj.bounds()
  4299. obj.options['xmin'] = a
  4300. obj.options['ymin'] = b
  4301. obj.options['xmax'] = c
  4302. obj.options['ymax'] = d
  4303. for obj in obj_list:
  4304. obj.plot()
  4305. for obj in obj_list:
  4306. out_name = obj.options["name"]
  4307. if obj.kind == 'gerber':
  4308. obj.source_file = self.export_gerber(
  4309. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4310. elif obj.kind == 'excellon':
  4311. obj.source_file = self.export_excellon(
  4312. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4313. self.inform.emit('[success] %s...' % _('Origin set'))
  4314. if use_thread is True:
  4315. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4316. else:
  4317. worker_task()
  4318. self.should_we_save = True
  4319. def on_jump_to(self, custom_location=None, fit_center=True):
  4320. """
  4321. Jump to a location by setting the mouse cursor location.
  4322. :param custom_location: Jump to a specified point. (x, y) tuple.
  4323. :param fit_center: If to fit view. Boolean.
  4324. :return:
  4325. """
  4326. self.defaults.report_usage("on_jump_to()")
  4327. if not custom_location:
  4328. dia_box_location = None
  4329. try:
  4330. dia_box_location = eval(self.clipboard.text())
  4331. except Exception:
  4332. pass
  4333. if type(dia_box_location) == tuple:
  4334. dia_box_location = str(dia_box_location)
  4335. else:
  4336. dia_box_location = None
  4337. # dia_box = Dialog_box(title=_("Jump to ..."),
  4338. # label=_("Enter the coordinates in format X,Y:"),
  4339. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4340. # initial_text=dia_box_location)
  4341. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4342. label=_("Enter the coordinates in format X,Y:"),
  4343. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4344. initial_text=dia_box_location,
  4345. reference=self.defaults['global_jump_ref'])
  4346. if dia_box.ok is True:
  4347. try:
  4348. location = eval(dia_box.location)
  4349. if not isinstance(location, tuple):
  4350. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4351. return
  4352. if dia_box.reference == 'rel':
  4353. rel_x = self.mouse[0] + location[0]
  4354. rel_y = self.mouse[1] + location[1]
  4355. location = (rel_x, rel_y)
  4356. self.defaults['global_jump_ref'] = dia_box.reference
  4357. except Exception:
  4358. return
  4359. else:
  4360. return
  4361. else:
  4362. location = custom_location
  4363. self.jump_signal.emit(location)
  4364. if fit_center:
  4365. self.plotcanvas.fit_center(loc=location)
  4366. cursor = QtGui.QCursor()
  4367. if self.is_legacy is False:
  4368. # I don't know where those differences come from but they are constant for the current
  4369. # execution of the application and they are multiples of a value around 0.0263mm.
  4370. # In a random way sometimes they are more sometimes they are less
  4371. # if units == 'MM':
  4372. # cal_factor = 0.0263
  4373. # else:
  4374. # cal_factor = 0.0263 / 25.4
  4375. cal_location = (location[0], location[1])
  4376. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4377. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4378. j_pos = (
  4379. int(canvas_origin.x() + round(jump_loc[0])),
  4380. int(canvas_origin.y() + round(jump_loc[1]))
  4381. )
  4382. cursor.setPos(j_pos[0], j_pos[1])
  4383. else:
  4384. # find the canvas origin which is in the top left corner
  4385. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4386. # determine the coordinates for the lowest left point of the canvas
  4387. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4388. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4389. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4390. # canvas) and the point (width, height) is in the top-right location
  4391. loc = self.plotcanvas.axes.transData.transform_point(location)
  4392. j_pos = (
  4393. int(x0 + loc[0]),
  4394. int(y0 - loc[1])
  4395. )
  4396. cursor.setPos(j_pos[0], j_pos[1])
  4397. self.plotcanvas.mouse = [location[0], location[1]]
  4398. if self.defaults["global_cursor_color_enabled"] is True:
  4399. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4400. else:
  4401. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4402. if self.grid_status():
  4403. # Update cursor
  4404. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4405. symbol='++', edge_color=self.cursor_color_3D,
  4406. edge_width=self.defaults["global_cursor_width"],
  4407. size=self.defaults["global_cursor_size"])
  4408. # Set the relative position label
  4409. dx = location[0] - float(self.rel_point1[0])
  4410. dy = location[1] - float(self.rel_point1[1])
  4411. # self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4412. # "<b>Y</b>: %.4f" % (location[0], location[1]))
  4413. # # Set the position label
  4414. #
  4415. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4416. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4417. units = self.defaults["units"].lower()
  4418. self.plotcanvas.text_hud.text = \
  4419. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4420. dx, units, dy, units, location[0], units, location[1], units)
  4421. self.inform.emit('[success] %s' % _("Done."))
  4422. return location
  4423. def on_locate(self, obj, fit_center=True):
  4424. """
  4425. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4426. :param obj: The object on which to locate certain points
  4427. :param fit_center: If to fit view. Boolean.
  4428. :return: A point location. (x, y) tuple.
  4429. """
  4430. self.defaults.report_usage("on_locate()")
  4431. if obj is None:
  4432. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4433. return 'fail'
  4434. class DialogBoxChoice(QtWidgets.QDialog):
  4435. def __init__(self, title=None, icon=None, choice='bl'):
  4436. """
  4437. :param title: string with the window title
  4438. """
  4439. super(DialogBoxChoice, self).__init__()
  4440. self.ok = False
  4441. self.setWindowIcon(icon)
  4442. self.setWindowTitle(str(title))
  4443. self.form = QtWidgets.QFormLayout(self)
  4444. self.ref_radio = RadioSet([
  4445. {"label": _("Bottom-Left"), "value": "bl"},
  4446. {"label": _("Top-Left"), "value": "tl"},
  4447. {"label": _("Bottom-Right"), "value": "br"},
  4448. {"label": _("Top-Right"), "value": "tr"},
  4449. {"label": _("Center"), "value": "c"}
  4450. ], orientation='vertical', stretch=False)
  4451. self.ref_radio.set_value(choice)
  4452. self.form.addRow(self.ref_radio)
  4453. self.button_box = QtWidgets.QDialogButtonBox(
  4454. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4455. Qt.Horizontal, parent=self)
  4456. self.form.addRow(self.button_box)
  4457. self.button_box.accepted.connect(self.accept)
  4458. self.button_box.rejected.connect(self.reject)
  4459. if self.exec_() == QtWidgets.QDialog.Accepted:
  4460. self.ok = True
  4461. self.location_point = self.ref_radio.get_value()
  4462. else:
  4463. self.ok = False
  4464. self.location_point = None
  4465. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4466. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4467. choice=self.defaults['global_locate_pt'])
  4468. if dia_box.ok is True:
  4469. try:
  4470. location_point = dia_box.location_point
  4471. self.defaults['global_locate_pt'] = dia_box.location_point
  4472. except Exception:
  4473. return
  4474. else:
  4475. return
  4476. loc_b = obj.bounds()
  4477. if location_point == 'bl':
  4478. location = (loc_b[0], loc_b[1])
  4479. elif location_point == 'tl':
  4480. location = (loc_b[0], loc_b[3])
  4481. elif location_point == 'br':
  4482. location = (loc_b[2], loc_b[1])
  4483. elif location_point == 'tr':
  4484. location = (loc_b[2], loc_b[3])
  4485. else:
  4486. # center
  4487. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4488. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4489. location = (cx, cy)
  4490. self.locate_signal.emit(location, location_point)
  4491. if fit_center:
  4492. self.plotcanvas.fit_center(loc=location)
  4493. cursor = QtGui.QCursor()
  4494. if self.is_legacy is False:
  4495. # I don't know where those differences come from but they are constant for the current
  4496. # execution of the application and they are multiples of a value around 0.0263mm.
  4497. # In a random way sometimes they are more sometimes they are less
  4498. # if units == 'MM':
  4499. # cal_factor = 0.0263
  4500. # else:
  4501. # cal_factor = 0.0263 / 25.4
  4502. cal_location = (location[0], location[1])
  4503. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4504. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4505. j_pos = (
  4506. int(canvas_origin.x() + round(jump_loc[0])),
  4507. int(canvas_origin.y() + round(jump_loc[1]))
  4508. )
  4509. cursor.setPos(j_pos[0], j_pos[1])
  4510. else:
  4511. # find the canvas origin which is in the top left corner
  4512. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4513. # determine the coordinates for the lowest left point of the canvas
  4514. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4515. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4516. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4517. # canvas) and the point (width, height) is in the top-right location
  4518. loc = self.plotcanvas.axes.transData.transform_point(location)
  4519. j_pos = (
  4520. int(x0 + loc[0]),
  4521. int(y0 - loc[1])
  4522. )
  4523. cursor.setPos(j_pos[0], j_pos[1])
  4524. self.plotcanvas.mouse = [location[0], location[1]]
  4525. if self.defaults["global_cursor_color_enabled"] is True:
  4526. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4527. else:
  4528. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4529. if self.grid_status():
  4530. # Update cursor
  4531. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4532. symbol='++', edge_color=self.cursor_color_3D,
  4533. edge_width=self.defaults["global_cursor_width"],
  4534. size=self.defaults["global_cursor_size"])
  4535. # Set the relative position label
  4536. self.dx = location[0] - float(self.rel_point1[0])
  4537. self.dy = location[1] - float(self.rel_point1[1])
  4538. # Set the position label
  4539. # self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4540. # "<b>Y</b>: %.4f" % (location[0], location[1]))
  4541. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4542. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4543. units = self.defaults["units"].lower()
  4544. self.plotcanvas.text_hud.text = \
  4545. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4546. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4547. self.inform.emit('[success] %s' % _("Done."))
  4548. return location
  4549. def on_copy_command(self):
  4550. """
  4551. Will copy a selection of objects, creating new objects.
  4552. :return:
  4553. """
  4554. self.defaults.report_usage("on_copy_command()")
  4555. def initialize(obj_init, app):
  4556. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4557. try:
  4558. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4559. except AttributeError:
  4560. pass
  4561. try:
  4562. obj_init.apertures = deepcopy(obj.apertures)
  4563. except AttributeError:
  4564. pass
  4565. try:
  4566. if obj.tools:
  4567. obj_init.tools = deepcopy(obj.tools)
  4568. except Exception as err:
  4569. log.debug("App.on_copy_command() --> %s" % str(err))
  4570. try:
  4571. obj_init.source_file = deepcopy(obj.source_file)
  4572. except (AttributeError, TypeError):
  4573. pass
  4574. def initialize_excellon(obj_init, app):
  4575. obj_init.source_file = deepcopy(obj.source_file)
  4576. obj_init.tools = deepcopy(obj.tools)
  4577. # drills are offset, so they need to be deep copied
  4578. obj_init.drills = deepcopy(obj.drills)
  4579. # slots are offset, so they need to be deep copied
  4580. obj_init.slots = deepcopy(obj.slots)
  4581. obj_init.create_geometry()
  4582. def initialize_script(obj_init, app_obj):
  4583. obj_init.source_file = deepcopy(obj.source_file)
  4584. def initialize_document(obj_init, app_obj):
  4585. obj_init.source_file = deepcopy(obj.source_file)
  4586. for obj in self.collection.get_selected():
  4587. obj_name = obj.options["name"]
  4588. try:
  4589. if isinstance(obj, ExcellonObject):
  4590. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4591. elif isinstance(obj, GerberObject):
  4592. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4593. elif isinstance(obj, GeometryObject):
  4594. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4595. elif isinstance(obj, ScriptObject):
  4596. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4597. elif isinstance(obj, DocumentObject):
  4598. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4599. except Exception as e:
  4600. return "Operation failed: %s" % str(e)
  4601. def on_copy_object2(self, custom_name):
  4602. def initialize_geometry(obj_init, app):
  4603. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4604. try:
  4605. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4606. except AttributeError:
  4607. pass
  4608. try:
  4609. obj_init.apertures = deepcopy(obj.apertures)
  4610. except AttributeError:
  4611. pass
  4612. try:
  4613. if obj.tools:
  4614. obj_init.tools = deepcopy(obj.tools)
  4615. except Exception as ee:
  4616. log.debug("on_copy_object2() --> %s" % str(ee))
  4617. def initialize_gerber(obj_init, app):
  4618. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4619. obj_init.apertures = deepcopy(obj.apertures)
  4620. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4621. def initialize_excellon(obj_init, app):
  4622. obj_init.tools = deepcopy(obj.tools)
  4623. # drills are offset, so they need to be deep copied
  4624. obj_init.drills = deepcopy(obj.drills)
  4625. # slots are offset, so they need to be deep copied
  4626. obj_init.slots = deepcopy(obj.slots)
  4627. obj_init.create_geometry()
  4628. for obj in self.collection.get_selected():
  4629. obj_name = obj.options["name"]
  4630. try:
  4631. if isinstance(obj, ExcellonObject):
  4632. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4633. elif isinstance(obj, GerberObject):
  4634. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4635. elif isinstance(obj, GeometryObject):
  4636. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4637. except Exception as er:
  4638. return "Operation failed: %s" % str(er)
  4639. def on_rename_object(self, text):
  4640. """
  4641. Will rename an object.
  4642. :param text: New name for the object.
  4643. :return:
  4644. """
  4645. self.defaults.report_usage("on_rename_object()")
  4646. named_obj = self.collection.get_active()
  4647. for obj in named_obj:
  4648. if obj is list:
  4649. self.on_rename_object(text)
  4650. else:
  4651. try:
  4652. obj.options['name'] = text
  4653. except Exception as e:
  4654. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4655. def convert_any2geo(self):
  4656. """
  4657. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4658. :return:
  4659. """
  4660. self.defaults.report_usage("convert_any2geo()")
  4661. def initialize(obj_init, app):
  4662. obj_init.solid_geometry = obj.solid_geometry
  4663. try:
  4664. obj_init.follow_geometry = obj.follow_geometry
  4665. except AttributeError:
  4666. pass
  4667. try:
  4668. obj_init.apertures = obj.apertures
  4669. except AttributeError:
  4670. pass
  4671. try:
  4672. if obj.tools:
  4673. obj_init.tools = obj.tools
  4674. except AttributeError:
  4675. pass
  4676. def initialize_excellon(obj_init, app):
  4677. # objs = self.collection.get_selected()
  4678. # GeometryObject.merge(objs, obj)
  4679. solid_geo = []
  4680. for tool in obj.tools:
  4681. for geo in obj.tools[tool]['solid_geometry']:
  4682. solid_geo.append(geo)
  4683. obj_init.solid_geometry = deepcopy(solid_geo)
  4684. if not self.collection.get_selected():
  4685. log.warning("App.convert_any2geo --> No object selected")
  4686. self.inform.emit('[WARNING_NOTCL] %s' %
  4687. _("No object is selected. Select an object and try again."))
  4688. return
  4689. for obj in self.collection.get_selected():
  4690. obj_name = obj.options["name"]
  4691. try:
  4692. if isinstance(obj, ExcellonObject):
  4693. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4694. else:
  4695. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4696. except Exception as e:
  4697. return "Operation failed: %s" % str(e)
  4698. def convert_any2gerber(self):
  4699. """
  4700. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4701. :return:
  4702. """
  4703. self.defaults.report_usage("convert_any2gerber()")
  4704. def initialize_geometry(obj_init, app):
  4705. apertures = {}
  4706. apid = 0
  4707. apertures[str(apid)] = {}
  4708. apertures[str(apid)]['geometry'] = []
  4709. for obj_orig in obj.solid_geometry:
  4710. new_elem = {}
  4711. new_elem['solid'] = obj_orig
  4712. try:
  4713. new_elem['follow'] = obj_orig.exterior
  4714. except AttributeError:
  4715. pass
  4716. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4717. apertures[str(apid)]['size'] = 0.0
  4718. apertures[str(apid)]['type'] = 'C'
  4719. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4720. obj_init.apertures = deepcopy(apertures)
  4721. def initialize_excellon(obj_init, app):
  4722. apertures = {}
  4723. apid = 10
  4724. for tool in obj.tools:
  4725. apertures[str(apid)] = {}
  4726. apertures[str(apid)]['geometry'] = []
  4727. for geo in obj.tools[tool]['solid_geometry']:
  4728. new_el = {}
  4729. new_el['solid'] = geo
  4730. new_el['follow'] = geo.exterior
  4731. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4732. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4733. apertures[str(apid)]['type'] = 'C'
  4734. apid += 1
  4735. # create solid_geometry
  4736. solid_geometry = []
  4737. for apid in apertures:
  4738. for geo_el in apertures[apid]['geometry']:
  4739. solid_geometry.append(geo_el['solid'])
  4740. solid_geometry = MultiPolygon(solid_geometry)
  4741. solid_geometry = solid_geometry.buffer(0.0000001)
  4742. obj_init.solid_geometry = deepcopy(solid_geometry)
  4743. obj_init.apertures = deepcopy(apertures)
  4744. # clear the working objects (perhaps not necessary due of Python GC)
  4745. apertures.clear()
  4746. if not self.collection.get_selected():
  4747. log.warning("App.convert_any2gerber --> No object selected")
  4748. self.inform.emit('[WARNING_NOTCL] %s' %
  4749. _("No object is selected. Select an object and try again."))
  4750. return
  4751. for obj in self.collection.get_selected():
  4752. obj_name = obj.options["name"]
  4753. try:
  4754. if isinstance(obj, ExcellonObject):
  4755. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4756. elif isinstance(obj, GeometryObject):
  4757. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4758. else:
  4759. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4760. except Exception as e:
  4761. return "Operation failed: %s" % str(e)
  4762. def abort_all_tasks(self):
  4763. """
  4764. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4765. on the first possible occasion.
  4766. :return:
  4767. """
  4768. if self.abort_flag is False:
  4769. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4770. self.abort_flag = True
  4771. self.cleanup.emit()
  4772. def app_is_idle(self):
  4773. if self.abort_flag:
  4774. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4775. self.abort_flag = False
  4776. def on_selectall(self):
  4777. """
  4778. Will draw a selection box shape around the selected objects.
  4779. :return:
  4780. """
  4781. self.defaults.report_usage("on_selectall()")
  4782. # delete the possible selection box around a possible selected object
  4783. self.delete_selection_shape()
  4784. for name in self.collection.get_names():
  4785. self.collection.set_active(name)
  4786. curr_sel_obj = self.collection.get_by_name(name)
  4787. # create the selection box around the selected object
  4788. if self.defaults['global_selection_shape'] is True:
  4789. self.draw_selection_shape(curr_sel_obj)
  4790. def on_preferences(self):
  4791. """
  4792. Adds the Preferences in a Tab in Plot Area
  4793. :return:
  4794. """
  4795. # add the tab if it was closed
  4796. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4797. # delete the absolute and relative position and messages in the infobar
  4798. # self.ui.position_label.setText("")
  4799. # self.ui.rel_position_label.setText("")
  4800. # Switch plot_area to preferences page
  4801. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4802. # self.ui.show()
  4803. # detect changes in the preferences
  4804. for idx in range(self.ui.pref_tab_area.count()):
  4805. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4806. try:
  4807. try:
  4808. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4809. except (TypeError, AttributeError):
  4810. pass
  4811. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4812. except AttributeError:
  4813. pass
  4814. try:
  4815. try:
  4816. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4817. except (TypeError, AttributeError):
  4818. pass
  4819. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4820. except AttributeError:
  4821. pass
  4822. try:
  4823. try:
  4824. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4825. except (TypeError, AttributeError):
  4826. pass
  4827. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4828. except AttributeError:
  4829. pass
  4830. try:
  4831. try:
  4832. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4833. except (TypeError, AttributeError):
  4834. pass
  4835. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4836. except AttributeError:
  4837. pass
  4838. try:
  4839. try:
  4840. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4841. except (TypeError, AttributeError):
  4842. pass
  4843. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4844. except AttributeError:
  4845. pass
  4846. def on_tools_database(self, source='app'):
  4847. """
  4848. Adds the Tools Database in a Tab in Plot Area.
  4849. :return:
  4850. """
  4851. for idx in range(self.ui.plot_tab_area.count()):
  4852. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4853. # there can be only one instance of Tools Database at one time
  4854. return
  4855. if source == 'app':
  4856. self.tools_db_tab = ToolsDB2(
  4857. app=self,
  4858. parent=self.ui,
  4859. callback_on_edited=self.on_tools_db_edited,
  4860. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4861. )
  4862. elif source == 'ncc':
  4863. self.tools_db_tab = ToolsDB2(
  4864. app=self,
  4865. parent=self.ui,
  4866. callback_on_edited=self.on_tools_db_edited,
  4867. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4868. )
  4869. elif source == 'paint':
  4870. self.tools_db_tab = ToolsDB2(
  4871. app=self,
  4872. parent=self.ui,
  4873. callback_on_edited=self.on_tools_db_edited,
  4874. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4875. )
  4876. # add the tab if it was closed
  4877. try:
  4878. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4879. self.tools_db_tab.setObjectName("database_tab")
  4880. except Exception as e:
  4881. log.debug("App.on_tools_database() --> %s" % str(e))
  4882. return
  4883. # delete the absolute and relative position and messages in the infobar
  4884. self.ui.position_label.setText("")
  4885. self.ui.rel_position_label.setText("")
  4886. # Switch plot_area to preferences page
  4887. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4888. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4889. self.tools_db_tab.ui_connect()
  4890. def on_tools_db_edited(self):
  4891. """
  4892. Executed whenever a tool is edited in Tools Database.
  4893. Will color the text of the Tools Database tab to Red color.
  4894. :return:
  4895. """
  4896. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4897. for idx in range(self.ui.plot_tab_area.count()):
  4898. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4899. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4900. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4901. self.tools_db_changed_flag = True
  4902. def on_geometry_tool_add_from_db_executed(self, tool):
  4903. """
  4904. Here add the tool from DB in the selected geometry object.
  4905. :return:
  4906. """
  4907. tool_from_db = deepcopy(tool)
  4908. obj = self.collection.get_active()
  4909. if isinstance(obj, GeometryObject):
  4910. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4911. # close the tab and delete it
  4912. for idx in range(self.ui.plot_tab_area.count()):
  4913. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4914. wdg = self.ui.plot_tab_area.widget(idx)
  4915. wdg.deleteLater()
  4916. self.ui.plot_tab_area.removeTab(idx)
  4917. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4918. else:
  4919. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4920. def on_plot_area_tab_closed(self, tab_obj_name):
  4921. """
  4922. Executed whenever a QTab is closed in the Plot Area.
  4923. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4924. :return:
  4925. """
  4926. if tab_obj_name == "preferences_tab":
  4927. self.preferencesUiManager.on_close_preferences_tab()
  4928. elif tab_obj_name == "database_tab":
  4929. # disconnect the signals from the table widget in tab
  4930. self.tools_db_tab.ui_disconnect()
  4931. if self.tools_db_changed_flag is True:
  4932. msgbox = QtWidgets.QMessageBox()
  4933. msgbox.setText(_("One or more Tools are edited.\n"
  4934. "Do you want to update the Tools Database?"))
  4935. msgbox.setWindowTitle(_("Save Tools Database"))
  4936. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4937. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4938. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4939. msgbox.setDefaultButton(bt_yes)
  4940. msgbox.exec_()
  4941. response = msgbox.clickedButton()
  4942. if response == bt_yes:
  4943. self.tools_db_tab.on_save_tools_db()
  4944. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4945. else:
  4946. self.tools_db_changed_flag = False
  4947. self.inform.emit('')
  4948. return
  4949. self.tools_db_tab.deleteLater()
  4950. elif tab_obj_name == "text_editor_tab":
  4951. self.toggle_codeeditor = False
  4952. elif tab_obj_name == "bookmarks_tab":
  4953. self.book_dialog_tab.rebuild_actions()
  4954. self.book_dialog_tab.deleteLater()
  4955. else:
  4956. return
  4957. # def on_plotarea_tab_closed(self, tab_idx):
  4958. # """
  4959. #
  4960. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4961. # :return:
  4962. # """
  4963. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4964. #
  4965. # if widget is not None:
  4966. # widget.deleteLater()
  4967. # self.ui.plot_tab_area.removeTab(tab_idx)
  4968. def on_flipy(self):
  4969. """
  4970. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4971. :return:
  4972. """
  4973. self.defaults.report_usage("on_flipy()")
  4974. obj_list = self.collection.get_selected()
  4975. xminlist = []
  4976. yminlist = []
  4977. xmaxlist = []
  4978. ymaxlist = []
  4979. if not obj_list:
  4980. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4981. else:
  4982. try:
  4983. # first get a bounding box to fit all
  4984. for obj in obj_list:
  4985. xmin, ymin, xmax, ymax = obj.bounds()
  4986. xminlist.append(xmin)
  4987. yminlist.append(ymin)
  4988. xmaxlist.append(xmax)
  4989. ymaxlist.append(ymax)
  4990. # get the minimum x,y and maximum x,y for all objects selected
  4991. xminimal = min(xminlist)
  4992. yminimal = min(yminlist)
  4993. xmaximal = max(xmaxlist)
  4994. ymaximal = max(ymaxlist)
  4995. px = 0.5 * (xminimal + xmaximal)
  4996. py = 0.5 * (yminimal + ymaximal)
  4997. # execute mirroring
  4998. for obj in obj_list:
  4999. obj.mirror('X', [px, py])
  5000. obj.plot()
  5001. self.object_changed.emit(obj)
  5002. self.inform.emit('[success] %s' %
  5003. _("Flip on Y axis done."))
  5004. except Exception as e:
  5005. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5006. return
  5007. def on_flipx(self):
  5008. """
  5009. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5010. :return:
  5011. """
  5012. self.defaults.report_usage("on_flipx()")
  5013. obj_list = self.collection.get_selected()
  5014. xminlist = []
  5015. yminlist = []
  5016. xmaxlist = []
  5017. ymaxlist = []
  5018. if not obj_list:
  5019. self.inform.emit('[WARNING_NOTCL] %s' %
  5020. _("No object selected to Flip on X axis."))
  5021. else:
  5022. try:
  5023. # first get a bounding box to fit all
  5024. for obj in obj_list:
  5025. xmin, ymin, xmax, ymax = obj.bounds()
  5026. xminlist.append(xmin)
  5027. yminlist.append(ymin)
  5028. xmaxlist.append(xmax)
  5029. ymaxlist.append(ymax)
  5030. # get the minimum x,y and maximum x,y for all objects selected
  5031. xminimal = min(xminlist)
  5032. yminimal = min(yminlist)
  5033. xmaximal = max(xmaxlist)
  5034. ymaximal = max(ymaxlist)
  5035. px = 0.5 * (xminimal + xmaximal)
  5036. py = 0.5 * (yminimal + ymaximal)
  5037. # execute mirroring
  5038. for obj in obj_list:
  5039. obj.mirror('Y', [px, py])
  5040. obj.plot()
  5041. self.object_changed.emit(obj)
  5042. self.inform.emit('[success] %s' %
  5043. _("Flip on X axis done."))
  5044. except Exception as e:
  5045. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5046. return
  5047. def on_rotate(self, silent=False, preset=None):
  5048. """
  5049. Executed when Options -> Rotate Selection menu entry is clicked.
  5050. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5051. :param preset: A value to be used as predefined angle for rotation.
  5052. :return:
  5053. """
  5054. self.defaults.report_usage("on_rotate()")
  5055. obj_list = self.collection.get_selected()
  5056. xminlist = []
  5057. yminlist = []
  5058. xmaxlist = []
  5059. ymaxlist = []
  5060. if not obj_list:
  5061. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5062. else:
  5063. if silent is False:
  5064. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5065. min=-360, max=360, decimals=4,
  5066. init_val=float(self.defaults['tools_transform_rotate']))
  5067. num, ok = rotatebox.get_value()
  5068. else:
  5069. num = preset
  5070. ok = True
  5071. if ok:
  5072. try:
  5073. # first get a bounding box to fit all
  5074. for obj in obj_list:
  5075. xmin, ymin, xmax, ymax = obj.bounds()
  5076. xminlist.append(xmin)
  5077. yminlist.append(ymin)
  5078. xmaxlist.append(xmax)
  5079. ymaxlist.append(ymax)
  5080. # get the minimum x,y and maximum x,y for all objects selected
  5081. xminimal = min(xminlist)
  5082. yminimal = min(yminlist)
  5083. xmaximal = max(xmaxlist)
  5084. ymaximal = max(ymaxlist)
  5085. px = 0.5 * (xminimal + xmaximal)
  5086. py = 0.5 * (yminimal + ymaximal)
  5087. for sel_obj in obj_list:
  5088. sel_obj.rotate(-float(num), point=(px, py))
  5089. sel_obj.plot()
  5090. self.object_changed.emit(sel_obj)
  5091. self.inform.emit('[success] %s' %
  5092. _("Rotation done."))
  5093. except Exception as e:
  5094. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5095. return
  5096. def on_skewx(self):
  5097. """
  5098. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5099. :return:
  5100. """
  5101. self.defaults.report_usage("on_skewx()")
  5102. obj_list = self.collection.get_selected()
  5103. xminlist = []
  5104. yminlist = []
  5105. if not obj_list:
  5106. self.inform.emit('[WARNING_NOTCL] %s' %
  5107. _("No object selected to Skew/Shear on X axis."))
  5108. else:
  5109. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5110. min=-360, max=360, decimals=4,
  5111. init_val=float(self.defaults['tools_transform_skew_x']))
  5112. num, ok = skewxbox.get_value()
  5113. if ok:
  5114. # first get a bounding box to fit all
  5115. for obj in obj_list:
  5116. xmin, ymin, xmax, ymax = obj.bounds()
  5117. xminlist.append(xmin)
  5118. yminlist.append(ymin)
  5119. # get the minimum x,y and maximum x,y for all objects selected
  5120. xminimal = min(xminlist)
  5121. yminimal = min(yminlist)
  5122. for obj in obj_list:
  5123. obj.skew(num, 0, point=(xminimal, yminimal))
  5124. obj.plot()
  5125. self.object_changed.emit(obj)
  5126. self.inform.emit('[success] %s' %
  5127. _("Skew on X axis done."))
  5128. def on_skewy(self):
  5129. """
  5130. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5131. :return:
  5132. """
  5133. self.defaults.report_usage("on_skewy()")
  5134. obj_list = self.collection.get_selected()
  5135. xminlist = []
  5136. yminlist = []
  5137. if not obj_list:
  5138. self.inform.emit('[WARNING_NOTCL] %s' %
  5139. _("No object selected to Skew/Shear on Y axis."))
  5140. else:
  5141. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5142. min=-360, max=360, decimals=4,
  5143. init_val=float(self.defaults['tools_transform_skew_y']))
  5144. num, ok = skewybox.get_value()
  5145. if ok:
  5146. # first get a bounding box to fit all
  5147. for obj in obj_list:
  5148. xmin, ymin, xmax, ymax = obj.bounds()
  5149. xminlist.append(xmin)
  5150. yminlist.append(ymin)
  5151. # get the minimum x,y and maximum x,y for all objects selected
  5152. xminimal = min(xminlist)
  5153. yminimal = min(yminlist)
  5154. for obj in obj_list:
  5155. obj.skew(0, num, point=(xminimal, yminimal))
  5156. obj.plot()
  5157. self.object_changed.emit(obj)
  5158. self.inform.emit('[success] %s' %
  5159. _("Skew on Y axis done."))
  5160. def on_plots_updated(self):
  5161. """
  5162. Callback used to report when the plots have changed.
  5163. Adjust axes and zooms to fit.
  5164. :return: None
  5165. """
  5166. if self.is_legacy is False:
  5167. self.plotcanvas.update()
  5168. else:
  5169. self.plotcanvas.auto_adjust_axes()
  5170. self.on_zoom_fit(None)
  5171. self.collection.update_view()
  5172. # self.inform.emit(_("Plots updated ..."))
  5173. def on_toolbar_replot(self):
  5174. """
  5175. Callback for toolbar button. Re-plots all objects.
  5176. :return: None
  5177. """
  5178. self.defaults.report_usage("on_toolbar_replot")
  5179. self.log.debug("on_toolbar_replot()")
  5180. try:
  5181. self.collection.get_active().read_form()
  5182. except AttributeError:
  5183. self.log.debug("on_toolbar_replot(): AttributeError")
  5184. pass
  5185. self.plot_all()
  5186. def on_row_activated(self, index):
  5187. if index.isValid():
  5188. if index.internalPointer().parent_item != self.collection.root_item:
  5189. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5190. self.collection.on_item_activated(index)
  5191. def on_row_selected(self, obj_name):
  5192. """
  5193. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5194. It mean we clicked outside of the items and deselected all
  5195. :param obj_name:
  5196. :return:
  5197. """
  5198. if obj_name == 'none':
  5199. for act in self.ui.menuobjects.actions():
  5200. act.setChecked(False)
  5201. return
  5202. # get the name of the selected objects and add them to a list
  5203. name_list = []
  5204. for obj in self.collection.get_selected():
  5205. name_list.append(obj.options['name'])
  5206. # set all actions as unchecked but the ones selected make them checked
  5207. for act in self.ui.menuobjects.actions():
  5208. act.setChecked(False)
  5209. if act.text() in name_list:
  5210. act.setChecked(True)
  5211. def on_collection_updated(self, obj, state, old_name):
  5212. """
  5213. Create a menu from the object loaded in the collection.
  5214. :param obj: object that was changed (added, deleted, renamed)
  5215. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5216. :param old_name: the old name of the object before the action that triggered this slot happened
  5217. :return: None
  5218. """
  5219. icon_files = {
  5220. "gerber": self.resource_location + "/flatcam_icon16.png",
  5221. "excellon": self.resource_location + "/drill16.png",
  5222. "cncjob": self.resource_location + "/cnc16.png",
  5223. "geometry": self.resource_location + "/geometry16.png",
  5224. "script": self.resource_location + "/script_new16.png",
  5225. "document": self.resource_location + "/notes16_1.png"
  5226. }
  5227. if state == 'append':
  5228. for act in self.ui.menuobjects.actions():
  5229. try:
  5230. act.triggered.disconnect()
  5231. except TypeError:
  5232. pass
  5233. self.ui.menuobjects.clear()
  5234. gerber_list = []
  5235. exc_list = []
  5236. cncjob_list = []
  5237. geo_list = []
  5238. script_list = []
  5239. doc_list = []
  5240. for name in self.collection.get_names():
  5241. obj_named = self.collection.get_by_name(name)
  5242. if obj_named.kind == 'gerber':
  5243. gerber_list.append(name)
  5244. elif obj_named.kind == 'excellon':
  5245. exc_list.append(name)
  5246. elif obj_named.kind == 'cncjob':
  5247. cncjob_list.append(name)
  5248. elif obj_named.kind == 'geometry':
  5249. geo_list.append(name)
  5250. elif obj_named.kind == 'script':
  5251. script_list.append(name)
  5252. elif obj_named.kind == 'document':
  5253. doc_list.append(name)
  5254. def add_act(o_name):
  5255. obj_for_icon = self.collection.get_by_name(o_name)
  5256. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5257. add_action.setCheckable(True)
  5258. add_action.setText(o_name)
  5259. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5260. add_action.triggered.connect(
  5261. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5262. self.collection.set_inactive(o_name))
  5263. self.ui.menuobjects.addAction(add_action)
  5264. for name in gerber_list:
  5265. add_act(name)
  5266. self.ui.menuobjects.addSeparator()
  5267. for name in exc_list:
  5268. add_act(name)
  5269. self.ui.menuobjects.addSeparator()
  5270. for name in cncjob_list:
  5271. add_act(name)
  5272. self.ui.menuobjects.addSeparator()
  5273. for name in geo_list:
  5274. add_act(name)
  5275. self.ui.menuobjects.addSeparator()
  5276. for name in script_list:
  5277. add_act(name)
  5278. self.ui.menuobjects.addSeparator()
  5279. for name in doc_list:
  5280. add_act(name)
  5281. self.ui.menuobjects.addSeparator()
  5282. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5283. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5284. _('Select All')
  5285. )
  5286. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5287. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5288. _('Deselect All')
  5289. )
  5290. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5291. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5292. elif state == 'delete':
  5293. for act in self.ui.menuobjects.actions():
  5294. if act.text() == obj.options['name']:
  5295. try:
  5296. act.triggered.disconnect()
  5297. except TypeError:
  5298. pass
  5299. self.ui.menuobjects.removeAction(act)
  5300. break
  5301. elif state == 'rename':
  5302. for act in self.ui.menuobjects.actions():
  5303. if act.text() == old_name:
  5304. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5305. add_action.setText(obj.options['name'])
  5306. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5307. add_action.triggered.connect(
  5308. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5309. self.collection.set_inactive(obj.options['name']))
  5310. self.ui.menuobjects.insertAction(act, add_action)
  5311. try:
  5312. act.triggered.disconnect()
  5313. except TypeError:
  5314. pass
  5315. self.ui.menuobjects.removeAction(act)
  5316. break
  5317. elif state == 'delete_all':
  5318. for act in self.ui.menuobjects.actions():
  5319. try:
  5320. act.triggered.disconnect()
  5321. except TypeError:
  5322. pass
  5323. self.ui.menuobjects.clear()
  5324. self.ui.menuobjects.addSeparator()
  5325. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5326. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5327. _('Select All')
  5328. )
  5329. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5330. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5331. _('Deselect All')
  5332. )
  5333. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5334. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5335. def on_objects_selection(self, on_off):
  5336. obj_list = self.collection.get_names()
  5337. if on_off is True:
  5338. self.collection.set_all_active()
  5339. for act in self.ui.menuobjects.actions():
  5340. try:
  5341. act.setChecked(True)
  5342. except Exception:
  5343. pass
  5344. if obj_list:
  5345. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5346. else:
  5347. self.collection.set_all_inactive()
  5348. for act in self.ui.menuobjects.actions():
  5349. try:
  5350. act.setChecked(False)
  5351. except Exception:
  5352. pass
  5353. if obj_list:
  5354. self.inform.emit('%s' % _("Objects selection is cleared."))
  5355. else:
  5356. self.inform.emit('')
  5357. def grid_status(self):
  5358. if self.ui.grid_snap_btn.isChecked():
  5359. return True
  5360. else:
  5361. return False
  5362. def populate_cmenu_grids(self):
  5363. units = self.defaults['units'].lower()
  5364. # for act in self.ui.cmenu_gridmenu.actions():
  5365. # act.triggered.disconnect()
  5366. self.ui.cmenu_gridmenu.clear()
  5367. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5368. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5369. _("Grid On/Off"))
  5370. grid_toggle.setCheckable(True)
  5371. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5372. self.ui.cmenu_gridmenu.addSeparator()
  5373. for grid in sorted_list:
  5374. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5375. "%s" % str(grid))
  5376. action.triggered.connect(self.set_grid)
  5377. self.ui.cmenu_gridmenu.addSeparator()
  5378. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5379. _("Add"))
  5380. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5381. _("Delete"))
  5382. grid_add.triggered.connect(self.on_grid_add)
  5383. grid_delete.triggered.connect(self.on_grid_delete)
  5384. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5385. def set_grid(self):
  5386. menu_action = self.sender()
  5387. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5388. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5389. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5390. def on_grid_add(self):
  5391. # ## Current application units in lower Case
  5392. units = self.defaults['units'].lower()
  5393. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5394. text=_('Enter a Grid Value:'),
  5395. min=0.0000, max=99.9999, decimals=4)
  5396. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5397. val, ok = grid_add_popup.get_value()
  5398. if ok:
  5399. if float(val) == 0:
  5400. self.inform.emit('[WARNING_NOTCL] %s' %
  5401. _("Please enter a grid value with non-zero value, in Float format."))
  5402. return
  5403. else:
  5404. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5405. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5406. self.inform.emit('[success] %s...' %
  5407. _("New Grid added"))
  5408. else:
  5409. self.inform.emit('[WARNING_NOTCL] %s...' %
  5410. _("Grid already exists"))
  5411. else:
  5412. self.inform.emit('[WARNING_NOTCL] %s...' %
  5413. _("Adding New Grid cancelled"))
  5414. def on_grid_delete(self):
  5415. # ## Current application units in lower Case
  5416. units = self.defaults['units'].lower()
  5417. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5418. text='Enter a Grid Value:',
  5419. min=0.0000, max=99.9999, decimals=4)
  5420. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5421. val, ok = grid_del_popup.get_value()
  5422. if ok:
  5423. if float(val) == 0:
  5424. self.inform.emit('[WARNING_NOTCL] %s' %
  5425. _("Please enter a grid value with non-zero value, in Float format."))
  5426. return
  5427. else:
  5428. try:
  5429. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5430. except ValueError:
  5431. self.inform.emit('[ERROR_NOTCL]%s...' %
  5432. _(" Grid Value does not exist"))
  5433. return
  5434. self.inform.emit('[success] %s...' %
  5435. _("Grid Value deleted"))
  5436. else:
  5437. self.inform.emit('[WARNING_NOTCL] %s...' %
  5438. _("Delete Grid value cancelled"))
  5439. def on_shortcut_list(self):
  5440. self.defaults.report_usage("on_shortcut_list()")
  5441. # add the tab if it was closed
  5442. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5443. # delete the absolute and relative position and messages in the infobar
  5444. self.ui.position_label.setText("")
  5445. self.ui.rel_position_label.setText("")
  5446. # Switch plot_area to preferences page
  5447. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5448. # self.ui.show()
  5449. def on_select_tab(self, name):
  5450. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5451. if self.ui.splitter.sizes()[0] == 0:
  5452. self.ui.splitter.setSizes([1, 1])
  5453. else:
  5454. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5455. self.ui.splitter.setSizes([0, 1])
  5456. if name == 'project':
  5457. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5458. elif name == 'selected':
  5459. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5460. elif name == 'tool':
  5461. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5462. def on_copy_name(self):
  5463. self.defaults.report_usage("on_copy_name()")
  5464. obj = self.collection.get_active()
  5465. try:
  5466. name = obj.options["name"]
  5467. except AttributeError:
  5468. log.debug("on_copy_name() --> No object selected to copy it's name")
  5469. self.inform.emit('[WARNING_NOTCL]%s' %
  5470. _(" No object selected to copy it's name"))
  5471. return
  5472. self.clipboard.setText(name)
  5473. self.inform.emit(_("Name copied on clipboard ..."))
  5474. def on_mouse_click_over_plot(self, event):
  5475. """
  5476. Default actions are:
  5477. :param event: Contains information about the event, like which button
  5478. was clicked, the pixel coordinates and the axes coordinates.
  5479. :return: None
  5480. """
  5481. self.pos = []
  5482. if self.is_legacy is False:
  5483. event_pos = event.pos
  5484. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5485. # # Set the mouse button for panning
  5486. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5487. else:
  5488. event_pos = (event.xdata, event.ydata)
  5489. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5490. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5491. # So it can receive key presses
  5492. self.plotcanvas.native.setFocus()
  5493. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5494. if self.grid_status():
  5495. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5496. else:
  5497. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5498. try:
  5499. if event.button == 1:
  5500. # Reset here the relative coordinates so there is a new reference on the click position
  5501. if self.rel_point1 is None:
  5502. self.rel_point1 = self.pos
  5503. else:
  5504. self.rel_point2 = copy(self.rel_point1)
  5505. self.rel_point1 = self.pos
  5506. self.on_mouse_move_over_plot(event, origin_click=True)
  5507. except Exception as e:
  5508. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5509. def on_mouse_double_click_over_plot(self, event):
  5510. if event.button == 1:
  5511. self.doubleclick = True
  5512. def on_mouse_move_over_plot(self, event, origin_click=None):
  5513. """
  5514. Callback for the mouse motion event over the plot.
  5515. :param event: Contains information about the event.
  5516. :param origin_click
  5517. :return: None
  5518. """
  5519. if self.is_legacy is False:
  5520. event_pos = event.pos
  5521. if self.defaults["global_pan_button"] == '2':
  5522. pan_button = 2
  5523. else:
  5524. pan_button = 3
  5525. self.event_is_dragging = event.is_dragging
  5526. else:
  5527. event_pos = (event.xdata, event.ydata)
  5528. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5529. if self.defaults["global_pan_button"] == '2':
  5530. pan_button = 3
  5531. else:
  5532. pan_button = 2
  5533. self.event_is_dragging = self.plotcanvas.is_dragging
  5534. # So it can receive key presses but not when the Tcl Shell is active
  5535. if not self.ui.shell_dock.isVisible():
  5536. if not self.plotcanvas.native.hasFocus():
  5537. self.plotcanvas.native.setFocus()
  5538. self.pos_jump = event_pos
  5539. self.ui.popMenu.mouse_is_panning = False
  5540. if origin_click is None:
  5541. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5542. if event.button == pan_button and self.event_is_dragging == 1:
  5543. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5544. if self.ui.popMenu.popup_active:
  5545. self.ui.popMenu.popup_active = False
  5546. return
  5547. self.ui.popMenu.mouse_is_panning = True
  5548. return
  5549. if self.rel_point1 is not None:
  5550. try: # May fail in case mouse not within axes
  5551. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5552. if pos_canvas[0] is None or pos_canvas[1] is None:
  5553. return
  5554. if self.grid_status():
  5555. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5556. # Update cursor
  5557. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5558. symbol='++', edge_color=self.cursor_color_3D,
  5559. edge_width=self.defaults["global_cursor_width"],
  5560. size=self.defaults["global_cursor_size"])
  5561. else:
  5562. pos = (pos_canvas[0], pos_canvas[1])
  5563. self.dx = pos[0] - float(self.rel_point1[0])
  5564. self.dy = pos[1] - float(self.rel_point1[1])
  5565. # self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5566. # "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5567. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5568. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5569. units = self.defaults["units"].lower()
  5570. self.plotcanvas.text_hud.text = \
  5571. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5572. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5573. self.mouse = [pos[0], pos[1]]
  5574. # if the mouse is moved and the LMB is clicked then the action is a selection
  5575. if self.event_is_dragging == 1 and event.button == 1:
  5576. self.delete_selection_shape()
  5577. if self.dx < 0:
  5578. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5579. face_color=self.defaults['global_alt_sel_fill'])
  5580. self.selection_type = False
  5581. elif self.dx >= 0:
  5582. self.draw_moving_selection_shape(self.pos, pos)
  5583. self.selection_type = True
  5584. else:
  5585. self.selection_type = None
  5586. else:
  5587. self.selection_type = None
  5588. # hover effect - enabled in Preferences -> General -> GUI Settings
  5589. if self.defaults['global_hover']:
  5590. for obj in self.collection.get_list():
  5591. try:
  5592. # select the object(s) only if it is enabled (plotted)
  5593. if obj.options['plot']:
  5594. if obj not in self.collection.get_selected():
  5595. poly_obj = Polygon(
  5596. [(obj.options['xmin'], obj.options['ymin']),
  5597. (obj.options['xmax'], obj.options['ymin']),
  5598. (obj.options['xmax'], obj.options['ymax']),
  5599. (obj.options['xmin'], obj.options['ymax'])]
  5600. )
  5601. if Point(pos).within(poly_obj):
  5602. if obj.isHovering is False:
  5603. obj.isHovering = True
  5604. obj.notHovering = True
  5605. # create the selection box around the selected object
  5606. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5607. else:
  5608. if obj.notHovering is True:
  5609. obj.notHovering = False
  5610. obj.isHovering = False
  5611. self.delete_hover_shape()
  5612. except Exception:
  5613. # the Exception here will happen if we try to select on screen and we have an
  5614. # newly (and empty) just created Geometry or Excellon object that do not have the
  5615. # xmin, xmax, ymin, ymax options.
  5616. # In this case poly_obj creation (see above) will fail
  5617. pass
  5618. except Exception as e:
  5619. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5620. # self.ui.position_label.setText("")
  5621. # self.ui.rel_position_label.setText("")
  5622. self.mouse = None
  5623. def on_mouse_click_release_over_plot(self, event):
  5624. """
  5625. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5626. and has been registered in ''self.__init__()''.
  5627. :param event: contains information about the event.
  5628. :return:
  5629. """
  5630. if self.is_legacy is False:
  5631. event_pos = event.pos
  5632. right_button = 2
  5633. else:
  5634. event_pos = (event.xdata, event.ydata)
  5635. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5636. right_button = 3
  5637. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5638. if self.grid_status():
  5639. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5640. else:
  5641. pos = (pos_canvas[0], pos_canvas[1])
  5642. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5643. # canvas menu
  5644. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5645. self.ui.popMenu.mouse_is_panning = False
  5646. self.cursor = QtGui.QCursor()
  5647. self.populate_cmenu_grids()
  5648. self.ui.popMenu.popup(self.cursor.pos())
  5649. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5650. # selection and then select a type of selection ("enclosing" or "touching")
  5651. if event.button == 1: # left click
  5652. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5653. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5654. if modifiers == QtCore.Qt.ShiftModifier:
  5655. # do not auto open the Project Tab
  5656. self.click_noproject = True
  5657. self.clipboard.setText(
  5658. self.defaults["global_point_clipboard_format"] %
  5659. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5660. )
  5661. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5662. return
  5663. if self.doubleclick is True:
  5664. self.doubleclick = False
  5665. if self.collection.get_selected():
  5666. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5667. if self.ui.splitter.sizes()[0] == 0:
  5668. self.ui.splitter.setSizes([1, 1])
  5669. try:
  5670. # delete the selection shape(S) as it may be in the way
  5671. self.delete_selection_shape()
  5672. self.delete_hover_shape()
  5673. except Exception as e:
  5674. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5675. return
  5676. else:
  5677. # WORKAROUND for LEGACY MODE
  5678. if self.is_legacy is True:
  5679. # if there is no move on canvas then we have no dragging selection
  5680. if self.dx == 0 or self.dy == 0:
  5681. self.selection_type = None
  5682. if self.selection_type is not None:
  5683. try:
  5684. self.selection_area_handler(self.pos, pos, self.selection_type)
  5685. self.selection_type = None
  5686. except Exception as e:
  5687. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5688. return
  5689. else:
  5690. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5691. if key_modifier == QtCore.Qt.ShiftModifier:
  5692. mod_key = 'Shift'
  5693. elif key_modifier == QtCore.Qt.ControlModifier:
  5694. mod_key = 'Control'
  5695. else:
  5696. mod_key = None
  5697. try:
  5698. if self.command_active is None:
  5699. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5700. # deselect, and if it's not selected then it will be selected
  5701. # If there is no active command (self.command_active is None) then we check if we clicked
  5702. # on a object by checking the bounding limits against mouse click position
  5703. if mod_key == self.defaults["global_mselect_key"]:
  5704. self.select_objects(key='multisel')
  5705. else:
  5706. # If there is no active command (self.command_active is None) then we check if
  5707. # we clicked on a object by checking the bounding limits against mouse click position
  5708. self.select_objects()
  5709. self.delete_hover_shape()
  5710. except Exception as e:
  5711. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5712. return
  5713. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5714. """
  5715. :param start_pos: mouse position when the selection LMB click was done
  5716. :param end_pos: mouse position when the left mouse button is released
  5717. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5718. :return:
  5719. """
  5720. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5721. # delete previous selection shape
  5722. self.delete_selection_shape()
  5723. # make all objects inactive
  5724. self.collection.set_all_inactive()
  5725. for obj in self.collection.get_list():
  5726. try:
  5727. # select the object(s) only if it is enabled (plotted)
  5728. if obj.options['plot']:
  5729. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5730. (obj.options['xmax'], obj.options['ymin']),
  5731. (obj.options['xmax'], obj.options['ymax']),
  5732. (obj.options['xmin'], obj.options['ymax'])])
  5733. if sel_type is True:
  5734. if poly_obj.within(poly_selection):
  5735. # create the selection box around the selected object
  5736. if self.defaults['global_selection_shape'] is True:
  5737. self.draw_selection_shape(obj)
  5738. self.collection.set_active(obj.options['name'])
  5739. else:
  5740. if poly_selection.intersects(poly_obj):
  5741. # create the selection box around the selected object
  5742. if self.defaults['global_selection_shape'] is True:
  5743. self.draw_selection_shape(obj)
  5744. self.collection.set_active(obj.options['name'])
  5745. obj.selection_shape_drawn = True
  5746. except Exception as e:
  5747. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5748. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5749. # In this case poly_obj creation (see above) will fail
  5750. log.debug("App.selection_area_handler() --> %s" % str(e))
  5751. def select_objects(self, key=None):
  5752. """
  5753. Will select objects clicked on canvas
  5754. :param key: for future use in cumulative selection
  5755. :return:
  5756. """
  5757. # list where we store the overlapped objects under our mouse left click position
  5758. if key is None:
  5759. self.objects_under_the_click_list = []
  5760. # Populate the list with the overlapped objects on the click position
  5761. curr_x, curr_y = self.pos
  5762. for obj in self.all_objects_list:
  5763. # ScriptObject and DocumentObject objects can't be selected
  5764. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5765. continue
  5766. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5767. continue
  5768. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5769. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5770. if obj.options['name'] not in self.objects_under_the_click_list:
  5771. if obj.options['plot']:
  5772. # add objects to the objects_under_the_click list only if the object is plotted
  5773. # (active and not disabled)
  5774. self.objects_under_the_click_list.append(obj.options['name'])
  5775. try:
  5776. if self.objects_under_the_click_list:
  5777. curr_sel_obj = self.collection.get_active()
  5778. # case when there is only an object under the click and we toggle it
  5779. if len(self.objects_under_the_click_list) == 1:
  5780. if curr_sel_obj is None:
  5781. self.collection.set_active(self.objects_under_the_click_list[0])
  5782. curr_sel_obj = self.collection.get_active()
  5783. # create the selection box around the selected object
  5784. if self.defaults['global_selection_shape'] is True:
  5785. self.draw_selection_shape(curr_sel_obj)
  5786. curr_sel_obj.selection_shape_drawn = True
  5787. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5788. self.on_objects_selection(False)
  5789. self.delete_selection_shape()
  5790. curr_sel_obj.selection_shape_drawn = False
  5791. self.collection.set_active(self.objects_under_the_click_list[0])
  5792. curr_sel_obj = self.collection.get_active()
  5793. # create the selection box around the selected object
  5794. if self.defaults['global_selection_shape'] is True:
  5795. self.draw_selection_shape(curr_sel_obj)
  5796. curr_sel_obj.selection_shape_drawn = True
  5797. self.selected_message(curr_sel_obj=curr_sel_obj)
  5798. elif curr_sel_obj.selection_shape_drawn is False:
  5799. if self.defaults['global_selection_shape'] is True:
  5800. self.draw_selection_shape(curr_sel_obj)
  5801. curr_sel_obj.selection_shape_drawn = True
  5802. else:
  5803. self.on_objects_selection(False)
  5804. self.delete_selection_shape()
  5805. if self.call_source != 'app':
  5806. self.call_source = 'app'
  5807. self.selected_message(curr_sel_obj=curr_sel_obj)
  5808. else:
  5809. # If there is no selected object
  5810. # make active the first element of the overlapped objects list
  5811. if self.collection.get_active() is None:
  5812. self.collection.set_active(self.objects_under_the_click_list[0])
  5813. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5814. name_sel_obj = self.collection.get_active().options['name']
  5815. # In case that there is a selected object but it is not in the overlapped object list
  5816. # make that object inactive and activate the first element in the overlapped object list
  5817. if name_sel_obj not in self.objects_under_the_click_list:
  5818. self.collection.set_inactive(name_sel_obj)
  5819. name_sel_obj = self.objects_under_the_click_list[0]
  5820. self.collection.set_active(name_sel_obj)
  5821. else:
  5822. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5823. self.collection.set_all_inactive()
  5824. self.collection.set_active(
  5825. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5826. curr_sel_obj = self.collection.get_active()
  5827. # delete the possible selection box around a possible selected object
  5828. self.delete_selection_shape()
  5829. curr_sel_obj.selection_shape_drawn = False
  5830. # create the selection box around the selected object
  5831. if self.defaults['global_selection_shape'] is True:
  5832. self.draw_selection_shape(curr_sel_obj)
  5833. curr_sel_obj.selection_shape_drawn = True
  5834. self.selected_message(curr_sel_obj=curr_sel_obj)
  5835. else:
  5836. # deselect everything
  5837. self.on_objects_selection(False)
  5838. # delete the possible selection box around a possible selected object
  5839. self.delete_selection_shape()
  5840. for o in self.collection.get_list():
  5841. o.selection_shape_drawn = False
  5842. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5843. # only when working on App
  5844. if self.call_source == 'app':
  5845. if self.click_noproject is False:
  5846. # if the Tool Tab is in focus don't change focus to Project Tab
  5847. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5848. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5849. else:
  5850. # restore auto open the Project Tab
  5851. self.click_noproject = False
  5852. # delete any text in the status bar, implicitly the last object name that was selected
  5853. # self.inform.emit("")
  5854. else:
  5855. self.call_source = 'app'
  5856. except Exception as e:
  5857. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5858. def selected_message(self, curr_sel_obj):
  5859. if curr_sel_obj:
  5860. if curr_sel_obj.kind == 'gerber':
  5861. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5862. color='green',
  5863. name=str(curr_sel_obj.options['name']),
  5864. tx=_("selected"))
  5865. )
  5866. elif curr_sel_obj.kind == 'excellon':
  5867. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5868. color='brown',
  5869. name=str(curr_sel_obj.options['name']),
  5870. tx=_("selected"))
  5871. )
  5872. elif curr_sel_obj.kind == 'cncjob':
  5873. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5874. color='blue',
  5875. name=str(curr_sel_obj.options['name']),
  5876. tx=_("selected"))
  5877. )
  5878. elif curr_sel_obj.kind == 'geometry':
  5879. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5880. color='red',
  5881. name=str(curr_sel_obj.options['name']),
  5882. tx=_("selected"))
  5883. )
  5884. def delete_hover_shape(self):
  5885. self.hover_shapes.clear()
  5886. self.hover_shapes.redraw()
  5887. def draw_hover_shape(self, sel_obj, color=None):
  5888. """
  5889. :param sel_obj: The object for which the hover shape must be drawn
  5890. :param color: The color of the hover shape
  5891. :return: None
  5892. """
  5893. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5894. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5895. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5896. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5897. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5898. if self.defaults['units'].upper() == 'MM':
  5899. hover_rect = hover_rect.buffer(-0.1)
  5900. hover_rect = hover_rect.buffer(0.2)
  5901. else:
  5902. hover_rect = hover_rect.buffer(-0.00393)
  5903. hover_rect = hover_rect.buffer(0.00787)
  5904. # if color:
  5905. # face = Color(color)
  5906. # face.alpha = 0.2
  5907. # outline = Color(color, alpha=0.8)
  5908. # else:
  5909. # face = Color(self.defaults['global_sel_fill'])
  5910. # face.alpha = 0.2
  5911. # outline = self.defaults['global_sel_line']
  5912. if color:
  5913. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5914. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5915. else:
  5916. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5917. outline = self.defaults['global_sel_line']
  5918. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5919. if self.is_legacy is True:
  5920. self.hover_shapes.redraw()
  5921. def delete_selection_shape(self):
  5922. self.move_tool.sel_shapes.clear()
  5923. self.move_tool.sel_shapes.redraw()
  5924. def draw_selection_shape(self, sel_obj, color=None):
  5925. """
  5926. Will draw a selection shape around the selected object.
  5927. :param sel_obj: The object for which the selection shape must be drawn
  5928. :param color: The color for the selection shape.
  5929. :return: None
  5930. """
  5931. if sel_obj is None:
  5932. return
  5933. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5934. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5935. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5936. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5937. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5938. if self.defaults['units'].upper() == 'MM':
  5939. sel_rect = sel_rect.buffer(-0.1)
  5940. sel_rect = sel_rect.buffer(0.2)
  5941. else:
  5942. sel_rect = sel_rect.buffer(-0.00393)
  5943. sel_rect = sel_rect.buffer(0.00787)
  5944. if color:
  5945. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5946. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5947. else:
  5948. if self.is_legacy is False:
  5949. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5950. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5951. else:
  5952. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5953. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5954. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5955. color=outline,
  5956. face_color=face,
  5957. update=True,
  5958. layer=0,
  5959. tolerance=None))
  5960. if self.is_legacy is True:
  5961. self.move_tool.sel_shapes.redraw()
  5962. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5963. """
  5964. Will draw a selection shape when dragging mouse on canvas.
  5965. :param old_coords: Old coordinates
  5966. :param coords: New coordinates
  5967. :param kwargs: Keyword arguments
  5968. :return:
  5969. """
  5970. if 'color' in kwargs:
  5971. color = kwargs['color']
  5972. else:
  5973. color = self.defaults['global_sel_line']
  5974. if 'face_color' in kwargs:
  5975. face_color = kwargs['face_color']
  5976. else:
  5977. face_color = self.defaults['global_sel_fill']
  5978. if 'face_alpha' in kwargs:
  5979. face_alpha = kwargs['face_alpha']
  5980. else:
  5981. face_alpha = 0.3
  5982. x0, y0 = old_coords
  5983. x1, y1 = coords
  5984. pt1 = (x0, y0)
  5985. pt2 = (x1, y0)
  5986. pt3 = (x1, y1)
  5987. pt4 = (x0, y1)
  5988. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5989. # color_t = Color(face_color)
  5990. # color_t.alpha = face_alpha
  5991. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5992. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5993. layer=0, tolerance=None)
  5994. if self.is_legacy is True:
  5995. self.move_tool.sel_shapes.redraw()
  5996. def on_file_new_click(self):
  5997. """
  5998. Callback for menu item File -> New.
  5999. Executed on clicking the Menu -> File -> New Project
  6000. :return:
  6001. """
  6002. if self.collection.get_list() and self.should_we_save:
  6003. msgbox = QtWidgets.QMessageBox()
  6004. # msgbox.setText("<B>Save changes ...</B>")
  6005. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6006. "Creating a New project will delete them.\n"
  6007. "Do you want to Save the project?"))
  6008. msgbox.setWindowTitle(_("Save changes"))
  6009. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6010. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6011. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6012. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6013. msgbox.setDefaultButton(bt_yes)
  6014. msgbox.exec_()
  6015. response = msgbox.clickedButton()
  6016. if response == bt_yes:
  6017. self.on_file_saveprojectas()
  6018. elif response == bt_cancel:
  6019. return
  6020. elif response == bt_no:
  6021. self.on_file_new()
  6022. else:
  6023. self.on_file_new()
  6024. self.inform.emit('[success] %s...' % _("New Project created"))
  6025. def on_file_new(self, cli=None):
  6026. """
  6027. Returns the application to its startup state. This method is thread-safe.
  6028. :param cli: Boolean. If True this method was run from command line
  6029. :return: None
  6030. """
  6031. self.defaults.report_usage("on_file_new")
  6032. # Remove everything from memory
  6033. App.log.debug("on_file_new()")
  6034. # close any editor that might be open
  6035. if self.call_source != 'app':
  6036. self.editor2object(cleanup=True)
  6037. # ## EDITOR section
  6038. self.geo_editor = FlatCAMGeoEditor(self)
  6039. self.exc_editor = FlatCAMExcEditor(self)
  6040. self.grb_editor = FlatCAMGrbEditor(self)
  6041. # Clear pool
  6042. self.clear_pool()
  6043. for obj in self.collection.get_list():
  6044. # delete shapes left drawn from mark shape_collections, if any
  6045. if isinstance(obj, GerberObject):
  6046. try:
  6047. for el in obj.mark_shapes:
  6048. obj.mark_shapes[el].clear(update=True)
  6049. obj.mark_shapes[el].enabled = False
  6050. del el
  6051. except AttributeError:
  6052. pass
  6053. # also delete annotation shapes, if any
  6054. elif isinstance(obj, CNCJobObject):
  6055. try:
  6056. obj.text_col.enabled = False
  6057. del obj.text_col
  6058. obj.annotation.clear(update=True)
  6059. del obj.annotation
  6060. except AttributeError:
  6061. pass
  6062. # delete the exclusion areas
  6063. self.exc_areas.clear_shapes()
  6064. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6065. self.shell.init_tcl()
  6066. # delete any selection shape on canvas
  6067. self.delete_selection_shape()
  6068. # delete all FlatCAM objects
  6069. self.collection.delete_all()
  6070. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  6071. self.setup_component_editor()
  6072. # Clear project filename
  6073. self.project_filename = None
  6074. # Load the application defaults
  6075. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6076. # Re-fresh project options
  6077. self.on_options_app2project()
  6078. # Init FlatCAMTools
  6079. self.init_tools()
  6080. # Try to close all tabs in the PlotArea but only if the GUI is active (CLI is None)
  6081. if cli is None:
  6082. # we need to go in reverse because once we remove a tab then the index changes
  6083. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  6084. # and so on. Therefore the deletion should be done in reverse
  6085. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  6086. for index in range(wdg_count, -1, -1):
  6087. try:
  6088. self.ui.plot_tab_area.closeTab(index)
  6089. except Exception as e:
  6090. log.debug("App.on_file_new() --> %s" % str(e))
  6091. # # And then add again the Plot Area
  6092. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  6093. self.ui.plot_tab_area.protectTab(0)
  6094. # take the focus of the Notebook on Project Tab.
  6095. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6096. self.set_ui_title(name=_("New Project - Not saved"))
  6097. def obj_properties(self):
  6098. """
  6099. Will launch the object Properties Tool
  6100. :return:
  6101. """
  6102. self.defaults.report_usage("obj_properties()")
  6103. self.properties_tool.run(toggle=False)
  6104. def on_project_context_save(self):
  6105. """
  6106. Wrapper, will save the object function of it's type
  6107. :return:
  6108. """
  6109. obj = self.collection.get_active()
  6110. if type(obj) == GeometryObject:
  6111. self.on_file_exportdxf()
  6112. elif type(obj) == ExcellonObject:
  6113. self.on_file_saveexcellon()
  6114. elif type(obj) == CNCJobObject:
  6115. obj.on_exportgcode_button_click()
  6116. elif type(obj) == GerberObject:
  6117. self.on_file_savegerber()
  6118. elif type(obj) == ScriptObject:
  6119. self.on_file_savescript()
  6120. elif type(obj) == DocumentObject:
  6121. self.on_file_savedocument()
  6122. def obj_move(self):
  6123. """
  6124. Callback for the Move menu entry in various Context Menu's.
  6125. :return:
  6126. """
  6127. self.defaults.report_usage("obj_move()")
  6128. self.move_tool.run(toggle=False)
  6129. def on_fileopengerber(self, signal, name=None):
  6130. """
  6131. File menu callback for opening a Gerber.
  6132. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6133. :param name:
  6134. :return: None
  6135. """
  6136. self.defaults.report_usage("on_fileopengerber")
  6137. App.log.debug("on_fileopengerber()")
  6138. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6139. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6140. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6141. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6142. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6143. "*.mil);;" \
  6144. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6145. "Allegro Files (*.art);;" \
  6146. "Mentor Files (*.pho *.gdo);;" \
  6147. "All Files (*.*)"
  6148. if name is None:
  6149. try:
  6150. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6151. directory=self.get_last_folder(),
  6152. filter=_filter_)
  6153. except TypeError:
  6154. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6155. filenames = [str(filename) for filename in filenames]
  6156. else:
  6157. filenames = [name]
  6158. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6159. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6160. _("Opening Gerber file.")),
  6161. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6162. color=QtGui.QColor("gray"))
  6163. if len(filenames) == 0:
  6164. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6165. else:
  6166. for filename in filenames:
  6167. if filename != '':
  6168. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6169. def on_fileopenexcellon(self, signal, name=None):
  6170. """
  6171. File menu callback for opening an Excellon file.
  6172. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6173. :param name:
  6174. :return: None
  6175. """
  6176. self.defaults.report_usage("on_fileopenexcellon")
  6177. App.log.debug("on_fileopenexcellon()")
  6178. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6179. "All Files (*.*)"
  6180. if name is None:
  6181. try:
  6182. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6183. directory=self.get_last_folder(),
  6184. filter=_filter_)
  6185. except TypeError:
  6186. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6187. filenames = [str(filename) for filename in filenames]
  6188. else:
  6189. filenames = [str(name)]
  6190. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6191. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6192. _("Opening Excellon file.")),
  6193. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6194. color=QtGui.QColor("gray"))
  6195. if len(filenames) == 0:
  6196. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6197. else:
  6198. for filename in filenames:
  6199. if filename != '':
  6200. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6201. def on_fileopengcode(self, signal, name=None):
  6202. """
  6203. File menu call back for opening gcode.
  6204. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6205. :param name:
  6206. :return:
  6207. """
  6208. self.defaults.report_usage("on_fileopengcode")
  6209. App.log.debug("on_fileopengcode()")
  6210. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6211. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6212. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6213. "All Files (*.*)"
  6214. if name is None:
  6215. try:
  6216. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6217. directory=self.get_last_folder(),
  6218. filter=_filter_)
  6219. except TypeError:
  6220. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6221. filenames = [str(filename) for filename in filenames]
  6222. else:
  6223. filenames = [name]
  6224. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6225. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6226. _("Opening G-Code file.")),
  6227. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6228. color=QtGui.QColor("gray"))
  6229. if len(filenames) == 0:
  6230. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6231. else:
  6232. for filename in filenames:
  6233. if filename != '':
  6234. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6235. def on_file_openproject(self, signal):
  6236. """
  6237. File menu callback for opening a project.
  6238. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6239. :return: None
  6240. """
  6241. self.defaults.report_usage("on_file_openproject")
  6242. App.log.debug("on_file_openproject()")
  6243. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6244. try:
  6245. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6246. directory=self.get_last_folder(), filter=_filter_)
  6247. except TypeError:
  6248. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6249. # The Qt methods above will return a QString which can cause problems later.
  6250. # So far json.dump() will fail to serialize it.
  6251. # TODO: Improve the serialization methods and remove this fix.
  6252. filename = str(filename)
  6253. if filename == "":
  6254. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6255. else:
  6256. # self.worker_task.emit({'fcn': self.open_project,
  6257. # 'params': [filename]})
  6258. # The above was failing because open_project() is not
  6259. # thread safe. The new_project()
  6260. self.open_project(filename)
  6261. def on_fileopenhpgl2(self, signal, name=None):
  6262. """
  6263. File menu callback for opening a HPGL2.
  6264. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6265. :param name:
  6266. :return: None
  6267. """
  6268. self.defaults.report_usage("on_fileopenhpgl2")
  6269. App.log.debug("on_fileopenhpgl2()")
  6270. _filter_ = "HPGL2 Files (*.plt);;" \
  6271. "All Files (*.*)"
  6272. if name is None:
  6273. try:
  6274. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6275. directory=self.get_last_folder(),
  6276. filter=_filter_)
  6277. except TypeError:
  6278. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6279. filenames = [str(filename) for filename in filenames]
  6280. else:
  6281. filenames = [name]
  6282. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6283. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6284. _("Opening HPGL2 file.")),
  6285. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6286. color=QtGui.QColor("gray"))
  6287. if len(filenames) == 0:
  6288. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6289. else:
  6290. for filename in filenames:
  6291. if filename != '':
  6292. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6293. def on_file_openconfig(self, signal):
  6294. """
  6295. File menu callback for opening a config file.
  6296. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6297. :return: None
  6298. """
  6299. self.defaults.report_usage("on_file_openconfig")
  6300. App.log.debug("on_file_openconfig()")
  6301. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6302. try:
  6303. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6304. directory=self.data_path, filter=_filter_)
  6305. except TypeError:
  6306. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6307. filter=_filter_)
  6308. if filename == "":
  6309. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6310. else:
  6311. self.open_config_file(filename)
  6312. def on_file_exportsvg(self):
  6313. """
  6314. Callback for menu item File->Export SVG.
  6315. :return: None
  6316. """
  6317. self.defaults.report_usage("on_file_exportsvg")
  6318. App.log.debug("on_file_exportsvg()")
  6319. obj = self.collection.get_active()
  6320. if obj is None:
  6321. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6322. msg = _("Please Select a Geometry object to export")
  6323. msgbox = QtWidgets.QMessageBox()
  6324. msgbox.setInformativeText(msg)
  6325. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6326. msgbox.setDefaultButton(bt_ok)
  6327. msgbox.exec_()
  6328. return
  6329. # Check for more compatible types and add as required
  6330. if (not isinstance(obj, GeometryObject)
  6331. and not isinstance(obj, GerberObject)
  6332. and not isinstance(obj, CNCJobObject)
  6333. and not isinstance(obj, ExcellonObject)):
  6334. msg = '[ERROR_NOTCL] %s' % \
  6335. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6336. msgbox = QtWidgets.QMessageBox()
  6337. msgbox.setInformativeText(msg)
  6338. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6339. msgbox.setDefaultButton(bt_ok)
  6340. msgbox.exec_()
  6341. return
  6342. name = obj.options["name"]
  6343. _filter = "SVG File (*.svg);;All Files (*.*)"
  6344. try:
  6345. filename, _f = FCFileSaveDialog.get_saved_filename(
  6346. caption=_("Export SVG"),
  6347. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6348. filter=_filter)
  6349. except TypeError:
  6350. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6351. filename = str(filename)
  6352. if filename == "":
  6353. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6354. return
  6355. else:
  6356. self.export_svg(name, filename)
  6357. if self.defaults["global_open_style"] is False:
  6358. self.file_opened.emit("SVG", filename)
  6359. self.file_saved.emit("SVG", filename)
  6360. def on_file_exportpng(self):
  6361. self.defaults.report_usage("on_file_exportpng")
  6362. App.log.debug("on_file_exportpng()")
  6363. self.date = str(datetime.today()).rpartition('.')[0]
  6364. self.date = ''.join(c for c in self.date if c not in ':-')
  6365. self.date = self.date.replace(' ', '_')
  6366. if self.is_legacy is False:
  6367. image = _screenshot()
  6368. data = np.asarray(image)
  6369. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6370. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6371. return
  6372. filter_ = "PNG File (*.png);;All Files (*.*)"
  6373. try:
  6374. filename, _f = FCFileSaveDialog.get_saved_filename(
  6375. caption=_("Export PNG Image"),
  6376. directory=self.get_last_save_folder() + '/png_' + self.date,
  6377. filter=filter_)
  6378. except TypeError:
  6379. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6380. filename = str(filename)
  6381. if filename == "":
  6382. self.inform.emit(_("Cancelled."))
  6383. return
  6384. else:
  6385. if self.is_legacy is False:
  6386. write_png(filename, data)
  6387. else:
  6388. self.plotcanvas.figure.savefig(filename)
  6389. if self.defaults["global_open_style"] is False:
  6390. self.file_opened.emit("png", filename)
  6391. self.file_saved.emit("png", filename)
  6392. def on_file_savegerber(self):
  6393. """
  6394. Callback for menu item in Project context menu.
  6395. :return: None
  6396. """
  6397. self.defaults.report_usage("on_file_savegerber")
  6398. App.log.debug("on_file_savegerber()")
  6399. obj = self.collection.get_active()
  6400. if obj is None:
  6401. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6402. return
  6403. # Check for more compatible types and add as required
  6404. if not isinstance(obj, GerberObject):
  6405. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6406. return
  6407. name = self.collection.get_active().options["name"]
  6408. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6409. try:
  6410. filename, _f = FCFileSaveDialog.get_saved_filename(
  6411. caption="Save Gerber source file",
  6412. directory=self.get_last_save_folder() + '/' + name,
  6413. filter=_filter)
  6414. except TypeError:
  6415. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6416. filename = str(filename)
  6417. if filename == "":
  6418. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6419. return
  6420. else:
  6421. self.save_source_file(name, filename)
  6422. if self.defaults["global_open_style"] is False:
  6423. self.file_opened.emit("Gerber", filename)
  6424. self.file_saved.emit("Gerber", filename)
  6425. def on_file_savescript(self):
  6426. """
  6427. Callback for menu item in Project context menu.
  6428. :return: None
  6429. """
  6430. self.defaults.report_usage("on_file_savescript")
  6431. App.log.debug("on_file_savescript()")
  6432. obj = self.collection.get_active()
  6433. if obj is None:
  6434. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6435. return
  6436. # Check for more compatible types and add as required
  6437. if not isinstance(obj, ScriptObject):
  6438. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6439. return
  6440. name = self.collection.get_active().options["name"]
  6441. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6442. try:
  6443. filename, _f = FCFileSaveDialog.get_saved_filename(
  6444. caption="Save Script source file",
  6445. directory=self.get_last_save_folder() + '/' + name,
  6446. filter=_filter)
  6447. except TypeError:
  6448. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6449. filename = str(filename)
  6450. if filename == "":
  6451. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6452. return
  6453. else:
  6454. self.save_source_file(name, filename)
  6455. if self.defaults["global_open_style"] is False:
  6456. self.file_opened.emit("Script", filename)
  6457. self.file_saved.emit("Script", filename)
  6458. def on_file_savedocument(self):
  6459. """
  6460. Callback for menu item in Project context menu.
  6461. :return: None
  6462. """
  6463. self.defaults.report_usage("on_file_savedocument")
  6464. App.log.debug("on_file_savedocument()")
  6465. obj = self.collection.get_active()
  6466. if obj is None:
  6467. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6468. return
  6469. # Check for more compatible types and add as required
  6470. if not isinstance(obj, ScriptObject):
  6471. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6472. return
  6473. name = self.collection.get_active().options["name"]
  6474. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6475. try:
  6476. filename, _f = FCFileSaveDialog.get_saved_filename(
  6477. caption="Save Document source file",
  6478. directory=self.get_last_save_folder() + '/' + name,
  6479. filter=_filter)
  6480. except TypeError:
  6481. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6482. filename = str(filename)
  6483. if filename == "":
  6484. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6485. return
  6486. else:
  6487. self.save_source_file(name, filename)
  6488. if self.defaults["global_open_style"] is False:
  6489. self.file_opened.emit("Document", filename)
  6490. self.file_saved.emit("Document", filename)
  6491. def on_file_saveexcellon(self):
  6492. """
  6493. Callback for menu item in project context menu.
  6494. :return: None
  6495. """
  6496. self.defaults.report_usage("on_file_saveexcellon")
  6497. App.log.debug("on_file_saveexcellon()")
  6498. obj = self.collection.get_active()
  6499. if obj is None:
  6500. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6501. return
  6502. # Check for more compatible types and add as required
  6503. if not isinstance(obj, ExcellonObject):
  6504. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6505. return
  6506. name = self.collection.get_active().options["name"]
  6507. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6508. try:
  6509. filename, _f = FCFileSaveDialog.get_saved_filename(
  6510. caption=_("Save Excellon source file"),
  6511. directory=self.get_last_save_folder() + '/' + name,
  6512. filter=_filter)
  6513. except TypeError:
  6514. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6515. filename = str(filename)
  6516. if filename == "":
  6517. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6518. return
  6519. else:
  6520. self.save_source_file(name, filename)
  6521. if self.defaults["global_open_style"] is False:
  6522. self.file_opened.emit("Excellon", filename)
  6523. self.file_saved.emit("Excellon", filename)
  6524. def on_file_exportexcellon(self):
  6525. """
  6526. Callback for menu item File->Export->Excellon.
  6527. :return: None
  6528. """
  6529. self.defaults.report_usage("on_file_exportexcellon")
  6530. App.log.debug("on_file_exportexcellon()")
  6531. obj = self.collection.get_active()
  6532. if obj is None:
  6533. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6534. return
  6535. # Check for more compatible types and add as required
  6536. if not isinstance(obj, ExcellonObject):
  6537. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6538. return
  6539. name = self.collection.get_active().options["name"]
  6540. _filter = self.defaults["excellon_save_filters"]
  6541. try:
  6542. filename, _f = FCFileSaveDialog.get_saved_filename(
  6543. caption=_("Export Excellon"),
  6544. directory=self.get_last_save_folder() + '/' + name,
  6545. filter=_filter)
  6546. except TypeError:
  6547. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6548. filename = str(filename)
  6549. if filename == "":
  6550. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6551. return
  6552. else:
  6553. used_extension = filename.rpartition('.')[2]
  6554. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6555. self.export_excellon(name, filename)
  6556. if self.defaults["global_open_style"] is False:
  6557. self.file_opened.emit("Excellon", filename)
  6558. self.file_saved.emit("Excellon", filename)
  6559. def on_file_exportgerber(self):
  6560. """
  6561. Callback for menu item File->Export->Gerber.
  6562. :return: None
  6563. """
  6564. self.defaults.report_usage("on_file_exportgerber")
  6565. App.log.debug("on_file_exportgerber()")
  6566. obj = self.collection.get_active()
  6567. if obj is None:
  6568. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6569. return
  6570. # Check for more compatible types and add as required
  6571. if not isinstance(obj, GerberObject):
  6572. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6573. return
  6574. name = self.collection.get_active().options["name"]
  6575. _filter_ = self.defaults['gerber_save_filters']
  6576. try:
  6577. filename, _f = FCFileSaveDialog.get_saved_filename(
  6578. caption=_("Export Gerber"),
  6579. directory=self.get_last_save_folder() + '/' + name,
  6580. filter=_filter_)
  6581. except TypeError:
  6582. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6583. filename = str(filename)
  6584. if filename == "":
  6585. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6586. return
  6587. else:
  6588. used_extension = filename.rpartition('.')[2]
  6589. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6590. self.export_gerber(name, filename)
  6591. if self.defaults["global_open_style"] is False:
  6592. self.file_opened.emit("Gerber", filename)
  6593. self.file_saved.emit("Gerber", filename)
  6594. def on_file_exportdxf(self):
  6595. """
  6596. Callback for menu item File->Export DXF.
  6597. :return: None
  6598. """
  6599. self.defaults.report_usage("on_file_exportdxf")
  6600. App.log.debug("on_file_exportdxf()")
  6601. obj = self.collection.get_active()
  6602. if obj is None:
  6603. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6604. msg = _("Please Select a Geometry object to export")
  6605. msgbox = QtWidgets.QMessageBox()
  6606. msgbox.setInformativeText(msg)
  6607. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6608. msgbox.setDefaultButton(bt_ok)
  6609. msgbox.exec_()
  6610. return
  6611. # Check for more compatible types and add as required
  6612. if not isinstance(obj, GeometryObject):
  6613. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6614. msgbox = QtWidgets.QMessageBox()
  6615. msgbox.setInformativeText(msg)
  6616. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6617. msgbox.setDefaultButton(bt_ok)
  6618. msgbox.exec_()
  6619. return
  6620. name = self.collection.get_active().options["name"]
  6621. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6622. try:
  6623. filename, _f = FCFileSaveDialog.get_saved_filename(
  6624. caption=_("Export DXF"),
  6625. directory=self.get_last_save_folder() + '/' + name,
  6626. filter=_filter_)
  6627. except TypeError:
  6628. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6629. filename = str(filename)
  6630. if filename == "":
  6631. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6632. return
  6633. else:
  6634. self.export_dxf(name, filename)
  6635. if self.defaults["global_open_style"] is False:
  6636. self.file_opened.emit("DXF", filename)
  6637. self.file_saved.emit("DXF", filename)
  6638. def on_file_importsvg(self, type_of_obj):
  6639. """
  6640. Callback for menu item File->Import SVG.
  6641. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6642. :type type_of_obj: str
  6643. :return: None
  6644. """
  6645. self.defaults.report_usage("on_file_importsvg")
  6646. App.log.debug("on_file_importsvg()")
  6647. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6648. try:
  6649. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6650. directory=self.get_last_folder(), filter=_filter_)
  6651. except TypeError:
  6652. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6653. filter=_filter_)
  6654. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6655. type_of_obj = "geometry"
  6656. filenames = [str(filename) for filename in filenames]
  6657. if len(filenames) == 0:
  6658. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6659. else:
  6660. for filename in filenames:
  6661. if filename != '':
  6662. self.worker_task.emit({'fcn': self.import_svg,
  6663. 'params': [filename, type_of_obj]})
  6664. def on_file_importdxf(self, type_of_obj):
  6665. """
  6666. Callback for menu item File->Import DXF.
  6667. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6668. :type type_of_obj: str
  6669. :return: None
  6670. """
  6671. self.defaults.report_usage("on_file_importdxf")
  6672. App.log.debug("on_file_importdxf()")
  6673. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6674. try:
  6675. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6676. directory=self.get_last_folder(),
  6677. filter=_filter_)
  6678. except TypeError:
  6679. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6680. filter=_filter_)
  6681. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6682. type_of_obj = "geometry"
  6683. filenames = [str(filename) for filename in filenames]
  6684. if len(filenames) == 0:
  6685. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6686. else:
  6687. for filename in filenames:
  6688. if filename != '':
  6689. self.worker_task.emit({'fcn': self.import_dxf,
  6690. 'params': [filename, type_of_obj]})
  6691. # ###############################################################################################################
  6692. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6693. # ###############################################################################################################
  6694. def init_code_editor(self, name):
  6695. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6696. # add the tab if it was closed
  6697. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6698. self.text_editor_tab.setObjectName('text_editor_tab')
  6699. # delete the absolute and relative position and messages in the infobar
  6700. self.ui.position_label.setText("")
  6701. self.ui.rel_position_label.setText("")
  6702. # first clear previous text in text editor (if any)
  6703. self.text_editor_tab.code_editor.clear()
  6704. self.text_editor_tab.code_editor.setReadOnly(False)
  6705. self.toggle_codeeditor = True
  6706. self.text_editor_tab.code_editor.completer_enable = False
  6707. self.text_editor_tab.buttonRun.hide()
  6708. # make sure to keep a reference to the code editor
  6709. self.reference_code_editor = self.text_editor_tab.code_editor
  6710. # Switch plot_area to CNCJob tab
  6711. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6712. def on_view_source(self):
  6713. """
  6714. Called when the user wants to see the source file of the selected object
  6715. :return:
  6716. """
  6717. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6718. self.proc_container.view.set_busy(_("Loading..."))
  6719. try:
  6720. obj = self.collection.get_active()
  6721. except Exception as e:
  6722. log.debug("App.on_view_source() --> %s" % str(e))
  6723. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6724. return 'fail'
  6725. if obj is None:
  6726. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6727. return 'fail'
  6728. flt = "All Files (*.*)"
  6729. if obj.kind == 'gerber':
  6730. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6731. elif obj.kind == 'excellon':
  6732. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6733. elif obj.kind == 'cncjob':
  6734. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6735. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6736. # add the tab if it was closed
  6737. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6738. self.source_editor_tab.setObjectName('source_editor_tab')
  6739. # delete the absolute and relative position and messages in the infobar
  6740. self.ui.position_label.setText("")
  6741. self.ui.rel_position_label.setText("")
  6742. # first clear previous text in text editor (if any)
  6743. self.source_editor_tab.code_editor.clear()
  6744. self.source_editor_tab.code_editor.setReadOnly(False)
  6745. self.source_editor_tab.code_editor.completer_enable = False
  6746. self.source_editor_tab.buttonRun.hide()
  6747. # Switch plot_area to CNCJob tab
  6748. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6749. try:
  6750. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6751. except TypeError:
  6752. pass
  6753. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6754. try:
  6755. self.source_editor_tab.buttonSave.clicked.disconnect()
  6756. except TypeError:
  6757. pass
  6758. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6759. # then append the text from GCode to the text editor
  6760. if obj.kind == 'cncjob':
  6761. try:
  6762. file = obj.export_gcode(
  6763. preamble=self.defaults["cncjob_prepend"],
  6764. postamble=self.defaults["cncjob_append"],
  6765. to_file=True)
  6766. if file == 'fail':
  6767. return 'fail'
  6768. except AttributeError:
  6769. self.inform.emit('[WARNING_NOTCL] %s' %
  6770. _("There is no selected object for which to see it's source file code."))
  6771. return 'fail'
  6772. else:
  6773. try:
  6774. file = StringIO(obj.source_file)
  6775. except (AttributeError, TypeError):
  6776. self.inform.emit('[WARNING_NOTCL] %s' %
  6777. _("There is no selected object for which to see it's source file code."))
  6778. return 'fail'
  6779. self.source_editor_tab.t_frame.hide()
  6780. try:
  6781. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6782. # for line in file:
  6783. # QtWidgets.QApplication.processEvents()
  6784. # proc_line = str(line).strip('\n')
  6785. # self.source_editor_tab.code_editor.append(proc_line)
  6786. except Exception as e:
  6787. log.debug('App.on_view_source() -->%s' % str(e))
  6788. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6789. return
  6790. self.source_editor_tab.handleTextChanged()
  6791. self.source_editor_tab.t_frame.show()
  6792. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6793. self.proc_container.view.set_idle()
  6794. # self.ui.show()
  6795. def on_toggle_code_editor(self):
  6796. self.defaults.report_usage("on_toggle_code_editor()")
  6797. if self.toggle_codeeditor is False:
  6798. self.init_code_editor(name=_("Code Editor"))
  6799. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6800. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6801. self.text_editor_tab.buttonSave.clicked.disconnect()
  6802. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6803. else:
  6804. for idx in range(self.ui.plot_tab_area.count()):
  6805. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6806. self.ui.plot_tab_area.closeTab(idx)
  6807. break
  6808. self.toggle_codeeditor = False
  6809. def on_code_editor_close(self):
  6810. self.toggle_codeeditor = False
  6811. def goto_text_line(self):
  6812. """
  6813. Will scroll a text to the specified text line.
  6814. :return: None
  6815. """
  6816. dia_box = Dialog_box(title=_("Go to Line ..."),
  6817. label=_("Line:"),
  6818. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6819. initial_text='')
  6820. try:
  6821. line = int(dia_box.location) - 1
  6822. except (ValueError, TypeError):
  6823. line = 0
  6824. if dia_box.ok:
  6825. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6826. # at the top of the window
  6827. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6828. # get the document() of the TextEditor
  6829. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6830. # create a Text Cursor based on the searched line
  6831. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6832. # set cursor of the code editor with the cursor at the searcehd line
  6833. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6834. def on_filenewscript(self, silent=False):
  6835. """
  6836. Will create a new script file and open it in the Code Editor
  6837. :param silent: if True will not display status messages
  6838. :param name: if specified will be the name of the new script
  6839. :param text: pass a source file to the newly created script to be loaded in it
  6840. :return: None
  6841. """
  6842. if silent is False:
  6843. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6844. # delete the absolute and relative position and messages in the infobar
  6845. self.ui.position_label.setText("")
  6846. self.ui.rel_position_label.setText("")
  6847. self.new_script_object()
  6848. # script_text = script_obj.source_file
  6849. #
  6850. # self.proc_container.view.set_busy(_("Loading..."))
  6851. # script_obj.script_editor_tab.t_frame.hide()
  6852. #
  6853. # script_obj.script_editor_tab.t_frame.show()
  6854. # self.proc_container.view.set_idle()
  6855. def on_fileopenscript(self, name=None, silent=False):
  6856. """
  6857. Will open a Tcl script file into the Code Editor
  6858. :param silent: if True will not display status messages
  6859. :param name: name of a Tcl script file to open
  6860. :return: None
  6861. """
  6862. self.defaults.report_usage("on_fileopenscript")
  6863. App.log.debug("on_fileopenscript()")
  6864. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6865. "All Files (*.*)"
  6866. if name:
  6867. filenames = [name]
  6868. else:
  6869. try:
  6870. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6871. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6872. except TypeError:
  6873. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6874. if len(filenames) == 0:
  6875. if silent is False:
  6876. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6877. else:
  6878. for filename in filenames:
  6879. if filename != '':
  6880. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6881. def on_fileopenscript_example(self, name=None, silent=False):
  6882. """
  6883. Will open a Tcl script file into the Code Editor
  6884. :param silent: if True will not display status messages
  6885. :param name: name of a Tcl script file to open
  6886. :return:
  6887. """
  6888. self.defaults.report_usage("on_fileopenscript_example")
  6889. log.debug("on_fileopenscript_example()")
  6890. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6891. "All Files (*.*)"
  6892. # test if the app was frozen and choose the path for the configuration file
  6893. if getattr(sys, "frozen", False) is True:
  6894. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6895. else:
  6896. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6897. if name:
  6898. filenames = [name]
  6899. else:
  6900. try:
  6901. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6902. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6903. except TypeError:
  6904. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6905. if len(filenames) == 0:
  6906. if silent is False:
  6907. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6908. else:
  6909. for filename in filenames:
  6910. if filename != '':
  6911. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6912. def on_filerunscript(self, name=None, silent=False):
  6913. """
  6914. File menu callback for loading and running a TCL script.
  6915. :param silent: if True will not display status messages
  6916. :param name: name of a Tcl script file to be run by FlatCAM
  6917. :return: None
  6918. """
  6919. self.defaults.report_usage("on_filerunscript")
  6920. App.log.debug("on_file_runscript()")
  6921. if name:
  6922. filename = name
  6923. if self.cmd_line_headless != 1:
  6924. self.splash.showMessage('%s: %ssec\n%s' %
  6925. (_("Canvas initialization started.\n"
  6926. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6927. _("Executing ScriptObject file.")
  6928. ),
  6929. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6930. color=QtGui.QColor("gray"))
  6931. else:
  6932. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6933. "All Files (*.*)"
  6934. try:
  6935. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6936. directory=self.get_last_folder(), filter=_filter_)
  6937. except TypeError:
  6938. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6939. # The Qt methods above will return a QString which can cause problems later.
  6940. # So far json.dump() will fail to serialize it.
  6941. filename = str(filename)
  6942. if filename == "":
  6943. if silent is False:
  6944. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6945. else:
  6946. if self.cmd_line_headless != 1:
  6947. if self.ui.shell_dock.isHidden():
  6948. self.ui.shell_dock.show()
  6949. try:
  6950. with open(filename, "r") as tcl_script:
  6951. cmd_line_shellfile_content = tcl_script.read()
  6952. if self.cmd_line_headless != 1:
  6953. self.shell.exec_command(cmd_line_shellfile_content)
  6954. else:
  6955. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6956. if silent is False:
  6957. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6958. except Exception as e:
  6959. log.debug("App.on_filerunscript() -> %s" % str(e))
  6960. sys.exit(2)
  6961. def on_file_saveproject(self, silent=False):
  6962. """
  6963. Callback for menu item File->Save Project. Saves the project to
  6964. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6965. if set to None. The project is saved by calling ``self.save_project()``.
  6966. :param silent: if True will not display status messages
  6967. :return: None
  6968. """
  6969. self.defaults.report_usage("on_file_saveproject")
  6970. if self.project_filename is None:
  6971. self.on_file_saveprojectas()
  6972. else:
  6973. self.worker_task.emit({'fcn': self.save_project,
  6974. 'params': [self.project_filename, silent]})
  6975. if self.defaults["global_open_style"] is False:
  6976. self.file_opened.emit("project", self.project_filename)
  6977. self.file_saved.emit("project", self.project_filename)
  6978. self.set_ui_title(name=self.project_filename)
  6979. self.should_we_save = False
  6980. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6981. """
  6982. Callback for menu item File->Save Project As... Opens a file
  6983. chooser and saves the project to the given file via
  6984. ``self.save_project()``.
  6985. :param make_copy if to be create a copy of the project; boolean
  6986. :param use_thread: if to be run in a separate thread; boolean
  6987. :param quit_action: if to be followed by quiting the application; boolean
  6988. :return: None
  6989. """
  6990. self.defaults.report_usage("on_file_saveprojectas")
  6991. self.date = str(datetime.today()).rpartition('.')[0]
  6992. self.date = ''.join(c for c in self.date if c not in ':-')
  6993. self.date = self.date.replace(' ', '_')
  6994. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6995. try:
  6996. filename, _f = FCFileSaveDialog.get_saved_filename(
  6997. caption=_("Save Project As ..."),
  6998. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6999. proj=_("Project")),
  7000. filter=filter_
  7001. )
  7002. except TypeError:
  7003. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  7004. filename = str(filename)
  7005. if filename == '':
  7006. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7007. return
  7008. if use_thread is True:
  7009. self.worker_task.emit({'fcn': self.save_project,
  7010. 'params': [filename, quit_action]})
  7011. else:
  7012. self.save_project(filename, quit_action)
  7013. # self.save_project(filename)
  7014. if self.defaults["global_open_style"] is False:
  7015. self.file_opened.emit("project", filename)
  7016. self.file_saved.emit("project", filename)
  7017. if not make_copy:
  7018. self.project_filename = filename
  7019. self.set_ui_title(name=self.project_filename)
  7020. self.should_we_save = False
  7021. def on_file_save_objects_pdf(self, use_thread=True):
  7022. self.date = str(datetime.today()).rpartition('.')[0]
  7023. self.date = ''.join(c for c in self.date if c not in ':-')
  7024. self.date = self.date.replace(' ', '_')
  7025. try:
  7026. obj_selection = self.collection.get_selected()
  7027. if len(obj_selection) == 1:
  7028. obj_name = str(obj_selection[0].options['name'])
  7029. else:
  7030. obj_name = _("FlatCAM objects print")
  7031. except AttributeError as err:
  7032. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7033. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7034. return
  7035. if not obj_selection:
  7036. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7037. return
  7038. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7039. try:
  7040. filename, _f = FCFileSaveDialog.get_saved_filename(
  7041. caption=_("Save Object as PDF ..."),
  7042. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7043. obj_name=obj_name,
  7044. date=self.date),
  7045. filter=filter_
  7046. )
  7047. except TypeError:
  7048. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7049. filename = str(filename)
  7050. if filename == '':
  7051. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7052. return
  7053. if use_thread is True:
  7054. self.proc_container.new(_("Printing PDF ... Please wait."))
  7055. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7056. else:
  7057. self.save_pdf(filename, obj_selection)
  7058. # self.save_project(filename)
  7059. if self.defaults["global_open_style"] is False:
  7060. self.file_opened.emit("pdf", filename)
  7061. self.file_saved.emit("pdf", filename)
  7062. def save_pdf(self, file_name, obj_selection):
  7063. p_size = self.defaults['global_workspaceT']
  7064. orientation = self.defaults['global_workspace_orientation']
  7065. color = 'black'
  7066. transparency_level = 1.0
  7067. self.pagesize = {}
  7068. self.pagesize.update(
  7069. {
  7070. 'Bounds': None,
  7071. 'A0': (841 * mm, 1189 * mm),
  7072. 'A1': (594 * mm, 841 * mm),
  7073. 'A2': (420 * mm, 594 * mm),
  7074. 'A3': (297 * mm, 420 * mm),
  7075. 'A4': (210 * mm, 297 * mm),
  7076. 'A5': (148 * mm, 210 * mm),
  7077. 'A6': (105 * mm, 148 * mm),
  7078. 'A7': (74 * mm, 105 * mm),
  7079. 'A8': (52 * mm, 74 * mm),
  7080. 'A9': (37 * mm, 52 * mm),
  7081. 'A10': (26 * mm, 37 * mm),
  7082. 'B0': (1000 * mm, 1414 * mm),
  7083. 'B1': (707 * mm, 1000 * mm),
  7084. 'B2': (500 * mm, 707 * mm),
  7085. 'B3': (353 * mm, 500 * mm),
  7086. 'B4': (250 * mm, 353 * mm),
  7087. 'B5': (176 * mm, 250 * mm),
  7088. 'B6': (125 * mm, 176 * mm),
  7089. 'B7': (88 * mm, 125 * mm),
  7090. 'B8': (62 * mm, 88 * mm),
  7091. 'B9': (44 * mm, 62 * mm),
  7092. 'B10': (31 * mm, 44 * mm),
  7093. 'C0': (917 * mm, 1297 * mm),
  7094. 'C1': (648 * mm, 917 * mm),
  7095. 'C2': (458 * mm, 648 * mm),
  7096. 'C3': (324 * mm, 458 * mm),
  7097. 'C4': (229 * mm, 324 * mm),
  7098. 'C5': (162 * mm, 229 * mm),
  7099. 'C6': (114 * mm, 162 * mm),
  7100. 'C7': (81 * mm, 114 * mm),
  7101. 'C8': (57 * mm, 81 * mm),
  7102. 'C9': (40 * mm, 57 * mm),
  7103. 'C10': (28 * mm, 40 * mm),
  7104. # American paper sizes
  7105. 'LETTER': (8.5 * inch, 11 * inch),
  7106. 'LEGAL': (8.5 * inch, 14 * inch),
  7107. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7108. # From https://en.wikipedia.org/wiki/Paper_size
  7109. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7110. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7111. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7112. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7113. 'LEDGER': (17 * inch, 11 * inch),
  7114. }
  7115. )
  7116. exported_svg = []
  7117. for obj in obj_selection:
  7118. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7119. scale_factor_x=None, scale_factor_y=None,
  7120. skew_factor_x=None, skew_factor_y=None,
  7121. mirror=None)
  7122. if obj.kind.lower() == 'gerber':
  7123. # color = self.defaults["gerber_plot_fill"][:-2]
  7124. color = obj.fill_color[:-2]
  7125. elif obj.kind.lower() == 'excellon':
  7126. color = '#C40000'
  7127. elif obj.kind.lower() == 'geometry':
  7128. color = self.defaults["global_draw_color"]
  7129. # Change the attributes of the exported SVG
  7130. # We don't need stroke-width
  7131. # We set opacity to maximum
  7132. # We set the colour to WHITE
  7133. root = ET.fromstring(svg_obj)
  7134. for child in root:
  7135. child.set('fill', str(color))
  7136. child.set('opacity', str(transparency_level))
  7137. child.set('stroke', str(color))
  7138. exported_svg.append(ET.tostring(root))
  7139. xmin = Inf
  7140. ymin = Inf
  7141. xmax = -Inf
  7142. ymax = -Inf
  7143. for obj in obj_selection:
  7144. try:
  7145. gxmin, gymin, gxmax, gymax = obj.bounds()
  7146. xmin = min([xmin, gxmin])
  7147. ymin = min([ymin, gymin])
  7148. xmax = max([xmax, gxmax])
  7149. ymax = max([ymax, gymax])
  7150. except Exception as e:
  7151. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7152. # Determine bounding area for svg export
  7153. bounds = [xmin, ymin, xmax, ymax]
  7154. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7155. # This contain the measure units
  7156. uom = obj_selection[0].units.lower()
  7157. # Define a boundary around SVG of about 1.0mm (~39mils)
  7158. if uom in "mm":
  7159. boundary = 1.0
  7160. else:
  7161. boundary = 0.0393701
  7162. # Convert everything to strings for use in the xml doc
  7163. svgwidth = str(size[0] + (2 * boundary))
  7164. svgheight = str(size[1] + (2 * boundary))
  7165. minx = str(bounds[0] - boundary)
  7166. miny = str(bounds[1] + boundary + size[1])
  7167. # Add a SVG Header and footer to the svg output from shapely
  7168. # The transform flips the Y Axis so that everything renders
  7169. # properly within svg apps such as inkscape
  7170. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7171. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7172. svg_header += 'width="' + svgwidth + uom + '" '
  7173. svg_header += 'height="' + svgheight + uom + '" '
  7174. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7175. svg_header += '>'
  7176. svg_header += '<g transform="scale(1,-1)">'
  7177. svg_footer = '</g> </svg>'
  7178. svg_elem = str(svg_header)
  7179. for svg_item in exported_svg:
  7180. svg_elem += str(svg_item)
  7181. svg_elem += str(svg_footer)
  7182. # Parse the xml through a xml parser just to add line feeds
  7183. # and to make it look more pretty for the output
  7184. doc = parse_xml_string(svg_elem)
  7185. doc_final = doc.toprettyxml()
  7186. try:
  7187. if self.defaults['units'].upper() == 'IN':
  7188. unit = inch
  7189. else:
  7190. unit = mm
  7191. doc_final = StringIO(doc_final)
  7192. drawing = svg2rlg(doc_final)
  7193. if p_size == 'Bounds':
  7194. renderPDF.drawToFile(drawing, file_name)
  7195. else:
  7196. if orientation == 'p':
  7197. page_size = portrait(self.pagesize[p_size])
  7198. else:
  7199. page_size = landscape(self.pagesize[p_size])
  7200. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7201. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7202. renderPDF.draw(drawing, my_canvas, 0, 0)
  7203. my_canvas.save()
  7204. except Exception as e:
  7205. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7206. return 'fail'
  7207. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7208. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7209. """
  7210. Exports a Geometry Object to an SVG file.
  7211. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7212. :param filename: Path to the SVG file to save to.
  7213. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7214. :return:
  7215. """
  7216. self.defaults.report_usage("export_svg()")
  7217. if filename is None:
  7218. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7219. is not None else self.defaults["global_last_folder"]
  7220. self.log.debug("export_svg()")
  7221. try:
  7222. obj = self.collection.get_by_name(str(obj_name))
  7223. except Exception:
  7224. # TODO: The return behavior has not been established... should raise exception?
  7225. return "Could not retrieve object: %s" % obj_name
  7226. with self.proc_container.new(_("Exporting SVG")) as proc:
  7227. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7228. # Determine bounding area for svg export
  7229. bounds = obj.bounds()
  7230. size = obj.size()
  7231. # Convert everything to strings for use in the xml doc
  7232. svgwidth = str(size[0])
  7233. svgheight = str(size[1])
  7234. minx = str(bounds[0])
  7235. miny = str(bounds[1] - size[1])
  7236. uom = obj.units.lower()
  7237. # Add a SVG Header and footer to the svg output from shapely
  7238. # The transform flips the Y Axis so that everything renders
  7239. # properly within svg apps such as inkscape
  7240. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7241. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7242. svg_header += 'width="' + svgwidth + uom + '" '
  7243. svg_header += 'height="' + svgheight + uom + '" '
  7244. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7245. svg_header += '<g transform="scale(1,-1)">'
  7246. svg_footer = '</g> </svg>'
  7247. svg_elem = svg_header + exported_svg + svg_footer
  7248. # Parse the xml through a xml parser just to add line feeds
  7249. # and to make it look more pretty for the output
  7250. svgcode = parse_xml_string(svg_elem)
  7251. svgcode = svgcode.toprettyxml()
  7252. try:
  7253. with open(filename, 'w') as fp:
  7254. fp.write(svgcode)
  7255. except PermissionError:
  7256. self.inform.emit('[WARNING] %s' %
  7257. _("Permission denied, saving not possible.\n"
  7258. "Most likely another app is holding the file open and not accessible."))
  7259. return 'fail'
  7260. if self.defaults["global_open_style"] is False:
  7261. self.file_opened.emit("SVG", filename)
  7262. self.file_saved.emit("SVG", filename)
  7263. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7264. def save_source_file(self, obj_name, filename, use_thread=True):
  7265. """
  7266. Exports a FlatCAM Object to an Gerber/Excellon file.
  7267. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7268. :param filename: Path to the Gerber file to save to.
  7269. :param use_thread: if to be run in a separate thread
  7270. :return:
  7271. """
  7272. self.defaults.report_usage("save source file()")
  7273. if filename is None:
  7274. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7275. is not None else self.defaults["global_last_folder"]
  7276. self.log.debug("save source file()")
  7277. obj = self.collection.get_by_name(obj_name)
  7278. file_string = StringIO(obj.source_file)
  7279. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7280. if file_string.getvalue() == '':
  7281. self.inform.emit('[ERROR_NOTCL] %s' %
  7282. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7283. return 'fail'
  7284. try:
  7285. with open(filename, 'w') as file:
  7286. file.writelines('G04*\n')
  7287. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7288. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7289. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7290. file.writelines('G04 Created on : %s*\n' % time_string)
  7291. for line in file_string:
  7292. file.writelines(line)
  7293. except PermissionError:
  7294. self.inform.emit('[WARNING] %s' %
  7295. _("Permission denied, saving not possible.\n"
  7296. "Most likely another app is holding the file open and not accessible."))
  7297. return 'fail'
  7298. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7299. """
  7300. Exports a Excellon Object to an Excellon file.
  7301. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7302. :param filename: Path to the Excellon file to save to.
  7303. :param local_use:
  7304. :param use_thread: if to be run in a separate thread
  7305. :return:
  7306. """
  7307. self.defaults.report_usage("export_excellon()")
  7308. if filename is None:
  7309. if self.defaults["global_last_save_folder"]:
  7310. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7311. else:
  7312. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7313. self.log.debug("export_excellon()")
  7314. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7315. self.defaults["excellon_exp_decimals"]
  7316. )
  7317. if local_use is None:
  7318. try:
  7319. obj = self.collection.get_by_name(str(obj_name))
  7320. except Exception:
  7321. return "Could not retrieve object: %s" % obj_name
  7322. else:
  7323. obj = local_use
  7324. if not isinstance(obj, ExcellonObject):
  7325. self.inform.emit('[ERROR_NOTCL] %s' %
  7326. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7327. return
  7328. # updated units
  7329. eunits = self.defaults["excellon_exp_units"]
  7330. ewhole = self.defaults["excellon_exp_integer"]
  7331. efract = self.defaults["excellon_exp_decimals"]
  7332. ezeros = self.defaults["excellon_exp_zeros"]
  7333. eformat = self.defaults["excellon_exp_format"]
  7334. slot_type = self.defaults["excellon_exp_slot_type"]
  7335. fc_units = self.defaults['units'].upper()
  7336. if fc_units == 'MM':
  7337. factor = 1 if eunits == 'METRIC' else 0.03937
  7338. else:
  7339. factor = 25.4 if eunits == 'METRIC' else 1
  7340. def make_excellon():
  7341. try:
  7342. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7343. header = 'M48\n'
  7344. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7345. (str(self.version), str(self.version_date))
  7346. header += ';Filename: %s' % str(obj_name) + '\n'
  7347. header += ';Created on : %s' % time_str + '\n'
  7348. if eformat == 'dec':
  7349. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7350. header += eunits + '\n'
  7351. for tool in obj.tools:
  7352. if eunits == 'METRIC':
  7353. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7354. tool=str(tool),
  7355. dec=2)
  7356. else:
  7357. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7358. tool=str(tool),
  7359. dec=4)
  7360. else:
  7361. if ezeros == 'LZ':
  7362. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7363. form='ndec', e_zeros='LZ', factor=factor,
  7364. slot_type=slot_type)
  7365. header += '%s,%s\n' % (eunits, 'LZ')
  7366. header += format_exc
  7367. for tool in obj.tools:
  7368. if eunits == 'METRIC':
  7369. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7370. tool=str(tool),
  7371. dec=2)
  7372. else:
  7373. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7374. tool=str(tool),
  7375. dec=4)
  7376. else:
  7377. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7378. form='ndec', e_zeros='TZ', factor=factor,
  7379. slot_type=slot_type)
  7380. header += '%s,%s\n' % (eunits, 'TZ')
  7381. header += format_exc
  7382. for tool in obj.tools:
  7383. if eunits == 'METRIC':
  7384. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7385. tool=str(tool),
  7386. dec=2)
  7387. else:
  7388. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7389. tool=str(tool),
  7390. dec=4)
  7391. header += '%\n'
  7392. footer = 'M30\n'
  7393. exported_excellon = header
  7394. exported_excellon += excellon_code
  7395. exported_excellon += footer
  7396. if local_use is None:
  7397. try:
  7398. with open(filename, 'w') as fp:
  7399. fp.write(exported_excellon)
  7400. except PermissionError:
  7401. self.inform.emit('[WARNING] %s' %
  7402. _("Permission denied, saving not possible.\n"
  7403. "Most likely another app is holding the file open and not accessible."))
  7404. return 'fail'
  7405. if self.defaults["global_open_style"] is False:
  7406. self.file_opened.emit("Excellon", filename)
  7407. self.file_saved.emit("Excellon", filename)
  7408. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7409. else:
  7410. return exported_excellon
  7411. except Exception as e:
  7412. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7413. return 'fail'
  7414. if use_thread is True:
  7415. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7416. def job_thread_exc(app_obj):
  7417. ret = make_excellon()
  7418. if ret == 'fail':
  7419. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7420. return
  7421. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7422. else:
  7423. eret = make_excellon()
  7424. if eret == 'fail':
  7425. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7426. return 'fail'
  7427. if local_use is not None:
  7428. return eret
  7429. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7430. """
  7431. Exports a Gerber Object to an Gerber file.
  7432. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7433. :param filename: Path to the Gerber file to save to.
  7434. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7435. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7436. :param use_thread: if to be run in a separate thread
  7437. :return:
  7438. """
  7439. self.defaults.report_usage("export_gerber()")
  7440. if filename is None:
  7441. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7442. is not None else self.defaults["global_last_folder"]
  7443. self.log.debug("export_gerber()")
  7444. if local_use is None:
  7445. try:
  7446. obj = self.collection.get_by_name(str(obj_name))
  7447. except Exception:
  7448. return "Could not retrieve object: %s" % obj_name
  7449. else:
  7450. obj = local_use
  7451. # updated units
  7452. gunits = self.defaults["gerber_exp_units"]
  7453. gwhole = self.defaults["gerber_exp_integer"]
  7454. gfract = self.defaults["gerber_exp_decimals"]
  7455. gzeros = self.defaults["gerber_exp_zeros"]
  7456. fc_units = self.defaults['units'].upper()
  7457. if fc_units == 'MM':
  7458. factor = 1 if gunits == 'MM' else 0.03937
  7459. else:
  7460. factor = 25.4 if gunits == 'MM' else 1
  7461. def make_gerber():
  7462. try:
  7463. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7464. header = 'G04*\n'
  7465. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7466. (str(self.version), str(self.version_date))
  7467. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7468. header += 'G04 Created on : %s*' % time_str + '\n'
  7469. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7470. header += "%MO{units}*%\n".format(units=gunits)
  7471. for apid in obj.apertures:
  7472. if obj.apertures[apid]['type'] == 'C':
  7473. header += "%ADD{apid}{type},{size}*%\n".format(
  7474. apid=str(apid),
  7475. type='C',
  7476. size=(factor * obj.apertures[apid]['size'])
  7477. )
  7478. elif obj.apertures[apid]['type'] == 'R':
  7479. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7480. apid=str(apid),
  7481. type='R',
  7482. width=(factor * obj.apertures[apid]['width']),
  7483. height=(factor * obj.apertures[apid]['height'])
  7484. )
  7485. elif obj.apertures[apid]['type'] == 'O':
  7486. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7487. apid=str(apid),
  7488. type='O',
  7489. width=(factor * obj.apertures[apid]['width']),
  7490. height=(factor * obj.apertures[apid]['height'])
  7491. )
  7492. header += '\n'
  7493. # obsolete units but some software may need it
  7494. if gunits == 'IN':
  7495. header += 'G70*\n'
  7496. else:
  7497. header += 'G71*\n'
  7498. # Absolute Mode
  7499. header += 'G90*\n'
  7500. header += 'G01*\n'
  7501. # positive polarity
  7502. header += '%LPD*%\n'
  7503. footer = 'M02*\n'
  7504. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7505. exported_gerber = header
  7506. exported_gerber += gerber_code
  7507. exported_gerber += footer
  7508. if local_use is None:
  7509. try:
  7510. with open(filename, 'w') as fp:
  7511. fp.write(exported_gerber)
  7512. except PermissionError:
  7513. self.inform.emit('[WARNING] %s' %
  7514. _("Permission denied, saving not possible.\n"
  7515. "Most likely another app is holding the file open and not accessible."))
  7516. return 'fail'
  7517. if self.defaults["global_open_style"] is False:
  7518. self.file_opened.emit("Gerber", filename)
  7519. self.file_saved.emit("Gerber", filename)
  7520. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7521. else:
  7522. return exported_gerber
  7523. except Exception as e:
  7524. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7525. return 'fail'
  7526. if use_thread is True:
  7527. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7528. def job_thread_grb(app_obj):
  7529. ret = make_gerber()
  7530. if ret == 'fail':
  7531. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7532. return
  7533. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7534. else:
  7535. gret = make_gerber()
  7536. if gret == 'fail':
  7537. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7538. return 'fail'
  7539. if local_use is not None:
  7540. return gret
  7541. def export_dxf(self, obj_name, filename, use_thread=True):
  7542. """
  7543. Exports a Geometry Object to an DXF file.
  7544. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7545. :param filename: Path to the DXF file to save to.
  7546. :param use_thread: if to be run in a separate thread
  7547. :return:
  7548. """
  7549. self.defaults.report_usage("export_dxf()")
  7550. if filename is None:
  7551. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7552. is not None else self.defaults["global_last_folder"]
  7553. self.log.debug("export_dxf()")
  7554. try:
  7555. obj = self.collection.get_by_name(str(obj_name))
  7556. except Exception:
  7557. # TODO: The return behavior has not been established... should raise exception?
  7558. return "Could not retrieve object: %s" % obj_name
  7559. def make_dxf():
  7560. try:
  7561. dxf_code = obj.export_dxf()
  7562. dxf_code.saveas(filename)
  7563. if self.defaults["global_open_style"] is False:
  7564. self.file_opened.emit("DXF", filename)
  7565. self.file_saved.emit("DXF", filename)
  7566. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7567. except Exception:
  7568. return 'fail'
  7569. if use_thread is True:
  7570. with self.proc_container.new(_("Exporting DXF")) as proc:
  7571. def job_thread_exc(app_obj):
  7572. ret_dxf_val = make_dxf()
  7573. if ret_dxf_val == 'fail':
  7574. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7575. return
  7576. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7577. else:
  7578. ret = make_dxf()
  7579. if ret == 'fail':
  7580. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7581. return
  7582. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7583. """
  7584. Adds a new Geometry Object to the projects and populates
  7585. it with shapes extracted from the SVG file.
  7586. :param plot: If True then the resulting object will be plotted on canvas
  7587. :param filename: Path to the SVG file.
  7588. :param geo_type: Type of FlatCAM object that will be created from SVG
  7589. :param outname: The name given to the resulting FlatCAM object
  7590. :return:
  7591. """
  7592. self.defaults.report_usage("import_svg()")
  7593. log.debug("App.import_svg()")
  7594. obj_type = ""
  7595. if geo_type is None or geo_type == "geometry":
  7596. obj_type = "geometry"
  7597. elif geo_type == "gerber":
  7598. obj_type = "gerber"
  7599. else:
  7600. self.inform.emit('[ERROR_NOTCL] %s' %
  7601. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7602. return
  7603. units = self.defaults['units'].upper()
  7604. def obj_init(geo_obj, app_obj):
  7605. geo_obj.import_svg(filename, obj_type, units=units)
  7606. geo_obj.multigeo = False
  7607. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7608. with self.proc_container.new(_("Importing SVG")) as proc:
  7609. # Object name
  7610. name = outname or filename.split('/')[-1].split('\\')[-1]
  7611. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7612. if ret == 'fail':
  7613. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7614. return 'fail'
  7615. # Register recent file
  7616. self.file_opened.emit("svg", filename)
  7617. # GUI feedback
  7618. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7619. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7620. """
  7621. Adds a new Geometry Object to the projects and populates
  7622. it with shapes extracted from the DXF file.
  7623. :param filename: Path to the DXF file.
  7624. :param geo_type: Type of FlatCAM object that will be created from DXF
  7625. :param outname: Name for the imported Geometry
  7626. :param plot: If True then the resulting object will be plotted on canvas
  7627. :return:
  7628. """
  7629. self.defaults.report_usage("import_dxf()")
  7630. obj_type = ""
  7631. if geo_type is None or geo_type == "geometry":
  7632. obj_type = "geometry"
  7633. elif geo_type == "gerber":
  7634. obj_type = geo_type
  7635. else:
  7636. self.inform.emit('[ERROR_NOTCL] %s' %
  7637. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7638. return
  7639. units = self.defaults['units'].upper()
  7640. def obj_init(geo_obj, app_obj):
  7641. geo_obj.import_dxf(filename, obj_type, units=units)
  7642. geo_obj.multigeo = False
  7643. with self.proc_container.new(_("Importing DXF")):
  7644. # Object name
  7645. name = outname or filename.split('/')[-1].split('\\')[-1]
  7646. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7647. if ret == 'fail':
  7648. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7649. return 'fail'
  7650. # Register recent file
  7651. self.file_opened.emit("dxf", filename)
  7652. # GUI feedback
  7653. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7654. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7655. """
  7656. Opens a Gerber file, parses it and creates a new object for
  7657. it in the program. Thread-safe.
  7658. :param outname: Name of the resulting object. None causes the
  7659. name to be that of the file. Str.
  7660. :param filename: Gerber file filename
  7661. :type filename: str
  7662. :param plot: boolean, to plot or not the resulting object
  7663. :param from_tcl: True if run from Tcl Shell
  7664. :return: None
  7665. """
  7666. # How the object should be initialized
  7667. def obj_init(gerber_obj, app_obj):
  7668. assert isinstance(gerber_obj, GerberObject), \
  7669. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7670. # Opening the file happens here
  7671. try:
  7672. gerber_obj.parse_file(filename)
  7673. except IOError:
  7674. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7675. return "fail"
  7676. except ParseError as err:
  7677. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7678. app_obj.log.error(str(err))
  7679. return "fail"
  7680. except Exception as e:
  7681. log.debug("App.open_gerber() --> %s" % str(e))
  7682. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7683. msg += traceback.format_exc()
  7684. app_obj.inform.emit(msg)
  7685. return "fail"
  7686. if gerber_obj.is_empty():
  7687. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7688. _("Object is not Gerber file or empty. Aborting object creation."))
  7689. return "fail"
  7690. App.log.debug("open_gerber()")
  7691. with self.proc_container.new(_("Opening Gerber")):
  7692. # Object name
  7693. name = outname or filename.split('/')[-1].split('\\')[-1]
  7694. # # ## Object creation # ##
  7695. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7696. if ret_val == 'fail':
  7697. if from_tcl:
  7698. filename = self.defaults['global_tcl_path'] + '/' + name
  7699. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7700. if ret_val == 'fail':
  7701. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7702. return 'fail'
  7703. # Register recent file
  7704. self.file_opened.emit("gerber", filename)
  7705. # GUI feedback
  7706. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7707. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7708. """
  7709. Opens an Excellon file, parses it and creates a new object for
  7710. it in the program. Thread-safe.
  7711. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7712. :param filename: Excellon file filename
  7713. :type filename: str
  7714. :param plot: boolean, to plot or not the resulting object
  7715. :param from_tcl: True if run from Tcl Shell
  7716. :return: None
  7717. """
  7718. App.log.debug("open_excellon()")
  7719. # How the object should be initialized
  7720. def obj_init(excellon_obj, app_obj):
  7721. try:
  7722. ret = excellon_obj.parse_file(filename=filename)
  7723. if ret == "fail":
  7724. log.debug("Excellon parsing failed.")
  7725. self.inform.emit('[ERROR_NOTCL] %s' %
  7726. _("This is not Excellon file."))
  7727. return "fail"
  7728. except IOError:
  7729. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7730. (_("Cannot open file"), filename))
  7731. log.debug("Could not open Excellon object.")
  7732. return "fail"
  7733. except Exception:
  7734. msg = '[ERROR_NOTCL] %s' % \
  7735. _("An internal error has occurred. See shell.\n")
  7736. msg += traceback.format_exc()
  7737. app_obj.inform.emit(msg)
  7738. return "fail"
  7739. ret = excellon_obj.create_geometry()
  7740. if ret == 'fail':
  7741. log.debug("Could not create geometry for Excellon object.")
  7742. return "fail"
  7743. for tool in excellon_obj.tools:
  7744. if excellon_obj.tools[tool]['solid_geometry']:
  7745. return
  7746. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7747. return "fail"
  7748. with self.proc_container.new(_("Opening Excellon.")):
  7749. # Object name
  7750. name = outname or filename.split('/')[-1].split('\\')[-1]
  7751. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7752. if ret_val == 'fail':
  7753. if from_tcl:
  7754. filename = self.defaults['global_tcl_path'] + '/' + name
  7755. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7756. if ret_val == 'fail':
  7757. self.inform.emit('[ERROR_NOTCL] %s' %
  7758. _('Open Excellon file failed. Probable not an Excellon file.'))
  7759. return
  7760. # Register recent file
  7761. self.file_opened.emit("excellon", filename)
  7762. # GUI feedback
  7763. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7764. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7765. """
  7766. Opens a G-gcode file, parses it and creates a new object for
  7767. it in the program. Thread-safe.
  7768. :param filename: G-code file filename
  7769. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7770. :param force_parsing:
  7771. :param plot: If True plot the object on canvas
  7772. :param from_tcl: True if run from Tcl Shell
  7773. :return: None
  7774. """
  7775. App.log.debug("open_gcode()")
  7776. # How the object should be initialized
  7777. def obj_init(job_obj, app_obj_):
  7778. """
  7779. :param job_obj: the resulting object
  7780. :type app_obj_: App
  7781. """
  7782. assert isinstance(app_obj_, App), \
  7783. "Initializer expected App, got %s" % type(app_obj_)
  7784. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7785. try:
  7786. f = open(filename)
  7787. gcode = f.read()
  7788. f.close()
  7789. except IOError:
  7790. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7791. return "fail"
  7792. job_obj.gcode = gcode
  7793. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7794. if gcode_ret == "fail":
  7795. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7796. return "fail"
  7797. job_obj.create_geometry()
  7798. with self.proc_container.new(_("Opening G-Code.")):
  7799. # Object name
  7800. name = outname or filename.split('/')[-1].split('\\')[-1]
  7801. # New object creation and file processing
  7802. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7803. if ret_val == 'fail':
  7804. if from_tcl:
  7805. filename = self.defaults['global_tcl_path'] + '/' + name
  7806. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7807. if ret_val == 'fail':
  7808. self.inform.emit('[ERROR_NOTCL] %s' %
  7809. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7810. "Try to load it from File menu.\n "
  7811. "Attempting to create a FlatCAM CNCJob Object from "
  7812. "G-Code file failed during processing"))
  7813. return "fail"
  7814. # Register recent file
  7815. self.file_opened.emit("cncjob", filename)
  7816. # GUI feedback
  7817. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7818. def open_hpgl2(self, filename, outname=None):
  7819. """
  7820. Opens a HPGL2 file, parses it and creates a new object for
  7821. it in the program. Thread-safe.
  7822. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7823. :param filename: HPGL2 file filename
  7824. :return: None
  7825. """
  7826. filename = filename
  7827. # How the object should be initialized
  7828. def obj_init(geo_obj, app_obj):
  7829. assert isinstance(geo_obj, GeometryObject), \
  7830. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7831. # Opening the file happens here
  7832. obj = HPGL2(self)
  7833. try:
  7834. HPGL2.parse_file(obj, filename)
  7835. except IOError:
  7836. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7837. return "fail"
  7838. except ParseError as err:
  7839. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7840. app_obj.log.error(str(err))
  7841. return "fail"
  7842. except Exception as e:
  7843. log.debug("App.open_hpgl2() --> %s" % str(e))
  7844. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7845. msg += traceback.format_exc()
  7846. app_obj.inform.emit(msg)
  7847. return "fail"
  7848. geo_obj.multigeo = True
  7849. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7850. geo_obj.tools = deepcopy(obj.tools)
  7851. geo_obj.source_file = deepcopy(obj.source_file)
  7852. del obj
  7853. if not geo_obj.solid_geometry:
  7854. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7855. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7856. return "fail"
  7857. App.log.debug("open_hpgl2()")
  7858. with self.proc_container.new(_("Opening HPGL2")):
  7859. # Object name
  7860. name = outname or filename.split('/')[-1].split('\\')[-1]
  7861. # # ## Object creation # ##
  7862. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7863. if ret == 'fail':
  7864. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7865. return 'fail'
  7866. # Register recent file
  7867. self.file_opened.emit("geometry", filename)
  7868. # GUI feedback
  7869. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7870. def open_script(self, filename, outname=None, silent=False):
  7871. """
  7872. Opens a Script file, parses it and creates a new object for
  7873. it in the program. Thread-safe.
  7874. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7875. :param filename: Script file filename
  7876. :param silent: If True there will be no messages printed to StatusBar
  7877. :return: None
  7878. """
  7879. def obj_init(script_obj, app_obj):
  7880. assert isinstance(script_obj, ScriptObject), \
  7881. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7882. if silent is False:
  7883. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7884. try:
  7885. script_obj.parse_file(filename)
  7886. except IOError:
  7887. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7888. return "fail"
  7889. except ParseError as err:
  7890. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7891. app_obj.log.error(str(err))
  7892. return "fail"
  7893. except Exception as e:
  7894. log.debug("App.open_script() -> %s" % str(e))
  7895. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7896. msg += traceback.format_exc()
  7897. app_obj.inform.emit(msg)
  7898. return "fail"
  7899. App.log.debug("open_script()")
  7900. with self.proc_container.new(_("Opening TCL Script...")):
  7901. # Object name
  7902. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7903. # Object creation
  7904. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7905. if ret_val == 'fail':
  7906. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7907. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7908. if ret_val == 'fail':
  7909. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7910. return 'fail'
  7911. # Register recent file
  7912. self.file_opened.emit("script", filename)
  7913. # GUI feedback
  7914. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7915. def open_config_file(self, filename, run_from_arg=None):
  7916. """
  7917. Loads a config file from the specified file.
  7918. :param filename: Name of the file from which to load.
  7919. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7920. :return: None
  7921. """
  7922. App.log.debug("Opening config file: " + filename)
  7923. if run_from_arg:
  7924. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7925. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7926. _("Opening FlatCAM Config file.")),
  7927. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7928. color=QtGui.QColor("gray"))
  7929. # # add the tab if it was closed
  7930. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7931. # # first clear previous text in text editor (if any)
  7932. # self.ui.text_editor_tab.code_editor.clear()
  7933. #
  7934. # # Switch plot_area to CNCJob tab
  7935. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7936. # close the Code editor if already open
  7937. if self.toggle_codeeditor:
  7938. self.on_toggle_code_editor()
  7939. self.on_toggle_code_editor()
  7940. try:
  7941. if filename:
  7942. f = QtCore.QFile(filename)
  7943. if f.open(QtCore.QIODevice.ReadOnly):
  7944. stream = QtCore.QTextStream(f)
  7945. code_edited = stream.readAll()
  7946. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7947. f.close()
  7948. except IOError:
  7949. App.log.error("Failed to open config file: %s" % filename)
  7950. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7951. (_("Failed to open config file"), filename))
  7952. return
  7953. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7954. """
  7955. Loads a project from the specified file.
  7956. 1) Loads and parses file
  7957. 2) Registers the file as recently opened.
  7958. 3) Calls on_file_new()
  7959. 4) Updates options
  7960. 5) Calls new_object() with the object's from_dict() as init method.
  7961. 6) Calls plot_all() if plot=True
  7962. :param filename: Name of the file from which to load.
  7963. :param run_from_arg: True if run for arguments
  7964. :param plot: If True plot all objects in the project
  7965. :param cli: Run from command line
  7966. :param from_tcl: True if run from Tcl Sehll
  7967. :return: None
  7968. """
  7969. App.log.debug("Opening project: " + filename)
  7970. # block autosaving while a project is loaded
  7971. self.block_autosave = True
  7972. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7973. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7974. if cli is None:
  7975. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7976. if run_from_arg:
  7977. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7978. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7979. _("Opening FlatCAM Project file.")),
  7980. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7981. color=QtGui.QColor("gray"))
  7982. # Open and parse an uncompressed Project file
  7983. try:
  7984. f = open(filename, 'r')
  7985. except IOError:
  7986. if from_tcl:
  7987. name = filename.split('/')[-1].split('\\')[-1]
  7988. filename = self.defaults['global_tcl_path'] + '/' + name
  7989. try:
  7990. f = open(filename, 'r')
  7991. except IOError:
  7992. log.error("Failed to open project file: %s" % filename)
  7993. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7994. return
  7995. else:
  7996. log.error("Failed to open project file: %s" % filename)
  7997. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7998. return
  7999. try:
  8000. d = json.load(f, object_hook=dict2obj)
  8001. except Exception as e:
  8002. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8003. (filename, str(e)))
  8004. f.close()
  8005. # Open and parse a compressed Project file
  8006. try:
  8007. with lzma.open(filename) as f:
  8008. file_content = f.read().decode('utf-8')
  8009. d = json.loads(file_content, object_hook=dict2obj)
  8010. except Exception as e:
  8011. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8012. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8013. return
  8014. # Clear the current project
  8015. # # NOT THREAD SAFE # ##
  8016. if run_from_arg is True:
  8017. pass
  8018. elif cli is True:
  8019. self.delete_selection_shape()
  8020. else:
  8021. self.on_file_new()
  8022. # Project options
  8023. self.options.update(d['options'])
  8024. self.project_filename = filename
  8025. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8026. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8027. if cli is None:
  8028. self.set_screen_units(self.options["units"])
  8029. # Re create objects
  8030. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8031. for obj in d['objs']:
  8032. try:
  8033. def obj_init(obj_inst, app_inst):
  8034. obj_inst.from_dict(obj)
  8035. App.log.debug("Recreating from opened project an %s object: %s" %
  8036. (obj['kind'].capitalize(), obj['options']['name']))
  8037. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8038. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8039. if cli is None:
  8040. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8041. obj['kind'].upper(),
  8042. obj['options']['name']
  8043. )
  8044. )
  8045. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8046. except Exception as e:
  8047. print('App.open_project() --> ' + str(e))
  8048. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8049. self.should_we_save = False
  8050. self.file_opened.emit("project", filename)
  8051. # restore autosaving after a project was loaded
  8052. self.block_autosave = False
  8053. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8054. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8055. if cli is None:
  8056. self.set_ui_title(name=self.project_filename)
  8057. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8058. def plot_all(self, fit_view=True, use_thread=True):
  8059. """
  8060. Re-generates all plots from all objects.
  8061. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8062. :param use_thread: if True will use threading for plotting the objects
  8063. :return: None
  8064. """
  8065. self.log.debug("Plot_all()")
  8066. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8067. for plot_obj in self.collection.get_list():
  8068. def worker_task(obj):
  8069. with self.proc_container.new("Plotting"):
  8070. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8071. if fit_view is True:
  8072. self.object_plotted.emit(obj)
  8073. if use_thread is True:
  8074. # Send to worker
  8075. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8076. else:
  8077. worker_task(plot_obj)
  8078. def register_folder(self, filename):
  8079. """
  8080. Register the last folder used by the app to open something
  8081. :param filename: the last folder is extracted from the filename
  8082. :return: None
  8083. """
  8084. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8085. def register_save_folder(self, filename):
  8086. """
  8087. Register the last folder used by the app to save something
  8088. :param filename: the last folder is extracted from the filename
  8089. :return: None
  8090. """
  8091. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8092. # def set_progress_bar(self, percentage, text=""):
  8093. # """
  8094. # Set a progress bar to a value (percentage)
  8095. #
  8096. # :param percentage: Value set to the progressbar
  8097. # :param text: Not used
  8098. # :return: None
  8099. # """
  8100. # self.ui.progress_bar.setValue(int(percentage))
  8101. def setup_recent_items(self):
  8102. """
  8103. Setup a dictionary with the recent files accessed, organized by type
  8104. :return:
  8105. """
  8106. icons = {
  8107. "gerber": self.resource_location + "/flatcam_icon16.png",
  8108. "excellon": self.resource_location + "/drill16.png",
  8109. 'geometry': self.resource_location + "/geometry16.png",
  8110. "cncjob": self.resource_location + "/cnc16.png",
  8111. "script": self.resource_location + "/script_new24.png",
  8112. "document": self.resource_location + "/notes16_1.png",
  8113. "project": self.resource_location + "/project16.png",
  8114. "svg": self.resource_location + "/geometry16.png",
  8115. "dxf": self.resource_location + "/dxf16.png",
  8116. "pdf": self.resource_location + "/pdf32.png",
  8117. "image": self.resource_location + "/image16.png"
  8118. }
  8119. try:
  8120. image_opener = self.image_tool.import_image
  8121. except AttributeError:
  8122. image_opener = None
  8123. openers = {
  8124. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8125. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8126. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8127. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8128. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8129. "document": None,
  8130. 'project': self.open_project,
  8131. 'svg': self.import_svg,
  8132. 'dxf': self.import_dxf,
  8133. 'image': image_opener,
  8134. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8135. }
  8136. # Open recent file for files
  8137. try:
  8138. f = open(self.data_path + '/recent.json')
  8139. except IOError:
  8140. App.log.error("Failed to load recent item list.")
  8141. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8142. return
  8143. try:
  8144. self.recent = json.load(f)
  8145. except json.errors.JSONDecodeError:
  8146. App.log.error("Failed to parse recent item list.")
  8147. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8148. f.close()
  8149. return
  8150. f.close()
  8151. # Open recent file for projects
  8152. try:
  8153. fp = open(self.data_path + '/recent_projects.json')
  8154. except IOError:
  8155. App.log.error("Failed to load recent project item list.")
  8156. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8157. return
  8158. try:
  8159. self.recent_projects = json.load(fp)
  8160. except json.errors.JSONDecodeError:
  8161. App.log.error("Failed to parse recent project item list.")
  8162. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8163. fp.close()
  8164. return
  8165. fp.close()
  8166. # Closure needed to create callbacks in a loop.
  8167. # Otherwise late binding occurs.
  8168. def make_callback(func, fname):
  8169. def opener():
  8170. func(fname)
  8171. return opener
  8172. def reset_recent_files():
  8173. # Reset menu
  8174. self.ui.recent.clear()
  8175. self.recent = []
  8176. try:
  8177. ff = open(self.data_path + '/recent.json', 'w')
  8178. except IOError:
  8179. App.log.error("Failed to open recent items file for writing.")
  8180. return
  8181. json.dump(self.recent, ff)
  8182. def reset_recent_projects():
  8183. # Reset menu
  8184. self.ui.recent_projects.clear()
  8185. self.recent_projects = []
  8186. try:
  8187. frp = open(self.data_path + '/recent_projects.json', 'w')
  8188. except IOError:
  8189. App.log.error("Failed to open recent projects items file for writing.")
  8190. return
  8191. json.dump(self.recent, frp)
  8192. # Reset menu
  8193. self.ui.recent.clear()
  8194. self.ui.recent_projects.clear()
  8195. # Create menu items for projects
  8196. for recent in self.recent_projects:
  8197. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8198. if recent['kind'] == 'project':
  8199. try:
  8200. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8201. # Attach callback
  8202. o = make_callback(openers[recent["kind"]], recent['filename'])
  8203. action.triggered.connect(o)
  8204. self.ui.recent_projects.addAction(action)
  8205. except KeyError:
  8206. App.log.error("Unsupported file type: %s" % recent["kind"])
  8207. # Last action in Recent Files menu is one that Clear the content
  8208. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8209. (_("Clear Recent projects")), self)
  8210. clear_action_proj.triggered.connect(reset_recent_projects)
  8211. self.ui.recent_projects.addSeparator()
  8212. self.ui.recent_projects.addAction(clear_action_proj)
  8213. # Create menu items for files
  8214. for recent in self.recent:
  8215. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8216. if recent['kind'] != 'project':
  8217. try:
  8218. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8219. # Attach callback
  8220. o = make_callback(openers[recent["kind"]], recent['filename'])
  8221. action.triggered.connect(o)
  8222. self.ui.recent.addAction(action)
  8223. except KeyError:
  8224. App.log.error("Unsupported file type: %s" % recent["kind"])
  8225. # Last action in Recent Files menu is one that Clear the content
  8226. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8227. (_("Clear Recent files")), self)
  8228. clear_action.triggered.connect(reset_recent_files)
  8229. self.ui.recent.addSeparator()
  8230. self.ui.recent.addAction(clear_action)
  8231. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8232. # self.ui.menufilerecent.set_submenu(recent_menu)
  8233. # recent_menu.show_all()
  8234. # self.ui.recent.show()
  8235. self.log.debug("Recent items list has been populated.")
  8236. def setup_component_editor(self):
  8237. """
  8238. Default text for the Selected tab when is not taken by the Object UI.
  8239. :return:
  8240. """
  8241. # label = QtWidgets.QLabel("Choose an item from Project")
  8242. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8243. sel_title = QtWidgets.QTextEdit(
  8244. _('<b>Shortcut Key List</b>'))
  8245. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8246. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8247. f_settings = QSettings("Open Source", "FlatCAM")
  8248. if f_settings.contains("notebook_font_size"):
  8249. fsize = f_settings.value('notebook_font_size', type=int)
  8250. else:
  8251. fsize = 12
  8252. tsize = fsize + int(fsize / 2)
  8253. # selected_text = (_('''
  8254. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8255. # </p>
  8256. #
  8257. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8258. # The normal flow when working in FlatCAM is the following:</span></p>
  8259. #
  8260. # <ol>
  8261. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8262. # file into
  8263. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8264. # even dragging and dropping the files on the GUI.<br />
  8265. # <br />
  8266. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8267. # drop of the
  8268. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8269. # &nbsp;</li>
  8270. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8271. # and then
  8272. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8273. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8274. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8275. # <br />
  8276. # If the selection of the object is done on the canvas by single click instead, and the
  8277. # <strong>SELECTED TAB</strong>
  8278. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8279. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8280. # it even if it was out of focus.<br />
  8281. # <br />
  8282. # You can change the parameters in this screen and the flow direction is like this:<br />
  8283. # <br />
  8284. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8285. # <strong> Geometry Object
  8286. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8287. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8288. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8289. # </ol>
  8290. #
  8291. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8292. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8293. # <strong>F3</strong>.</span></p>
  8294. #
  8295. # ''').format(fsize=fsize, tsize=tsize))
  8296. selected_text = '''
  8297. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8298. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8299. {s1}</span></p>
  8300. <ol>
  8301. <li><span style="font-size:{fsize}px">{s2}<br />
  8302. <br />
  8303. {s3}</span><br />
  8304. &nbsp;</li>
  8305. <li><span style="font-size:{fsize}px">{s4}<br />
  8306. &nbsp;</li>
  8307. <br />
  8308. <li><span style="font-size:{fsize}px">{s5}<br />
  8309. &nbsp;</li>
  8310. <br />
  8311. <li><span style="font-size:{fsize}px">{s6}<br />
  8312. <br />
  8313. {s7}</span></li>
  8314. </ol>
  8315. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8316. '''.format(
  8317. title=_("Selected Tab - Choose an Item from Project Tab"),
  8318. subtitle=_("Details"),
  8319. s1=_("The normal flow when working in FlatCAM is the following:"),
  8320. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8321. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8322. "files on the GUI."),
  8323. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8324. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8325. "actions offered within the app."),
  8326. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8327. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8328. "SELECTED TAB will be updated with the object properties according to its kind: "
  8329. "Gerber, Excellon, Geometry or CNCJob object."),
  8330. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8331. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8332. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8333. "the SELECTED TAB and populate it even if it was out of focus."),
  8334. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8335. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8336. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8337. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8338. "(again, done in SELECTED TAB) --> Save GCode."),
  8339. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8340. "or through its own key shortcut: <b>F3</b>."),
  8341. tsize=tsize,
  8342. fsize=fsize
  8343. )
  8344. sel_title.setText(selected_text)
  8345. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8346. self.ui.selected_scroll_area.setWidget(sel_title)
  8347. def setup_obj_classes(self):
  8348. """
  8349. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8350. class.
  8351. :return: None
  8352. """
  8353. FlatCAMObj.app = self
  8354. ObjectCollection.app = self
  8355. Gerber.app = self
  8356. Excellon.app = self
  8357. Geometry.app = self
  8358. CNCjob.app = self
  8359. FCProcess.app = self
  8360. FCProcessContainer.app = self
  8361. OptionsGroupUI.app = self
  8362. def version_check(self):
  8363. """
  8364. Checks for the latest version of the program. Alerts the
  8365. user if theirs is outdated. This method is meant to be run
  8366. in a separate thread.
  8367. :return: None
  8368. """
  8369. self.log.debug("version_check()")
  8370. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8371. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8372. App.version_url,
  8373. str(self.defaults['global_serial']),
  8374. str(self.version),
  8375. str(self.os),
  8376. urllib.parse.urlencode(self.defaults["global_stats"])
  8377. )
  8378. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8379. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8380. # urllib.parse.urlencode(self.defaults["global_stats"])
  8381. else:
  8382. # no_stats dict; just so it won't break things on website
  8383. no_ststs_dict = {}
  8384. no_ststs_dict["global_ststs"] = {}
  8385. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8386. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8387. App.log.debug("Checking for updates @ %s" % full_url)
  8388. # ## Get the data
  8389. try:
  8390. f = urllib.request.urlopen(full_url)
  8391. except Exception:
  8392. # App.log.warning("Failed checking for latest version. Could not connect.")
  8393. self.log.warning("Failed checking for latest version. Could not connect.")
  8394. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8395. return
  8396. try:
  8397. data = json.load(f)
  8398. except Exception as e:
  8399. App.log.error("Could not parse information about latest version.")
  8400. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8401. App.log.debug("json.load(): %s" % str(e))
  8402. f.close()
  8403. return
  8404. f.close()
  8405. # ## Latest version?
  8406. if self.version >= data["version"]:
  8407. App.log.debug("FlatCAM is up to date!")
  8408. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8409. return
  8410. App.log.debug("Newer version available.")
  8411. self.message.emit(
  8412. _("Newer Version Available"),
  8413. '%s<br><br>><b>%s</b><br>%s' % (
  8414. _("There is a newer version of FlatCAM available for download:"),
  8415. str(data["name"]),
  8416. str(data["message"])
  8417. ),
  8418. _("info")
  8419. )
  8420. def on_plotcanvas_setup(self, container=None):
  8421. """
  8422. This is doing the setup for the plot area (canvas).
  8423. :param container: QT Widget where to install the canvas
  8424. :return: None
  8425. """
  8426. if container:
  8427. plot_container = container
  8428. else:
  8429. plot_container = self.ui.right_layout
  8430. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8431. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8432. self.is_legacy = True
  8433. self.defaults["global_graphic_engine"] = "2D"
  8434. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8435. else:
  8436. try:
  8437. self.plotcanvas = PlotCanvas(plot_container, self)
  8438. except Exception as er:
  8439. msg_txt = traceback.format_exc()
  8440. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8441. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8442. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8443. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8444. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8445. msg += msg_txt
  8446. self.inform.emit(msg)
  8447. return 'fail'
  8448. # So it can receive key presses
  8449. self.plotcanvas.native.setFocus()
  8450. if self.is_legacy is False:
  8451. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8452. # Set the mouse button for panning
  8453. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8454. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8455. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8456. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8457. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8458. # Keys over plot enabled
  8459. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8460. if self.defaults['global_cursor_type'] == 'small':
  8461. self.app_cursor = self.plotcanvas.new_cursor()
  8462. else:
  8463. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8464. if self.ui.grid_snap_btn.isChecked():
  8465. self.app_cursor.enabled = True
  8466. else:
  8467. self.app_cursor.enabled = False
  8468. if self.is_legacy is False:
  8469. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8470. else:
  8471. # will use the default Matplotlib axes
  8472. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8473. def on_zoom_fit(self, event):
  8474. """
  8475. Callback for zoom-fit request. This can be either from the corresponding
  8476. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8477. with axes limits from the geometry bounds of all objects.
  8478. :param event: Ignored.
  8479. :return: None
  8480. """
  8481. if self.is_legacy is False:
  8482. self.plotcanvas.fit_view()
  8483. else:
  8484. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8485. width = xmax - xmin
  8486. height = ymax - ymin
  8487. xmin -= 0.05 * width
  8488. xmax += 0.05 * width
  8489. ymin -= 0.05 * height
  8490. ymax += 0.05 * height
  8491. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8492. def on_zoom_in(self):
  8493. """
  8494. Callback for zoom-in request.
  8495. :return:
  8496. """
  8497. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8498. def on_zoom_out(self):
  8499. """
  8500. Callback for zoom-out request.
  8501. :return:
  8502. """
  8503. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8504. def disable_all_plots(self):
  8505. self.defaults.report_usage("disable_all_plots()")
  8506. self.disable_plots(self.collection.get_list())
  8507. self.inform.emit('[success] %s' %
  8508. _("All plots disabled."))
  8509. def disable_other_plots(self):
  8510. self.defaults.report_usage("disable_other_plots()")
  8511. self.disable_plots(self.collection.get_non_selected())
  8512. self.inform.emit('[success] %s' %
  8513. _("All non selected plots disabled."))
  8514. def enable_all_plots(self):
  8515. self.defaults.report_usage("enable_all_plots()")
  8516. self.enable_plots(self.collection.get_list())
  8517. self.inform.emit('[success] %s' %
  8518. _("All plots enabled."))
  8519. def on_enable_sel_plots(self):
  8520. log.debug("App.on_enable_sel_plot()")
  8521. object_list = self.collection.get_selected()
  8522. self.enable_plots(objects=object_list)
  8523. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8524. def on_disable_sel_plots(self):
  8525. log.debug("App.on_disable_sel_plot()")
  8526. # self.inform.emit(_("Disabling plots ..."))
  8527. object_list = self.collection.get_selected()
  8528. self.disable_plots(objects=object_list)
  8529. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8530. def enable_plots(self, objects):
  8531. """
  8532. Enable plots
  8533. :param objects: list of Objects to be enabled
  8534. :return:
  8535. """
  8536. log.debug("Enabling plots ...")
  8537. # self.inform.emit(_("Working ..."))
  8538. for obj in objects:
  8539. if obj.options['plot'] is False:
  8540. obj.options.set_change_callback(lambda x: None)
  8541. obj.options['plot'] = True
  8542. try:
  8543. # only the Gerber obj has on_plot_cb_click() method
  8544. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8545. # disable this cb while disconnected,
  8546. # in case the operation takes time the user is not allowed to change it
  8547. obj.ui.plot_cb.setDisabled(True)
  8548. except AttributeError:
  8549. pass
  8550. obj.set_form_item("plot")
  8551. try:
  8552. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8553. obj.ui.plot_cb.setDisabled(False)
  8554. except AttributeError:
  8555. pass
  8556. obj.options.set_change_callback(obj.on_options_change)
  8557. def worker_task(objs):
  8558. with self.proc_container.new(_("Enabling plots ...")):
  8559. for plot_obj in objs:
  8560. # obj.options['plot'] = True
  8561. if isinstance(plot_obj, CNCJobObject):
  8562. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8563. else:
  8564. plot_obj.plot(visible=True)
  8565. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8566. # self.plots_updated.emit()
  8567. def disable_plots(self, objects):
  8568. """
  8569. Disables plots
  8570. :param objects: list of Objects to be disabled
  8571. :return:
  8572. """
  8573. # if no objects selected then do nothing
  8574. if not self.collection.get_selected():
  8575. return
  8576. log.debug("Disabling plots ...")
  8577. # self.inform.emit(_("Working ..."))
  8578. for obj in objects:
  8579. if obj.options['plot'] is True:
  8580. obj.options.set_change_callback(lambda x: None)
  8581. obj.options['plot'] = False
  8582. try:
  8583. # only the Gerber obj has on_plot_cb_click() method
  8584. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8585. obj.ui.plot_cb.setDisabled(True)
  8586. except AttributeError:
  8587. pass
  8588. obj.set_form_item("plot")
  8589. try:
  8590. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8591. obj.ui.plot_cb.setDisabled(False)
  8592. except AttributeError:
  8593. pass
  8594. obj.options.set_change_callback(obj.on_options_change)
  8595. try:
  8596. self.delete_selection_shape()
  8597. except Exception as e:
  8598. log.debug("App.disable_plots() --> %s" % str(e))
  8599. # self.plots_updated.emit()
  8600. def worker_task(objs):
  8601. with self.proc_container.new(_("Disabling plots ...")):
  8602. for plot_obj in objs:
  8603. # obj.options['plot'] = True
  8604. if isinstance(plot_obj, CNCJobObject):
  8605. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8606. else:
  8607. plot_obj.plot(visible=False)
  8608. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8609. def toggle_plots(self, objects):
  8610. """
  8611. Toggle plots visibility
  8612. :param objects: list of Objects for which to be toggled the visibility
  8613. :return: None
  8614. """
  8615. # if no objects selected then do nothing
  8616. if not self.collection.get_selected():
  8617. return
  8618. log.debug("Toggling plots ...")
  8619. self.inform.emit(_("Working ..."))
  8620. for obj in objects:
  8621. if obj.options['plot'] is False:
  8622. obj.options['plot'] = True
  8623. else:
  8624. obj.options['plot'] = False
  8625. self.plots_updated.emit()
  8626. def clear_plots(self):
  8627. """
  8628. Clear the plots
  8629. :return: None
  8630. """
  8631. objects = self.collection.get_list()
  8632. for obj in objects:
  8633. obj.clear(obj == objects[-1])
  8634. # Clear pool to free memory
  8635. self.clear_pool()
  8636. def on_set_color_action_triggered(self):
  8637. """
  8638. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8639. :return:
  8640. """
  8641. new_color = self.defaults['gerber_plot_fill']
  8642. clicked_action = self.sender()
  8643. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8644. act_name = clicked_action.text()
  8645. sel_obj_list = self.collection.get_selected()
  8646. if not sel_obj_list:
  8647. return
  8648. # a default value, I just chose this one
  8649. alpha_level = 'BF'
  8650. for sel_obj in sel_obj_list:
  8651. if sel_obj.kind == 'excellon':
  8652. alpha_level = str(hex(
  8653. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8654. elif sel_obj.kind == 'gerber':
  8655. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8656. elif sel_obj.kind == 'geometry':
  8657. alpha_level = 'FF'
  8658. else:
  8659. log.debug(
  8660. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8661. continue
  8662. sel_obj.alpha_level = alpha_level
  8663. if act_name == _('Red'):
  8664. new_color = '#FF0000' + alpha_level
  8665. if act_name == _('Blue'):
  8666. new_color = '#0000FF' + alpha_level
  8667. if act_name == _('Yellow'):
  8668. new_color = '#FFDF00' + alpha_level
  8669. if act_name == _('Green'):
  8670. new_color = '#00FF00' + alpha_level
  8671. if act_name == _('Purple'):
  8672. new_color = '#FF00FF' + alpha_level
  8673. if act_name == _('Brown'):
  8674. new_color = '#A52A2A' + alpha_level
  8675. if act_name == _('White'):
  8676. new_color = '#FFFFFF' + alpha_level
  8677. if act_name == _('Black'):
  8678. new_color = '#000000' + alpha_level
  8679. if act_name == _('Custom'):
  8680. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8681. c_dialog = QtWidgets.QColorDialog()
  8682. plot_fill_color = c_dialog.getColor(initial=new_color)
  8683. if plot_fill_color.isValid() is False:
  8684. return
  8685. new_color = str(plot_fill_color.name()) + alpha_level
  8686. if act_name == _("Default"):
  8687. for sel_obj in sel_obj_list:
  8688. if sel_obj.kind == 'excellon':
  8689. new_color = self.defaults['excellon_plot_fill']
  8690. new_line_color = self.defaults['excellon_plot_line']
  8691. elif sel_obj.kind == 'gerber':
  8692. new_color = self.defaults['gerber_plot_fill']
  8693. new_line_color = self.defaults['gerber_plot_line']
  8694. elif sel_obj.kind == 'geometry':
  8695. new_color = self.defaults['geometry_plot_line']
  8696. new_line_color = self.defaults['geometry_plot_line']
  8697. else:
  8698. log.debug(
  8699. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8700. continue
  8701. sel_obj.fill_color = new_color
  8702. sel_obj.outline_color = new_line_color
  8703. sel_obj.shapes.redraw(
  8704. update_colors=(new_color, new_line_color)
  8705. )
  8706. return
  8707. if act_name == _("Opacity"):
  8708. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8709. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8710. if ok_button:
  8711. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8712. for sel_obj in sel_obj_list:
  8713. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8714. sel_obj.shapes.redraw(
  8715. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8716. )
  8717. return
  8718. new_line_color = color_variant(new_color[:7], 0.7)
  8719. if act_name == _("White"):
  8720. new_line_color = color_variant("#dedede", 0.7)
  8721. for sel_obj in sel_obj_list:
  8722. sel_obj.fill_color = new_color
  8723. sel_obj.outline_color = new_line_color
  8724. sel_obj.shapes.redraw(
  8725. update_colors=(new_color, new_line_color)
  8726. )
  8727. def generate_cnc_job(self, objects):
  8728. """
  8729. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8730. :param objects: Selected objects in the Project Tab
  8731. :return:
  8732. """
  8733. self.defaults.report_usage("generate_cnc_job()")
  8734. # for obj in objects:
  8735. # obj.generatecncjob()
  8736. for obj in objects:
  8737. obj.on_generatecnc_button_click()
  8738. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8739. """
  8740. Saves the current project to the specified file.
  8741. :param filename: Name of the file in which to save.
  8742. :type filename: str
  8743. :param quit_action: if the project saving will be followed by an app quit; boolean
  8744. :param silent: if True will not display status messages
  8745. :param from_tcl True is run from Tcl Shell
  8746. :return: None
  8747. """
  8748. self.log.debug("save_project()")
  8749. self.save_in_progress = True
  8750. with self.proc_container.new(_("Saving FlatCAM Project")):
  8751. # Capture the latest changes
  8752. # Current object
  8753. try:
  8754. current_object = self.collection.get_active()
  8755. if current_object:
  8756. current_object.read_form()
  8757. except Exception as e:
  8758. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8759. pass
  8760. # Serialize the whole project
  8761. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8762. "options": self.options,
  8763. "version": self.version}
  8764. if self.defaults["global_save_compressed"] is True:
  8765. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8766. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8767. # # Write
  8768. f.write(g)
  8769. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8770. else:
  8771. # Open file
  8772. try:
  8773. f = open(filename, 'w')
  8774. except IOError:
  8775. App.log.error("Failed to open file for saving: %s", filename)
  8776. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8777. return
  8778. # Write
  8779. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8780. f.close()
  8781. # verification of the saved project
  8782. # Open and parse
  8783. try:
  8784. saved_f = open(filename, 'r')
  8785. except IOError:
  8786. if silent is False:
  8787. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8788. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8789. return
  8790. try:
  8791. saved_d = json.load(saved_f, object_hook=dict2obj)
  8792. except Exception:
  8793. if silent is False:
  8794. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8795. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8796. f.close()
  8797. return
  8798. saved_f.close()
  8799. if silent is False:
  8800. if 'version' in saved_d:
  8801. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8802. else:
  8803. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8804. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8805. tb_settings = QSettings("Open Source", "FlatCAM")
  8806. lock_state = self.ui.lock_action.isChecked()
  8807. tb_settings.setValue('toolbar_lock', lock_state)
  8808. # This will write the setting to the platform specific storage.
  8809. del tb_settings
  8810. # if quit:
  8811. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8812. # t.start()
  8813. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8814. def start_delayed_quit(self, delay, filename, should_quit=None):
  8815. """
  8816. :param delay: period of checking if project file size is more than zero; in seconds
  8817. :param filename: the name of the project file to be checked periodically for size more than zero
  8818. :param should_quit: if the task finished will be followed by an app quit; boolean
  8819. :return:
  8820. """
  8821. to_quit = should_quit
  8822. self.save_timer = QtCore.QTimer()
  8823. self.save_timer.setInterval(delay)
  8824. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8825. self.save_timer.start()
  8826. def check_project_file_size(self, filename, should_quit=None):
  8827. """
  8828. :param filename: the name of the project file to be checked periodically for size more than zero
  8829. :param should_quit: will quit the app if True; boolean
  8830. :return:
  8831. """
  8832. try:
  8833. if os.stat(filename).st_size > 0:
  8834. self.save_in_progress = False
  8835. self.save_timer.stop()
  8836. if should_quit:
  8837. self.app_quit.emit()
  8838. except Exception:
  8839. traceback.print_exc()
  8840. def save_project_auto(self):
  8841. """
  8842. Called periodically to save the project.
  8843. 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
  8844. # progress.
  8845. :return:
  8846. """
  8847. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8848. self.on_file_saveproject()
  8849. def save_project_auto_update(self):
  8850. """
  8851. Update the auto save time interval value.
  8852. :return:
  8853. """
  8854. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8855. try:
  8856. if self.autosave_timer.isActive():
  8857. self.autosave_timer.stop()
  8858. except Exception:
  8859. pass
  8860. if self.defaults['global_autosave'] is True:
  8861. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8862. self.autosave_timer.start()
  8863. def on_options_app2project(self):
  8864. """
  8865. Callback for Options->Transfer Options->App=>Project. Copies options
  8866. from application defaults to project defaults.
  8867. :return: None
  8868. """
  8869. self.defaults.report_usage("on_options_app2project")
  8870. self.preferencesUiManager.defaults_read_form()
  8871. self.options.update(self.defaults)
  8872. def toggle_shell(self):
  8873. """
  8874. Toggle shell: if is visible close it, if it is closed then open it
  8875. :return: None
  8876. """
  8877. self.defaults.report_usage("toggle_shell()")
  8878. if self.ui.shell_dock.isVisible():
  8879. self.ui.shell_dock.hide()
  8880. self.plotcanvas.native.setFocus()
  8881. else:
  8882. self.ui.shell_dock.show()
  8883. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8884. # self.shell._edit.setFocus()
  8885. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8886. # HACK - simulate a mouse click - alternative
  8887. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8888. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8889. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8890. # no_km)
  8891. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8892. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8893. # no_km)
  8894. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8895. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8896. """
  8897. Shows a message on the FlatCAM Shell
  8898. :param msg: Message to display.
  8899. :param show: Opens the shell.
  8900. :param error: Shows the message as an error.
  8901. :param warning: Shows the message as an warning.
  8902. :param success: Shows the message as an success.
  8903. :param selected: Indicate that something was selected on canvas
  8904. :return: None
  8905. """
  8906. if show:
  8907. self.ui.shell_dock.show()
  8908. try:
  8909. if error:
  8910. self.shell.append_error(msg + "\n")
  8911. elif warning:
  8912. self.shell.append_warning(msg + "\n")
  8913. elif success:
  8914. self.shell.append_success(msg + "\n")
  8915. elif selected:
  8916. self.shell.append_selected(msg + "\n")
  8917. else:
  8918. self.shell.append_output(msg + "\n")
  8919. except AttributeError:
  8920. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8921. class ArgsThread(QtCore.QObject):
  8922. open_signal = pyqtSignal(list)
  8923. start = pyqtSignal()
  8924. stop = pyqtSignal()
  8925. if sys.platform == 'win32':
  8926. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8927. else:
  8928. address = ('/tmp/testipc', 'AF_UNIX')
  8929. def __init__(self):
  8930. super(ArgsThread, self).__init__()
  8931. self.listener = None
  8932. self.thread_exit = False
  8933. self.start.connect(self.run)
  8934. self.stop.connect(self.close_listener)
  8935. def my_loop(self, address):
  8936. try:
  8937. self.listener = Listener(*address)
  8938. while self.thread_exit is False:
  8939. conn = self.listener.accept()
  8940. self.serve(conn)
  8941. except socket.error:
  8942. try:
  8943. conn = Client(*address)
  8944. conn.send(sys.argv)
  8945. conn.send('close')
  8946. # close the current instance only if there are args
  8947. if len(sys.argv) > 1:
  8948. try:
  8949. self.listener.close()
  8950. except Exception:
  8951. pass
  8952. sys.exit()
  8953. except ConnectionRefusedError:
  8954. if sys.platform == 'win32':
  8955. pass
  8956. else:
  8957. os.system('rm /tmp/testipc')
  8958. self.listener = Listener(*address)
  8959. while True:
  8960. conn = self.listener.accept()
  8961. self.serve(conn)
  8962. def serve(self, conn):
  8963. while self.thread_exit is False:
  8964. msg = conn.recv()
  8965. if msg == 'close':
  8966. break
  8967. self.open_signal.emit(msg)
  8968. conn.close()
  8969. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8970. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8971. @pyqtSlot()
  8972. def run(self):
  8973. self.my_loop(self.address)
  8974. @pyqtSlot()
  8975. def close_listener(self):
  8976. self.thread_exit = True
  8977. self.listener.close()
  8978. # end of file