FlatCAMApp.py 486 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936
  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 shapely.geometry import Point, MultiPolygon
  21. from io import StringIO
  22. from reportlab.graphics import renderPDF
  23. from reportlab.pdfgen import canvas
  24. from reportlab.lib.units import inch, mm
  25. from reportlab.lib.pagesizes import landscape, portrait
  26. from svglib.svglib import svg2rlg
  27. import gc
  28. from xml.dom.minidom import parseString as parse_xml_string
  29. from multiprocessing.connection import Listener, Client
  30. from multiprocessing import Pool
  31. import socket
  32. # ####################################################################################################################
  33. # ################################### Imports part of FlatCAM #############################################
  34. # ####################################################################################################################
  35. # Diverse
  36. from FlatCAMCommon import LoudDict, color_variant
  37. from FlatCAMBookmark import BookmarkManager
  38. from FlatCAMDB import ToolsDB2
  39. from vispy.gloo.util import _screenshot
  40. from vispy.io import write_png
  41. # FlatCAM Objects
  42. from defaults import FlatCAMDefaults
  43. from flatcamObjects.ObjectCollection import *
  44. from flatcamObjects.FlatCAMObj import FlatCAMObj
  45. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  46. from flatcamObjects.FlatCAMDocument import DocumentObject
  47. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  48. from flatcamObjects.FlatCAMGeometry import GeometryObject
  49. from flatcamObjects.FlatCAMGerber import GerberObject
  50. from flatcamObjects.FlatCAMScript import ScriptObject
  51. # FlatCAM Parsing files
  52. from flatcamParsers.ParseExcellon import Excellon
  53. from flatcamParsers.ParseGerber import Gerber
  54. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  55. # FlatCAM GUI
  56. from flatcamGUI.PlotCanvas import *
  57. from flatcamGUI.PlotCanvasLegacy import *
  58. from flatcamGUI.FlatCAMGUI import *
  59. from flatcamGUI.GUIElements import FCFileSaveDialog
  60. # FlatCAM Pre-processors
  61. from FlatCAMPostProc import load_preprocessors
  62. # FlatCAM Editors
  63. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  64. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  65. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  66. from flatcamEditors.FlatCAMTextEditor import TextEditor
  67. from flatcamParsers.ParseHPGL2 import HPGL2
  68. # FlatCAM Workers
  69. from FlatCAMProcess import *
  70. from FlatCAMWorkerStack import WorkerStack
  71. # FlatCAM Tools
  72. from flatcamTools import *
  73. # FlatCAM Translation
  74. import gettext
  75. import FlatCAMTranslation as fcTranslate
  76. import builtins
  77. if sys.platform == 'win32':
  78. import winreg
  79. from win32comext.shell import shell, shellcon
  80. fcTranslate.apply_language('strings')
  81. if '_' not in builtins.__dict__:
  82. _ = gettext.gettext
  83. class App(QtCore.QObject):
  84. """
  85. The main application class. The constructor starts the GUI.
  86. """
  87. # ###############################################################################################################
  88. # ########################################## App ################################################################
  89. # ###############################################################################################################
  90. # ###############################################################################################################
  91. # ######################################### LOGGING #############################################################
  92. # ###############################################################################################################
  93. log = logging.getLogger('base')
  94. log.setLevel(logging.DEBUG)
  95. # log.setLevel(logging.WARNING)
  96. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  97. handler = logging.StreamHandler()
  98. handler.setFormatter(formatter)
  99. log.addHandler(handler)
  100. # ###############################################################################################################
  101. # #################################### Get Cmd Line Options #####################################################
  102. # ###############################################################################################################
  103. cmd_line_shellfile = ''
  104. cmd_line_shellvar = ''
  105. cmd_line_headless = None
  106. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  107. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  108. "FlatCam.py --headless=1"
  109. try:
  110. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  111. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  112. "shellvar=",
  113. "headless=",
  114. "multiprocessing-fork="])
  115. except getopt.GetoptError:
  116. print(cmd_line_help)
  117. sys.exit(2)
  118. for opt, arg in cmd_line_options:
  119. if opt == '-h':
  120. print(cmd_line_help)
  121. sys.exit()
  122. elif opt == '--shellfile':
  123. cmd_line_shellfile = arg
  124. elif opt == '--shellvar':
  125. cmd_line_shellvar = arg
  126. elif opt == '--headless':
  127. try:
  128. cmd_line_headless = eval(arg)
  129. except NameError:
  130. pass
  131. # ###############################################################################################################
  132. # ################################### Version and VERSION DATE ##################################################
  133. # ###############################################################################################################
  134. version = 8.992
  135. version_date = "2020/05/01"
  136. beta = True
  137. engine = '3D'
  138. # current date now
  139. date = str(datetime.today()).rpartition('.')[0]
  140. date = ''.join(c for c in date if c not in ':-')
  141. date = date.replace(' ', '_')
  142. # ###############################################################################################################
  143. # ############################################ URLS's ###########################################################
  144. # ###############################################################################################################
  145. # URL for update checks and statistics
  146. version_url = "http://flatcam.org/version"
  147. # App URL
  148. app_url = "http://flatcam.org"
  149. # Manual URL
  150. manual_url = "http://flatcam.org/manual/index.html"
  151. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  152. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  153. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  154. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  155. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  156. # this variable will hold the project status
  157. # if True it will mean that the project was modified and not saved
  158. should_we_save = False
  159. # flag is True if saving action has been triggered
  160. save_in_progress = False
  161. # ###############################################################################################################
  162. # ####################################### APP Signals ######################################################
  163. # ###############################################################################################################
  164. # Inform the user
  165. # Handled by:
  166. # * App.info() --> Print on the status bar
  167. inform = QtCore.pyqtSignal(str)
  168. app_quit = QtCore.pyqtSignal()
  169. # General purpose background task
  170. worker_task = QtCore.pyqtSignal(dict)
  171. # File opened
  172. # Handled by:
  173. # * register_folder()
  174. # * register_recent()
  175. # Note: Setting the parameters to unicode does not seem
  176. # to have an effect. Then are received as Qstring
  177. # anyway.
  178. # File type and filename
  179. file_opened = QtCore.pyqtSignal(str, str)
  180. # File type and filename
  181. file_saved = QtCore.pyqtSignal(str, str)
  182. # Percentage of progress
  183. progress = QtCore.pyqtSignal(int)
  184. plots_updated = QtCore.pyqtSignal()
  185. # Emitted by new_object() and passes the new object as argument, plot flag.
  186. # on_object_created() adds the object to the collection, plots on appropriate flag
  187. # and emits new_object_available.
  188. object_created = QtCore.pyqtSignal(object, bool, bool)
  189. # Emitted when a object has been changed (like scaled, mirrored)
  190. object_changed = QtCore.pyqtSignal(object)
  191. # Emitted after object has been plotted.
  192. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  193. object_plotted = QtCore.pyqtSignal(object)
  194. # Emitted when a new object has been added or deleted from/to the collection
  195. object_status_changed = QtCore.pyqtSignal(object, str, str)
  196. message = QtCore.pyqtSignal(str, str, str)
  197. # Emmited when shell command is finished(one command only)
  198. shell_command_finished = QtCore.pyqtSignal(object)
  199. # Emitted when multiprocess pool has been recreated
  200. pool_recreated = QtCore.pyqtSignal(object)
  201. # Emitted when an unhandled exception happens
  202. # in the worker task.
  203. thread_exception = QtCore.pyqtSignal(object)
  204. # used to signal that there are arguments for the app
  205. args_at_startup = QtCore.pyqtSignal(list)
  206. # a reusable signal to replot a list of objects
  207. # should be disconnected after use so it can be reused
  208. replot_signal = pyqtSignal(list)
  209. # signal emitted when jumping
  210. jump_signal = pyqtSignal(tuple)
  211. # signal emitted when jumping
  212. locate_signal = pyqtSignal(tuple, str)
  213. # close app signal
  214. close_app_signal = pyqtSignal()
  215. # will perform the cleanup operation after a Graceful Exit
  216. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  217. # graphic residues behind
  218. cleanup = pyqtSignal()
  219. def __init__(self, user_defaults=True):
  220. """
  221. Starts the application.
  222. :return: app
  223. :rtype: App
  224. """
  225. App.log.info("FlatCAM Starting...")
  226. self.main_thread = QtWidgets.QApplication.instance().thread()
  227. # ############################################################################################################
  228. # ################# Setup the listening thread for another instance launching with args ######################
  229. # ############################################################################################################
  230. if sys.platform == 'win32' or sys.platform == 'linux':
  231. # make sure the thread is stored by using a self. otherwise it's garbage collected
  232. self.th = QtCore.QThread()
  233. self.th.start(priority=QtCore.QThread.LowestPriority)
  234. self.new_launch = ArgsThread()
  235. self.new_launch.open_signal[list].connect(self.on_startup_args)
  236. self.new_launch.moveToThread(self.th)
  237. self.new_launch.start.emit()
  238. # ############################################################################################################
  239. # # ######################################## OS-specific #####################################################
  240. # ############################################################################################################
  241. portable = False
  242. # Folder for user settings.
  243. if sys.platform == 'win32':
  244. if platform.architecture()[0] == '32bit':
  245. App.log.debug("Win32!")
  246. else:
  247. App.log.debug("Win64!")
  248. # #######################################################################################################
  249. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  250. # #######################################################################################################
  251. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r'):
  254. pass
  255. except FileNotFoundError:
  256. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  257. try:
  258. with open(config_file, 'r') as f:
  259. try:
  260. for line in f:
  261. param = str(line).replace('\n', '').rpartition('=')
  262. if param[0] == 'portable':
  263. try:
  264. portable = eval(param[2])
  265. except NameError:
  266. portable = False
  267. if param[0] == 'headless':
  268. if param[2].lower() == 'true':
  269. self.cmd_line_headless = 1
  270. else:
  271. self.cmd_line_headless = None
  272. except Exception as e:
  273. log.debug('App.__init__() -->%s' % str(e))
  274. return
  275. except FileNotFoundError as e:
  276. log.debug(str(e))
  277. pass
  278. if portable is False:
  279. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  280. else:
  281. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  282. self.os = 'windows'
  283. else: # Linux/Unix/MacOS
  284. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  285. self.os = 'unix'
  286. # ############################################################################################################
  287. # ################################# Setup folders and files ##################################################
  288. # ############################################################################################################
  289. if not os.path.exists(self.data_path):
  290. os.makedirs(self.data_path)
  291. App.log.debug('Created data folder: ' + self.data_path)
  292. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  293. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  294. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  295. if not os.path.exists(self.preprocessorpaths):
  296. os.makedirs(self.preprocessorpaths)
  297. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  298. # create geo_tools_db.FlatDB file if there is none
  299. try:
  300. f = open(self.data_path + '/geo_tools_db.FlatDB')
  301. f.close()
  302. except IOError:
  303. App.log.debug('Creating empty geo_tool_db.FlatDB')
  304. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  305. json.dump({}, f)
  306. f.close()
  307. # create current_defaults.FlatConfig file if there is none
  308. try:
  309. f = open(self.data_path + '/current_defaults.FlatConfig')
  310. f.close()
  311. except IOError:
  312. App.log.debug('Creating empty current_defaults.FlatConfig')
  313. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  314. json.dump({}, f)
  315. f.close()
  316. # Write factory_defaults.FlatConfig file to disk
  317. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  318. # create a recent files json file if there is none
  319. try:
  320. f = open(self.data_path + '/recent.json')
  321. f.close()
  322. except IOError:
  323. App.log.debug('Creating empty recent.json')
  324. f = open(self.data_path + '/recent.json', 'w')
  325. json.dump([], f)
  326. f.close()
  327. # create a recent projects json file if there is none
  328. try:
  329. fp = open(self.data_path + '/recent_projects.json')
  330. fp.close()
  331. except IOError:
  332. App.log.debug('Creating empty recent_projects.json')
  333. fp = open(self.data_path + '/recent_projects.json', 'w')
  334. json.dump([], fp)
  335. fp.close()
  336. # Application directory. CHDIR to it. Otherwise, trying to load
  337. # GUI icons will fail as their path is relative.
  338. # This will fail under cx_freeze ...
  339. self.app_home = os.path.dirname(os.path.realpath(__file__))
  340. App.log.debug("Application path is " + self.app_home)
  341. App.log.debug("Started in " + os.getcwd())
  342. # cx_freeze workaround
  343. if os.path.isfile(self.app_home):
  344. self.app_home = os.path.dirname(self.app_home)
  345. os.chdir(self.app_home)
  346. # ############################################################################################################
  347. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  348. # ############################################################################################################
  349. self.defaults = FlatCAMDefaults()
  350. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  351. if user_defaults:
  352. self.defaults.load(filename=current_defaults_path)
  353. if self.defaults['units'] == 'MM':
  354. self.decimals = int(self.defaults['decimals_metric'])
  355. else:
  356. self.decimals = int(self.defaults['decimals_inch'])
  357. if self.defaults["global_gray_icons"] is False:
  358. self.resource_location = 'assets/resources'
  359. else:
  360. self.resource_location = 'assets/resources/dark_resources'
  361. self.current_units = self.defaults['units']
  362. # ###########################################################################################################
  363. # #################################### SETUP OBJECT CLASSES #################################################
  364. # ###########################################################################################################
  365. self.setup_obj_classes()
  366. # ###########################################################################################################
  367. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  368. # ###########################################################################################################
  369. self.pool = Pool()
  370. # ###########################################################################################################
  371. # ###################################### Setting the Splash Screen ##########################################
  372. # ###########################################################################################################
  373. splash_settings = QSettings("Open Source", "FlatCAM")
  374. if splash_settings.contains("splash_screen"):
  375. show_splash = splash_settings.value("splash_screen")
  376. else:
  377. splash_settings.setValue('splash_screen', 1)
  378. # This will write the setting to the platform specific storage.
  379. del splash_settings
  380. show_splash = 1
  381. if show_splash and self.cmd_line_headless != 1:
  382. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  383. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  384. # self.splash.setMask(splash_pix.mask())
  385. # move splashscreen to the current monitor
  386. desktop = QtWidgets.QApplication.desktop()
  387. screen = desktop.screenNumber(QtGui.QCursor.pos())
  388. current_screen_center = desktop.availableGeometry(screen).center()
  389. self.splash.move(current_screen_center - self.splash.rect().center())
  390. self.splash.show()
  391. self.splash.showMessage(_("FlatCAM is initializing ..."),
  392. alignment=Qt.AlignBottom | Qt.AlignLeft,
  393. color=QtGui.QColor("gray"))
  394. else:
  395. show_splash = 0
  396. # ###########################################################################################################
  397. # ######################################### Initialize GUI ##################################################
  398. # ###########################################################################################################
  399. # FlatCAM colors used in plotting
  400. self.FC_light_green = '#BBF268BF'
  401. self.FC_dark_green = '#006E20BF'
  402. self.FC_light_blue = '#a5a5ffbf'
  403. self.FC_dark_blue = '#0000ffbf'
  404. QtCore.QObject.__init__(self)
  405. self.ui = FlatCAMGUI(self)
  406. self.on_grid_snap_triggered(state=True)
  407. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  408. if theme_settings.contains("theme"):
  409. theme = theme_settings.value('theme', type=str)
  410. else:
  411. theme = 'white'
  412. if self.defaults["global_cursor_color_enabled"]:
  413. self.cursor_color_3D = self.defaults["global_cursor_color"]
  414. else:
  415. if theme == 'white':
  416. self.cursor_color_3D = 'black'
  417. else:
  418. self.cursor_color_3D = 'gray'
  419. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  420. self.ui.final_save.connect(self.final_save)
  421. # restore the toolbar view
  422. self.restore_toolbar_view()
  423. # restore the GUI geometry
  424. self.restore_main_win_geom()
  425. # set FlatCAM units in the Status bar
  426. self.set_screen_units(self.defaults['units'])
  427. # ###########################################################################################################
  428. # ########################################### AUTOSAVE SETUP ################################################
  429. # ###########################################################################################################
  430. self.block_autosave = False
  431. self.autosave_timer = QtCore.QTimer(self)
  432. self.save_project_auto_update()
  433. self.autosave_timer.timeout.connect(self.save_project_auto)
  434. # ###########################################################################################################
  435. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  436. # ###########################################################################################################
  437. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  438. inform=self.inform)
  439. self.preferencesUiManager.defaults_write_form()
  440. # When the self.defaults dictionary changes will update the Preferences GUI forms
  441. self.defaults.set_change_callback(self.on_defaults_dict_change)
  442. # ###########################################################################################################
  443. # ##################################### FIRST RUN SECTION ###################################################
  444. # ################################ It's done only once after install #####################################
  445. # ###########################################################################################################
  446. if self.defaults["first_run"] is True:
  447. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  448. initial_lay = 'minimal'
  449. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  450. # Set the combobox in Preferences to the current layout
  451. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  452. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  453. # after the first run, this object should be False
  454. self.defaults["first_run"] = False
  455. self.preferencesUiManager.save_defaults(silent=True)
  456. # ###########################################################################################################
  457. # ############################################ Data #########################################################
  458. # ###########################################################################################################
  459. self.recent = []
  460. self.recent_projects = []
  461. self.clipboard = QtWidgets.QApplication.clipboard()
  462. self.project_filename = None
  463. self.toggle_units_ignore = False
  464. # ###########################################################################################################
  465. # #################################### LOAD PREPROCESSORS ###################################################
  466. # ###########################################################################################################
  467. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  468. # the preprocessor file
  469. self.preprocessors = load_preprocessors(self)
  470. # make sure that always the 'default' preprocessor is the first item in the dictionary
  471. if 'default' in self.preprocessors.keys():
  472. new_ppp_dict = {}
  473. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  474. default_pp = self.preprocessors.pop('default')
  475. new_ppp_dict['default'] = default_pp
  476. # then add the rest of the keys
  477. for name, val_class in self.preprocessors.items():
  478. new_ppp_dict[name] = val_class
  479. # and now put back the ordered dict with 'default' key first
  480. self.preprocessors = new_ppp_dict
  481. for name in list(self.preprocessors.keys()):
  482. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  483. if name.partition('_')[0] == 'Paste':
  484. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  485. continue
  486. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  487. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  488. if name == 'hpgl':
  489. continue
  490. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  491. # ###########################################################################################################
  492. # ########################################## LOAD LANGUAGES ################################################
  493. # ###########################################################################################################
  494. self.languages = fcTranslate.load_languages()
  495. for name in sorted(self.languages.values()):
  496. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  497. # ###########################################################################################################
  498. # ####################################### APPLY APP LANGUAGE ################################################
  499. # ###########################################################################################################
  500. ret_val = fcTranslate.apply_language('strings')
  501. if ret_val == "no language":
  502. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  503. log.debug("Could not find the Language files. The App strings are missing.")
  504. else:
  505. # make the current language the current selection on the language combobox
  506. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  507. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  508. # ###########################################################################################################
  509. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  510. # ###########################################################################################################
  511. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  512. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  513. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  514. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  515. self.defaults.propagate_defaults()
  516. # ###########################################################################################################
  517. # ######################################## UPDATE THE OPTIONS ###############################################
  518. # ###########################################################################################################
  519. self.options = LoudDict()
  520. # -----------------------------------------------------------------------------------------------------------
  521. # Update the self.options from the self.defaults
  522. # The self.defaults holds the application defaults while the self.options holds the object defaults
  523. # -----------------------------------------------------------------------------------------------------------
  524. # Copy app defaults to project options
  525. for def_key, def_val in self.defaults.items():
  526. self.options[def_key] = deepcopy(def_val)
  527. self.preferencesUiManager.show_preferences_gui()
  528. # ### End of Data ####
  529. # ###########################################################################################################
  530. # #################################### SETUP OBJECT COLLECTION ##############################################
  531. # ###########################################################################################################
  532. self.collection = ObjectCollection(self)
  533. self.ui.project_tab_layout.addWidget(self.collection.view)
  534. # ### Adjust tabs width ## ##
  535. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  536. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  537. self.collection.view.setMinimumWidth(290)
  538. self.log.debug("Finished creating Object Collection.")
  539. # ###########################################################################################################
  540. # ######################################## SETUP Plot Area ##################################################
  541. # ###########################################################################################################
  542. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  543. if self.defaults["global_graphic_engine"] == '3D':
  544. self.is_legacy = False
  545. else:
  546. self.is_legacy = True
  547. # Event signals disconnect id holders
  548. self.mp = None
  549. self.mm = None
  550. self.mr = None
  551. self.mdc = None
  552. self.mp_zc = None
  553. self.kp = None
  554. # Matplotlib axis
  555. self.axes = None
  556. if show_splash:
  557. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  558. "Canvas initialization started."),
  559. alignment=Qt.AlignBottom | Qt.AlignLeft,
  560. color=QtGui.QColor("gray"))
  561. start_plot_time = time.time() # debug
  562. self.plotcanvas = None
  563. self.app_cursor = None
  564. self.hover_shapes = None
  565. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  566. # setup the PlotCanvas
  567. self.on_plotcanvas_setup()
  568. end_plot_time = time.time()
  569. self.used_time = end_plot_time - start_plot_time
  570. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  571. if show_splash:
  572. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  573. "Canvas initialization started.\n"
  574. "Canvas initialization finished in"), '%.2f' % self.used_time),
  575. alignment=Qt.AlignBottom | Qt.AlignLeft,
  576. color=QtGui.QColor("gray"))
  577. self.ui.splitter.setStretchFactor(1, 2)
  578. # ###########################################################################################################
  579. # ############################################### SYS TRAY ##################################################
  580. # ###########################################################################################################
  581. if self.defaults["global_systray_icon"]:
  582. self.parent_w = QtWidgets.QWidget()
  583. if self.cmd_line_headless == 1:
  584. self.trayIcon = FlatCAMSystemTray(app=self,
  585. icon=QtGui.QIcon(self.resource_location +
  586. '/flatcam_icon32_green.png'),
  587. headless=True,
  588. parent=self.parent_w)
  589. else:
  590. self.trayIcon = FlatCAMSystemTray(app=self,
  591. icon=QtGui.QIcon(self.resource_location +
  592. '/flatcam_icon32_green.png'),
  593. parent=self.parent_w)
  594. # ###########################################################################################################
  595. # ############################################### Worker SETUP ##############################################
  596. # ###########################################################################################################
  597. if self.defaults["global_worker_number"]:
  598. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  599. else:
  600. self.workers = WorkerStack(workers_number=2)
  601. self.worker_task.connect(self.workers.add_task)
  602. self.log.debug("Finished creating Workers crew.")
  603. # ###########################################################################################################
  604. # ############################################# Activity Monitor ###########################################
  605. # ###########################################################################################################
  606. self.activity_view = FlatCAMActivityView(app=self)
  607. self.ui.infobar.addWidget(self.activity_view)
  608. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  609. # ###########################################################################################################
  610. # ############################################# Signal handling #############################################
  611. # ###########################################################################################################
  612. # ########################################## Custom signals ################################################
  613. # signal for displaying messages in status bar
  614. self.inform.connect(self.info)
  615. # signal to be called when the app is quiting
  616. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  617. self.message.connect(self.message_dialog)
  618. # self.progress.connect(self.set_progress_bar)
  619. # signals that are emitted when object state changes
  620. self.object_created.connect(self.on_object_created)
  621. self.object_changed.connect(self.on_object_changed)
  622. self.object_plotted.connect(self.on_object_plotted)
  623. self.plots_updated.connect(self.on_plots_updated)
  624. # signals emitted when file state change
  625. self.file_opened.connect(self.register_recent)
  626. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  627. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  628. # ########################################## Standard signals ###############################################
  629. # ### Menu
  630. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  631. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  632. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  633. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  634. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  635. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  636. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  637. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  638. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  639. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  640. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  641. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  642. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  643. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  644. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  645. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  646. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  647. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  648. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  649. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  650. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  651. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  652. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  653. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  654. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  655. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  656. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  657. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  658. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  659. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  660. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  661. self.ui.menufile_exit.triggered.connect(self.final_save)
  662. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  663. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  664. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  665. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  666. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  667. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  668. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  669. self.ui.menueditdelete.triggered.connect(self.on_delete)
  670. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  671. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  672. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  673. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  674. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  675. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  676. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  677. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  678. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  679. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  680. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  681. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  682. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  683. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  684. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  685. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  686. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  687. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  688. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  689. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  690. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  691. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  692. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  693. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  694. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  695. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  696. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  697. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  698. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  699. self.ui.menuview_replot.triggered.connect(self.plot_all)
  700. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  701. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  702. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  703. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  704. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  705. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  706. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  707. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  708. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  709. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  710. self.ui.menuhelp_about.triggered.connect(self.on_about)
  711. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  712. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  713. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  714. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  715. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  716. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  717. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  718. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  719. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  720. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  721. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  722. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  723. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  724. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  725. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  726. # ToolBar signals
  727. self.connect_toolbar_signals()
  728. # Notebook and Plot Tab Area signals
  729. # make the right click on the notebook tab and plot tab area tab raise a menu
  730. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  731. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  732. self.on_tab_setup_context_menu()
  733. # activate initial state
  734. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  735. # Context Menu
  736. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  737. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  738. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  739. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  740. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  741. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  742. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  743. self.ui.clearplot.triggered.connect(self.clear_plots)
  744. self.ui.replot.triggered.connect(self.plot_all)
  745. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  746. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  747. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  748. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  749. self.ui.popmenu_move.triggered.connect(self.obj_move)
  750. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  751. # Project Context Menu -> Color Setting
  752. for act in self.ui.menuprojectcolor.actions():
  753. act.triggered.connect(self.on_set_color_action_triggered)
  754. # ###########################################################################################################
  755. # #################################### GUI PREFERENCES SIGNALS ##############################################
  756. # ###########################################################################################################
  757. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  758. lambda: self.on_toggle_units(no_pref=False))
  759. # ##################################### Workspace Setting Signals ###########################################
  760. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  761. self.on_workspace_modified)
  762. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  763. self.on_workspace_modified
  764. )
  765. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  766. # ###########################################################################################################
  767. # ######################################## GUI SETTINGS SIGNALS #############################################
  768. # ###########################################################################################################
  769. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  770. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  771. # ######################################## Tools related signals ############################################
  772. # Film Tool
  773. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  774. self.on_film_color_entry)
  775. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  776. self.on_film_color_button)
  777. # QRCode Tool
  778. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  779. self.on_qrcode_fill_color_entry)
  780. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  781. self.on_qrcode_fill_color_button)
  782. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  783. self.on_qrcode_back_color_entry)
  784. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  785. self.on_qrcode_back_color_button)
  786. # portability changed signal
  787. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  788. # Object list
  789. self.collection.view.activated.connect(self.on_row_activated)
  790. self.collection.item_selected.connect(self.on_row_selected)
  791. self.object_status_changed.connect(self.on_collection_updated)
  792. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  793. # Export Excellon parameters.
  794. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  795. self.on_update_exc_export
  796. )
  797. # call it once to make sure it is updated at startup
  798. self.on_update_exc_export(state=self.defaults["excellon_update"])
  799. # when there are arguments at application startup this get launched
  800. self.args_at_startup[list].connect(self.on_startup_args)
  801. # ###########################################################################################################
  802. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  803. # ###########################################################################################################
  804. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  805. lambda: self.restore_extensions(ext_type='excellon'))
  806. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  807. lambda: self.restore_extensions(ext_type='gcode'))
  808. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  809. lambda: self.restore_extensions(ext_type='gerber'))
  810. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  811. lambda: self.delete_all_extensions(ext_type='excellon'))
  812. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  813. lambda: self.delete_all_extensions(ext_type='gcode'))
  814. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  815. lambda: self.delete_all_extensions(ext_type='gerber'))
  816. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  817. lambda: self.add_extension(ext_type='excellon'))
  818. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  819. lambda: self.add_extension(ext_type='gcode'))
  820. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  821. lambda: self.add_extension(ext_type='gerber'))
  822. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  823. lambda: self.del_extension(ext_type='excellon'))
  824. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  825. lambda: self.del_extension(ext_type='gcode'))
  826. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  827. lambda: self.del_extension(ext_type='gerber'))
  828. # connect the 'Apply' buttons from the Preferences/File Associations
  829. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  830. lambda: self.on_register_files(obj_type='excellon'))
  831. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  832. lambda: self.on_register_files(obj_type='gcode'))
  833. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  834. lambda: self.on_register_files(obj_type='gerber'))
  835. # ###########################################################################################################
  836. # ########################################### KEYWORDS SIGNALS ##############################################
  837. # ###########################################################################################################
  838. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  839. lambda: self.restore_extensions(ext_type='keyword'))
  840. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  841. lambda: self.delete_all_extensions(ext_type='keyword'))
  842. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  843. lambda: self.add_extension(ext_type='keyword'))
  844. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  845. lambda: self.del_extension(ext_type='keyword'))
  846. # connect the abort_all_tasks related slots to the related signals
  847. self.proc_container.idle_flag.connect(self.app_is_idle)
  848. # signal emitted when a tab is closed in the Plot Area
  849. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  850. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  851. self.ui.snap_infobar_label.clicked.connect(self.on_grid_icon_snap_clicked)
  852. # signal to close the application
  853. self.close_app_signal.connect(self.kill_app)
  854. # ################################# FINISHED CONNECTING SIGNALS #############################################
  855. # ###########################################################################################################
  856. # ###########################################################################################################
  857. # ###########################################################################################################
  858. self.log.debug("Finished connecting Signals.")
  859. # ###########################################################################################################
  860. # ########################################## Other setups ###################################################
  861. # ###########################################################################################################
  862. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  863. # depending on from where those tools are called different actions can be done
  864. self.call_source = 'app'
  865. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  866. self.tool_tab_locked = False
  867. # decide if to show or hide the Notebook side of the screen at startup
  868. if self.defaults["global_project_at_startup"] is True:
  869. self.ui.splitter.setSizes([1, 1])
  870. else:
  871. self.ui.splitter.setSizes([0, 1])
  872. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  873. self.setup_component_editor()
  874. # ###########################################################################################################
  875. # ####################################### Auto-complete KEYWORDS ############################################
  876. # ###########################################################################################################
  877. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  878. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  879. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  880. 'export_exc',
  881. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  882. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  883. 'interiors', 'isolate', 'join_excellon',
  884. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  885. 'mirror', 'ncc',
  886. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  887. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  888. 'options', 'origin',
  889. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  890. 'save', 'save_project',
  891. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  892. 'skew', 'subtract_poly', 'subtract_rectangle',
  893. 'version', 'write_gcode'
  894. ]
  895. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  896. 'Paste_1',
  897. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  898. 'Toolchange_manual', 'True', 'Users',
  899. 'all', 'auto', 'axis',
  900. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  901. 'contour', 'default',
  902. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  903. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  904. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  905. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  906. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  907. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  908. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  909. 'spacing_columns',
  910. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  911. 'toolchange_xy', 'toolchangez', 'travelz',
  912. 'tooldia', 'use_threads', 'value',
  913. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  914. ]
  915. self.tcl_keywords = [
  916. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  917. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  918. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  919. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  920. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  921. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  922. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  923. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  924. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  925. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  926. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  927. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  928. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  929. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  930. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  931. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  932. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  933. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  934. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  935. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  936. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  937. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  938. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  939. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  940. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  941. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  942. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  943. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  944. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  945. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  946. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  947. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  948. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  949. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  950. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  951. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  952. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  953. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  954. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  955. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  956. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  957. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  958. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  959. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  960. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  961. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  962. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  963. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  964. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  965. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  966. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  967. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  968. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  969. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  970. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  971. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  972. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  973. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  974. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  975. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  976. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  977. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  978. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  979. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  980. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  981. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  982. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  983. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  984. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  985. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  986. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  987. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  988. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  989. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  990. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  991. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  992. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  993. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  994. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  995. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  996. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  997. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  998. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  999. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1000. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1001. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1002. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1003. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1004. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1005. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1006. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1007. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1008. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1009. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1010. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1011. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1012. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1013. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1014. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1015. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1016. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1017. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1018. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1019. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1020. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1021. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1022. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1023. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1024. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1025. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1026. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1027. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1028. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1029. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1030. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1031. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1032. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1033. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1034. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1035. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1036. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1037. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1038. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1039. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1040. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1041. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1042. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1043. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1044. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1045. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1046. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1047. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1048. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1049. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1050. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1051. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1052. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1053. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1054. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1055. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1056. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1057. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1058. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1059. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1060. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1061. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1062. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1063. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1064. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1065. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1066. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1067. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1068. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1069. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1070. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1071. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1072. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1073. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1074. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1075. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1076. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1077. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1078. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1079. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1080. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1081. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1082. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1083. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1084. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1085. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1086. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1087. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1088. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1089. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1090. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1091. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1092. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1093. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1094. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1095. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1096. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1097. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1098. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1099. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1100. ]
  1101. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1102. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1103. # ###########################################################################################################
  1104. # ############################################## Shell SETUP ################################################
  1105. # ###########################################################################################################
  1106. self.shell = FCShell(app=self, version=self.version)
  1107. self.ui.shell_dock.setWidget(self.shell)
  1108. self.log.debug("TCL Shell has been initialized.")
  1109. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1110. if self.defaults["global_shell_at_startup"]:
  1111. self.ui.shell_dock.show()
  1112. else:
  1113. self.ui.shell_dock.hide()
  1114. # ###########################################################################################################
  1115. # ########################################## Tools and Plugins ##############################################
  1116. # ###########################################################################################################
  1117. self.dblsidedtool = None
  1118. self.distance_tool = None
  1119. self.distance_min_tool = None
  1120. self.panelize_tool = None
  1121. self.film_tool = None
  1122. self.paste_tool = None
  1123. self.calculator_tool = None
  1124. self.rules_tool = None
  1125. self.sub_tool = None
  1126. self.move_tool = None
  1127. self.cutout_tool = None
  1128. self.ncclear_tool = None
  1129. self.optimal_tool = None
  1130. self.paint_tool = None
  1131. self.transform_tool = None
  1132. self.properties_tool = None
  1133. self.pdf_tool = None
  1134. self.image_tool = None
  1135. self.pcb_wizard_tool = None
  1136. self.cal_exc_tool = None
  1137. self.qrcode_tool = None
  1138. self.copper_thieving_tool = None
  1139. self.fiducial_tool = None
  1140. self.edrills_tool = None
  1141. self.align_objects_tool = None
  1142. self.punch_tool = None
  1143. self.invert_tool = None
  1144. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1145. try:
  1146. self.install_tools()
  1147. except AttributeError as e:
  1148. log.debug("App.__init__() install tools() --> %s" % str(e))
  1149. # ###########################################################################################################
  1150. # ############################################ SETUP RECENT ITEMS ###########################################
  1151. # ###########################################################################################################
  1152. self.setup_recent_items()
  1153. # ###########################################################################################################
  1154. # ######################################### BookMarks Manager ###############################################
  1155. # ###########################################################################################################
  1156. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1157. self.install_bookmarks()
  1158. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1159. # ###########################################################################################################
  1160. # ########################################### Tools Database ################################################
  1161. # ###########################################################################################################
  1162. self.tools_db_tab = None
  1163. # ### System Font Parsing ###
  1164. # self.f_parse = ParseFont(self)
  1165. # self.parse_system_fonts()
  1166. # ###########################################################################################################
  1167. # ######################################### Check for updates ###############################################
  1168. # ###########################################################################################################
  1169. # Separate thread (Not worker)
  1170. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1171. if (self.beta is False or self.beta is None) and \
  1172. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1173. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1174. # self.thr2 = QtCore.QThread()
  1175. self.worker_task.emit({'fcn': self.version_check,
  1176. 'params': []})
  1177. # self.thr2.start(QtCore.QThread.LowPriority)
  1178. # ###########################################################################################################
  1179. # ##################################### Register files with FlatCAM; #######################################
  1180. # ################################### It works only for Windows for now ####################################
  1181. # ###########################################################################################################
  1182. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1183. self.on_register_files()
  1184. # ###########################################################################################################
  1185. # ######################################## Variables for global usage #######################################
  1186. # ###########################################################################################################
  1187. # hold the App units
  1188. self.units = 'MM'
  1189. # coordinates for relative position display
  1190. self.rel_point1 = (0, 0)
  1191. self.rel_point2 = (0, 0)
  1192. # variable to store coordinates
  1193. self.pos = (0, 0)
  1194. self.pos_canvas = (0, 0)
  1195. self.pos_jump = (0, 0)
  1196. # variable to store mouse coordinates
  1197. self.mouse = [0, 0]
  1198. # variable to store the delta positions on cavnas
  1199. self.dx = 0
  1200. self.dy = 0
  1201. # decide if we have a double click or single click
  1202. self.doubleclick = False
  1203. # store here the is_dragging value
  1204. self.event_is_dragging = False
  1205. # variable to store if a command is active (then the var is not None) and which one it is
  1206. self.command_active = None
  1207. # variable to store the status of moving selection action
  1208. # None value means that it's not an selection action
  1209. # True value = a selection from left to right
  1210. # False value = a selection from right to left
  1211. self.selection_type = None
  1212. # List to store the objects that are currently loaded in FlatCAM
  1213. # This list is updated on each object creation or object delete
  1214. self.all_objects_list = []
  1215. self.objects_under_the_click_list = []
  1216. # List to store the objects that are selected
  1217. self.sel_objects_list = []
  1218. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1219. self.key_modifiers = None
  1220. # Variable to hold the status of the axis
  1221. self.toggle_axis = True
  1222. # Variable to hold the status of the grid lines
  1223. self.toggle_grid_lines = True
  1224. # Variable to store the status of the fullscreen event
  1225. self.toggle_fscreen = False
  1226. # Variable to store the status of the code editor
  1227. self.toggle_codeeditor = False
  1228. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1229. self.click_noproject = False
  1230. self.cursor = None
  1231. # Variable to store the GCODE that was edited
  1232. self.gcode_edited = ""
  1233. self.text_editor_tab = None
  1234. # reference for the self.ui.code_editor
  1235. self.reference_code_editor = None
  1236. self.script_code = ''
  1237. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1238. self.tools_db_changed_flag = False
  1239. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1240. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1241. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1242. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1243. 'tsm']
  1244. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1245. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1246. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1247. 'sbp', 'tap', 'xpi']
  1248. self.svg_list = ['svg']
  1249. self.dxf_list = ['dxf']
  1250. self.pdf_list = ['pdf']
  1251. self.prj_list = ['flatprj']
  1252. self.conf_list = ['flatconfig']
  1253. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1254. # flag for polygons not cleared
  1255. self.poly_not_cleared = False
  1256. # VisPy visuals
  1257. self.isHovering = False
  1258. self.notHovering = True
  1259. # Window geometry
  1260. self.x_pos = None
  1261. self.y_pos = None
  1262. self.width = None
  1263. self.height = None
  1264. # when True, the app has to return from any thread
  1265. self.abort_flag = False
  1266. # set the value used in the Windows Title
  1267. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1268. # this holds a widget that is installed in the Plot Area when View Source option is used
  1269. self.source_editor_tab = None
  1270. self.pagesize = {}
  1271. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1272. # VisPy visuals
  1273. if self.is_legacy is False:
  1274. try:
  1275. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1276. except AttributeError:
  1277. self.tool_shapes = None
  1278. else:
  1279. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1280. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1281. # used in the delayed shutdown self.start_delayed_quit() method
  1282. self.save_timer = None
  1283. # ###########################################################################################################
  1284. # ################################## ADDING FlatCAM EDITORS section #########################################
  1285. # ###########################################################################################################
  1286. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1287. # at the first launch of the App , the editors will not be functional.
  1288. try:
  1289. self.geo_editor = FlatCAMGeoEditor(self)
  1290. except AttributeError:
  1291. pass
  1292. try:
  1293. self.exc_editor = FlatCAMExcEditor(self)
  1294. except AttributeError:
  1295. pass
  1296. try:
  1297. self.grb_editor = FlatCAMGrbEditor(self)
  1298. except AttributeError:
  1299. pass
  1300. self.log.debug("Finished adding FlatCAM Editor's.")
  1301. self.set_ui_title(name=_("New Project - Not saved"))
  1302. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1303. current_platform = platform.architecture()[0]
  1304. if current_platform != '64bit':
  1305. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1306. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1307. # ###########################################################################################################
  1308. # ##################################### Finished the CONSTRUCTOR ############################################
  1309. # ###########################################################################################################
  1310. App.log.debug("END of constructor. Releasing control.")
  1311. # ###########################################################################################################
  1312. # ########################################## SHOW GUI #######################################################
  1313. # ###########################################################################################################
  1314. # if the app is not started as headless, show it
  1315. if self.cmd_line_headless != 1:
  1316. if show_splash:
  1317. # finish the splash
  1318. self.splash.finish(self.ui)
  1319. mgui_settings = QSettings("Open Source", "FlatCAM")
  1320. if mgui_settings.contains("maximized_gui"):
  1321. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1322. if maximized_ui is True:
  1323. self.ui.showMaximized()
  1324. else:
  1325. self.ui.show()
  1326. else:
  1327. self.ui.show()
  1328. if self.defaults["global_systray_icon"]:
  1329. self.trayIcon.show()
  1330. else:
  1331. log.warning("******************* RUNNING HEADLESS *******************")
  1332. # ###########################################################################################################
  1333. # ######################################## START-UP ARGUMENTS ###############################################
  1334. # ###########################################################################################################
  1335. # test if the program was started with a script as parameter
  1336. if self.cmd_line_shellvar:
  1337. try:
  1338. cnt = 0
  1339. command_tcl = 0
  1340. for i in self.cmd_line_shellvar.split(','):
  1341. if i is not None:
  1342. # noinspection PyBroadException
  1343. try:
  1344. command_tcl = eval(i)
  1345. except Exception:
  1346. command_tcl = i
  1347. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1348. cnt += 1
  1349. # if there are Windows paths then replace the path separator with a Unix like one
  1350. if sys.platform == 'win32':
  1351. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1352. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1353. except Exception as ext:
  1354. print("ERROR: ", ext)
  1355. sys.exit(2)
  1356. if self.cmd_line_shellfile:
  1357. if self.cmd_line_headless != 1:
  1358. if self.ui.shell_dock.isHidden():
  1359. self.ui.shell_dock.show()
  1360. try:
  1361. with open(self.cmd_line_shellfile, "r") as myfile:
  1362. # if show_splash:
  1363. # self.splash.showMessage('%s: %ssec\n%s' % (
  1364. # _("Canvas initialization started.\n"
  1365. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1366. # _("Executing Tcl Script ...")),
  1367. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1368. # color=QtGui.QColor("gray"))
  1369. cmd_line_shellfile_text = myfile.read()
  1370. if self.cmd_line_headless != 1:
  1371. self.shell.exec_command(cmd_line_shellfile_text)
  1372. else:
  1373. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1374. except Exception as ext:
  1375. print("ERROR: ", ext)
  1376. sys.exit(2)
  1377. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1378. # the path/file_name must be enclosed in quotes if it contain spaces
  1379. if App.args:
  1380. self.args_at_startup.emit(App.args)
  1381. if self.defaults.old_defaults_found is True:
  1382. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1383. "Please reboot the application to update."))
  1384. self.defaults.old_defaults_found = False
  1385. # ######################################### INIT FINISHED #######################################################
  1386. # #################################################################################################################
  1387. # #################################################################################################################
  1388. # #################################################################################################################
  1389. # #################################################################################################################
  1390. # #################################################################################################################
  1391. @staticmethod
  1392. def copy_and_overwrite(from_path, to_path):
  1393. """
  1394. From here:
  1395. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1396. :param from_path: source path
  1397. :param to_path: destination path
  1398. :return: None
  1399. """
  1400. if os.path.exists(to_path):
  1401. shutil.rmtree(to_path)
  1402. try:
  1403. shutil.copytree(from_path, to_path)
  1404. except FileNotFoundError:
  1405. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1406. shutil.copytree(from_new_path, to_path)
  1407. def on_startup_args(self, args, silent=False):
  1408. """
  1409. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1410. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1411. :param args: a list containing the application args at startup
  1412. :return: None
  1413. """
  1414. if args is not None:
  1415. args_to_process = args
  1416. else:
  1417. args_to_process = App.args
  1418. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1419. for argument in args_to_process:
  1420. if '.FlatPrj'.lower() in argument.lower():
  1421. try:
  1422. project_name = str(argument)
  1423. if project_name == "":
  1424. if silent is False:
  1425. self.inform.emit(_("Cancelled."))
  1426. else:
  1427. # self.open_project(project_name)
  1428. run_from_arg = True
  1429. # self.worker_task.emit({'fcn': self.open_project,
  1430. # 'params': [project_name, run_from_arg]})
  1431. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1432. except Exception as e:
  1433. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1434. elif '.FlatConfig'.lower() in argument.lower():
  1435. try:
  1436. file_name = str(argument)
  1437. if file_name == "":
  1438. if silent is False:
  1439. self.inform.emit(_("Open Config file failed."))
  1440. else:
  1441. run_from_arg = True
  1442. # self.worker_task.emit({'fcn': self.open_config_file,
  1443. # 'params': [file_name, run_from_arg]})
  1444. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1445. except Exception as e:
  1446. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1447. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1448. try:
  1449. file_name = str(argument)
  1450. if file_name == "":
  1451. if silent is False:
  1452. self.inform.emit(_("Open Script file failed."))
  1453. else:
  1454. if silent is False:
  1455. self.on_fileopenscript(name=file_name)
  1456. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1457. self.on_filerunscript(name=file_name)
  1458. except Exception as e:
  1459. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1460. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1461. log.debug("App.on_startup_args() --> Quit event.")
  1462. sys.exit()
  1463. elif 'save'.lower() in argument.lower():
  1464. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1465. self.preferencesUiManager.save_defaults()
  1466. else:
  1467. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1468. proc_arg = argument.lower()
  1469. for ext in exc_list:
  1470. proc_ext = ext.replace(' ', '')
  1471. proc_ext = '.%s' % proc_ext
  1472. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1473. file_name = str(argument)
  1474. if file_name == "":
  1475. if silent is False:
  1476. self.inform.emit(_("Open Excellon file failed."))
  1477. else:
  1478. self.on_fileopenexcellon(name=file_name, signal=None)
  1479. return
  1480. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1481. for ext in gco_list:
  1482. proc_ext = ext.replace(' ', '')
  1483. proc_ext = '.%s' % proc_ext
  1484. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1485. file_name = str(argument)
  1486. if file_name == "":
  1487. if silent is False:
  1488. self.inform.emit(_("Open GCode file failed."))
  1489. else:
  1490. self.on_fileopengcode(name=file_name, signal=None)
  1491. return
  1492. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1493. for ext in grb_list:
  1494. proc_ext = ext.replace(' ', '')
  1495. proc_ext = '.%s' % proc_ext
  1496. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1497. file_name = str(argument)
  1498. if file_name == "":
  1499. if silent is False:
  1500. self.inform.emit(_("Open Gerber file failed."))
  1501. else:
  1502. self.on_fileopengerber(name=file_name, signal=None)
  1503. return
  1504. # if it reached here without already returning then the app was registered with a file that it does not
  1505. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1506. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1507. # for arg in args_to_process:
  1508. # if 'FlatCAM.exe' in arg:
  1509. # continue
  1510. # else:
  1511. # sys.exit(2)
  1512. def set_ui_title(self, name):
  1513. """
  1514. Sets the title of the main window.
  1515. :param name: String that store the project path and project name
  1516. :return: None
  1517. """
  1518. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1519. (self.version,
  1520. ('BETA' if self.beta else ''),
  1521. platform.architecture()[0],
  1522. self.engine,
  1523. name)
  1524. )
  1525. def on_app_restart(self):
  1526. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1527. # be left in the SySTray
  1528. try:
  1529. self.trayIcon.hide()
  1530. except Exception:
  1531. pass
  1532. fcTranslate.restart_program(app=self)
  1533. def clear_pool(self):
  1534. """
  1535. Clear the multiprocessing pool and calls garbage collector.
  1536. :return: None
  1537. """
  1538. self.pool.close()
  1539. self.pool = Pool()
  1540. self.pool_recreated.emit(self.pool)
  1541. gc.collect()
  1542. def install_tools(self):
  1543. """
  1544. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1545. Instantiation of the Tools classes.
  1546. The order that the tools are installed is important as they can depend on each other install position.
  1547. :return: None
  1548. """
  1549. self.distance_tool = Distance(self)
  1550. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1551. before=self.ui.menueditorigin,
  1552. separator=False)
  1553. self.distance_min_tool = DistanceMin(self)
  1554. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1555. pos=self.ui.menuedit,
  1556. before=self.ui.menueditorigin,
  1557. separator=True)
  1558. self.dblsidedtool = DblSidedTool(self)
  1559. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1560. self.cal_exc_tool = ToolCalibration(self)
  1561. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1562. before=self.dblsidedtool.menuAction,
  1563. separator=False)
  1564. self.align_objects_tool = AlignObjects(self)
  1565. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1566. self.edrills_tool = ToolExtractDrills(self)
  1567. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1568. self.panelize_tool = Panelize(self)
  1569. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1570. self.film_tool = Film(self)
  1571. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1572. self.paste_tool = SolderPaste(self)
  1573. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1574. self.calculator_tool = ToolCalculator(self)
  1575. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1576. self.sub_tool = ToolSub(self)
  1577. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1578. pos=self.ui.menutool, separator=True)
  1579. self.rules_tool = RulesCheck(self)
  1580. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1581. pos=self.ui.menutool, separator=False)
  1582. self.optimal_tool = ToolOptimal(self)
  1583. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1584. pos=self.ui.menutool, separator=True)
  1585. self.move_tool = ToolMove(self)
  1586. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1587. before=self.ui.menueditorigin, separator=True)
  1588. self.cutout_tool = CutOut(self)
  1589. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1590. before=self.sub_tool.menuAction)
  1591. self.ncclear_tool = NonCopperClear(self)
  1592. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1593. before=self.sub_tool.menuAction, separator=True)
  1594. self.paint_tool = ToolPaint(self)
  1595. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1596. before=self.sub_tool.menuAction, separator=True)
  1597. self.copper_thieving_tool = ToolCopperThieving(self)
  1598. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1599. pos=self.ui.menutool)
  1600. self.fiducial_tool = ToolFiducials(self)
  1601. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1602. pos=self.ui.menutool)
  1603. self.qrcode_tool = QRCode(self)
  1604. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1605. pos=self.ui.menutool)
  1606. self.punch_tool = ToolPunchGerber(self)
  1607. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1608. self.invert_tool = ToolInvertGerber(self)
  1609. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1610. self.transform_tool = ToolTransform(self)
  1611. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1612. pos=self.ui.menuoptions, separator=True)
  1613. self.properties_tool = Properties(self)
  1614. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1615. pos=self.ui.menuoptions)
  1616. self.pdf_tool = ToolPDF(self)
  1617. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1618. pos=self.ui.menufileimport,
  1619. separator=True)
  1620. self.image_tool = ToolImage(self)
  1621. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1622. pos=self.ui.menufileimport,
  1623. separator=True)
  1624. self.pcb_wizard_tool = PcbWizard(self)
  1625. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1626. pos=self.ui.menufileimport)
  1627. self.log.debug("Tools are installed.")
  1628. def remove_tools(self):
  1629. """
  1630. Will remove all the actions in the Tool menu.
  1631. :return: None
  1632. """
  1633. for act in self.ui.menutool.actions():
  1634. self.ui.menutool.removeAction(act)
  1635. def init_tools(self):
  1636. """
  1637. Initialize the Tool tab in the notebook side of the central widget.
  1638. Remove the actions in the Tools menu.
  1639. Instantiate again the FlatCAM tools (plugins).
  1640. All this is required when changing the layout: standard, compact etc.
  1641. :return: None
  1642. """
  1643. log.debug("init_tools()")
  1644. # delete the data currently in the Tools Tab and the Tab itself
  1645. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1646. if widget is not None:
  1647. widget.deleteLater()
  1648. self.ui.notebook.removeTab(2)
  1649. # rebuild the Tools Tab
  1650. self.ui.tool_tab = QtWidgets.QWidget()
  1651. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1652. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1653. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1654. self.ui.tool_scroll_area = VerticalScrollArea()
  1655. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1656. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1657. # first remove all of them
  1658. self.remove_tools()
  1659. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1660. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1661. '&Command Line\tS')
  1662. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1663. # third install all of them
  1664. try:
  1665. self.install_tools()
  1666. except AttributeError:
  1667. pass
  1668. self.log.debug("Tools are initialized.")
  1669. # def parse_system_fonts(self):
  1670. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1671. # 'params': []})
  1672. def connect_toolbar_signals(self):
  1673. """
  1674. Reconnect the signals to the actions in the toolbar.
  1675. This has to be done each time after the FlatCAM tools are removed/installed.
  1676. :return: None
  1677. """
  1678. # Toolbar
  1679. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1680. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1681. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1682. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1683. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1684. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1685. self.ui.replot_btn.triggered.connect(self.plot_all)
  1686. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1687. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1688. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1689. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1690. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1691. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1692. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1693. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1694. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1695. self.ui.delete_btn.triggered.connect(self.on_delete)
  1696. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1697. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1698. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1699. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1700. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1701. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1702. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1703. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1704. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1705. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1706. # Tools Toolbar Signals
  1707. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1708. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1709. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1710. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1711. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1712. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1713. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1714. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1715. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1716. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1717. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1718. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1719. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1720. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1721. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1722. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1723. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1724. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1725. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1726. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1727. def object2editor(self):
  1728. """
  1729. Send the current Geometry or Excellon object (if any) into the it's editor.
  1730. :return: None
  1731. """
  1732. self.defaults.report_usage("object2editor()")
  1733. # disable the objects menu as it may interfere with the Editors
  1734. self.ui.menuobjects.setDisabled(True)
  1735. edited_object = self.collection.get_active()
  1736. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1737. isinstance(edited_object, ExcellonObject):
  1738. pass
  1739. else:
  1740. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1741. return
  1742. if isinstance(edited_object, GeometryObject):
  1743. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1744. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1745. # we set the notebook to hidden
  1746. # self.ui.splitter.setSizes([0, 1])
  1747. if edited_object.multigeo is True:
  1748. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1749. if len(sel_rows) > 1:
  1750. self.inform.emit('[WARNING_NOTCL] %s' %
  1751. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1752. "is not possible.\n"
  1753. "Edit only one geometry at a time."))
  1754. # determine the tool dia of the selected tool
  1755. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1756. # now find the key in the edited_object.tools that has this tooldia
  1757. multi_tool = 1
  1758. for tool in edited_object.tools:
  1759. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1760. multi_tool = tool
  1761. break
  1762. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1763. else:
  1764. self.geo_editor.edit_fcgeometry(edited_object)
  1765. # set call source to the Editor we go into
  1766. self.call_source = 'geo_editor'
  1767. elif isinstance(edited_object, ExcellonObject):
  1768. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1769. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1770. if self.ui.splitter.sizes()[0] == 0:
  1771. self.ui.splitter.setSizes([1, 1])
  1772. self.exc_editor.edit_fcexcellon(edited_object)
  1773. # set call source to the Editor we go into
  1774. self.call_source = 'exc_editor'
  1775. elif isinstance(edited_object, GerberObject):
  1776. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1777. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1778. if self.ui.splitter.sizes()[0] == 0:
  1779. self.ui.splitter.setSizes([1, 1])
  1780. self.grb_editor.edit_fcgerber(edited_object)
  1781. # set call source to the Editor we go into
  1782. self.call_source = 'grb_editor'
  1783. # reset the following variables so the UI is built again after edit
  1784. edited_object.ui_build = False
  1785. edited_object.build_aperture_storage = False
  1786. # make sure that we can't select another object while in Editor Mode:
  1787. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1788. self.ui.project_frame.setDisabled(True)
  1789. # delete any selection shape that might be active as they are not relevant in Editor
  1790. self.delete_selection_shape()
  1791. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1792. self.ui.plot_tab_area.protectTab(0)
  1793. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1794. self.should_we_save = True
  1795. def editor2object(self, cleanup=None):
  1796. """
  1797. Transfers the Geometry or Excellon from it's editor to the current object.
  1798. :return: None
  1799. """
  1800. self.defaults.report_usage("editor2object()")
  1801. # re-enable the objects menu that was disabled on entry in Editor mode
  1802. self.ui.menuobjects.setDisabled(False)
  1803. # do not update a geometry or excellon object unless it comes out of an editor
  1804. if self.call_source != 'app':
  1805. edited_obj = self.collection.get_active()
  1806. if cleanup is None:
  1807. msgbox = QtWidgets.QMessageBox()
  1808. msgbox.setText(_("Do you want to save the edited object?"))
  1809. msgbox.setWindowTitle(_("Close Editor"))
  1810. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1811. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1812. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1813. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1814. msgbox.setDefaultButton(bt_yes)
  1815. msgbox.exec_()
  1816. response = msgbox.clickedButton()
  1817. if response == bt_yes:
  1818. # clean the Tools Tab
  1819. self.ui.tool_scroll_area.takeWidget()
  1820. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1821. self.ui.notebook.setTabText(2, "Tool")
  1822. if isinstance(edited_obj, GeometryObject):
  1823. obj_type = "Geometry"
  1824. if cleanup is None:
  1825. self.geo_editor.update_fcgeometry(edited_obj)
  1826. # self.geo_editor.update_options(edited_obj)
  1827. self.geo_editor.deactivate()
  1828. # restore GUI to the Selected TAB
  1829. # Remove anything else in the GUI
  1830. self.ui.tool_scroll_area.takeWidget()
  1831. # update the geo object options so it is including the bounding box values
  1832. try:
  1833. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1834. edited_obj.options['xmin'] = xmin
  1835. edited_obj.options['ymin'] = ymin
  1836. edited_obj.options['xmax'] = xmax
  1837. edited_obj.options['ymax'] = ymax
  1838. except AttributeError as e:
  1839. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1840. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1841. edited_obj.build_ui()
  1842. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1843. elif isinstance(edited_obj, GerberObject):
  1844. obj_type = "Gerber"
  1845. if cleanup is None:
  1846. self.grb_editor.update_fcgerber()
  1847. self.grb_editor.update_options(edited_obj)
  1848. self.grb_editor.deactivate_grb_editor()
  1849. # delete the old object (the source object) if it was an empty one
  1850. try:
  1851. if len(edited_obj.solid_geometry) == 0:
  1852. old_name = edited_obj.options['name']
  1853. self.collection.set_active(old_name)
  1854. self.collection.delete_active()
  1855. except TypeError:
  1856. # if the solid_geometry is a single Polygon the len() will not work
  1857. # in any case, falling here means that we have something in the solid_geometry, even if only
  1858. # a single Polygon, therefore we pass this
  1859. pass
  1860. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1861. # restore GUI to the Selected TAB
  1862. # Remove anything else in the GUI
  1863. self.ui.selected_scroll_area.takeWidget()
  1864. elif isinstance(edited_obj, ExcellonObject):
  1865. obj_type = "Excellon"
  1866. if cleanup is None:
  1867. self.exc_editor.update_fcexcellon(edited_obj)
  1868. # self.exc_editor.update_options(edited_obj)
  1869. self.exc_editor.deactivate()
  1870. # restore GUI to the Selected TAB
  1871. # Remove anything else in the GUI
  1872. self.ui.tool_scroll_area.takeWidget()
  1873. # delete the old object (the source object) if it was an empty one
  1874. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1875. old_name = edited_obj.options['name']
  1876. self.collection.delete_by_name(name=old_name)
  1877. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1878. else:
  1879. self.inform.emit('[WARNING_NOTCL] %s' %
  1880. _("Select a Gerber, Geometry or Excellon Object to update."))
  1881. return
  1882. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1883. elif response == bt_no:
  1884. # clean the Tools Tab
  1885. self.ui.tool_scroll_area.takeWidget()
  1886. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1887. self.ui.notebook.setTabText(2, "Tool")
  1888. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1889. if isinstance(edited_obj, GeometryObject):
  1890. self.geo_editor.deactivate()
  1891. edited_obj.build_ui()
  1892. elif isinstance(edited_obj, GerberObject):
  1893. self.grb_editor.deactivate_grb_editor()
  1894. edited_obj.build_ui()
  1895. elif isinstance(edited_obj, ExcellonObject):
  1896. self.exc_editor.deactivate()
  1897. edited_obj.build_ui()
  1898. else:
  1899. self.inform.emit('[WARNING_NOTCL] %s' %
  1900. _("Select a Gerber, Geometry or Excellon Object to update."))
  1901. return
  1902. elif response == bt_cancel:
  1903. return
  1904. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1905. # edited_obj.build_ui()
  1906. # Switch notebook to Selected page
  1907. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1908. else:
  1909. if isinstance(edited_obj, GeometryObject):
  1910. self.geo_editor.deactivate()
  1911. elif isinstance(edited_obj, GerberObject):
  1912. self.grb_editor.deactivate_grb_editor()
  1913. elif isinstance(edited_obj, ExcellonObject):
  1914. self.exc_editor.deactivate()
  1915. else:
  1916. self.inform.emit('[WARNING_NOTCL] %s' %
  1917. _("Select a Gerber, Geometry or Excellon Object to update."))
  1918. return
  1919. # if notebook is hidden we show it
  1920. if self.ui.splitter.sizes()[0] == 0:
  1921. self.ui.splitter.setSizes([1, 1])
  1922. # restore the call_source to app
  1923. self.call_source = 'app'
  1924. edited_obj.plot()
  1925. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1926. self.ui.plot_tab_area.protectTab(0)
  1927. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1928. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1929. self.ui.project_frame.setDisabled(False)
  1930. def get_last_folder(self):
  1931. """
  1932. Get the folder path from where the last file was opened.
  1933. :return: String, last opened folder path
  1934. """
  1935. return self.defaults["global_last_folder"]
  1936. def get_last_save_folder(self):
  1937. """
  1938. Get the folder path from where the last file was saved.
  1939. :return: String, last saved folder path
  1940. """
  1941. loc = self.defaults["global_last_save_folder"]
  1942. if loc is None:
  1943. loc = self.defaults["global_last_folder"]
  1944. if loc is None:
  1945. loc = os.path.dirname(__file__)
  1946. return loc
  1947. def info(self, msg):
  1948. """
  1949. Informs the user. Normally on the status bar, optionally
  1950. also on the shell.
  1951. :param msg: Text to write.
  1952. :return: None
  1953. """
  1954. # Type of message in brackets at the beginning of the message.
  1955. match = re.search(r"\[(.*)\](.*)", msg)
  1956. if match:
  1957. level = match.group(1)
  1958. msg_ = match.group(2)
  1959. self.ui.fcinfo.set_status(str(msg_), level=level)
  1960. if level.lower() == "error":
  1961. self.shell_message(msg, error=True, show=True)
  1962. elif level.lower() == "warning":
  1963. self.shell_message(msg, warning=True, show=True)
  1964. elif level.lower() == "error_notcl":
  1965. self.shell_message(msg, error=True, show=False)
  1966. elif level.lower() == "warning_notcl":
  1967. self.shell_message(msg, warning=True, show=False)
  1968. elif level.lower() == "success":
  1969. self.shell_message(msg, success=True, show=False)
  1970. elif level.lower() == "selected":
  1971. self.shell_message(msg, selected=True, show=False)
  1972. else:
  1973. self.shell_message(msg, show=False)
  1974. else:
  1975. self.ui.fcinfo.set_status(str(msg), level="info")
  1976. # make sure that if the message is to clear the infobar with a space
  1977. # is not printed over and over on the shell
  1978. if msg != '':
  1979. self.shell_message(msg)
  1980. def restore_toolbar_view(self):
  1981. """
  1982. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1983. was saved in the defaults dictionary.
  1984. :return: None
  1985. """
  1986. tb = self.defaults["global_toolbar_view"]
  1987. if tb & 1:
  1988. self.ui.toolbarfile.setVisible(True)
  1989. else:
  1990. self.ui.toolbarfile.setVisible(False)
  1991. if tb & 2:
  1992. self.ui.toolbargeo.setVisible(True)
  1993. else:
  1994. self.ui.toolbargeo.setVisible(False)
  1995. if tb & 4:
  1996. self.ui.toolbarview.setVisible(True)
  1997. else:
  1998. self.ui.toolbarview.setVisible(False)
  1999. if tb & 8:
  2000. self.ui.toolbartools.setVisible(True)
  2001. else:
  2002. self.ui.toolbartools.setVisible(False)
  2003. if tb & 16:
  2004. self.ui.exc_edit_toolbar.setVisible(True)
  2005. else:
  2006. self.ui.exc_edit_toolbar.setVisible(False)
  2007. if tb & 32:
  2008. self.ui.geo_edit_toolbar.setVisible(True)
  2009. else:
  2010. self.ui.geo_edit_toolbar.setVisible(False)
  2011. if tb & 64:
  2012. self.ui.grb_edit_toolbar.setVisible(True)
  2013. else:
  2014. self.ui.grb_edit_toolbar.setVisible(False)
  2015. if tb & 128:
  2016. self.ui.snap_toolbar.setVisible(True)
  2017. else:
  2018. self.ui.snap_toolbar.setVisible(False)
  2019. if tb & 256:
  2020. self.ui.toolbarshell.setVisible(True)
  2021. else:
  2022. self.ui.toolbarshell.setVisible(False)
  2023. def on_import_preferences(self):
  2024. """
  2025. Loads the application default settings from a saved file into
  2026. ``self.defaults`` dictionary.
  2027. :return: None
  2028. """
  2029. self.defaults.report_usage("on_import_preferences")
  2030. App.log.debug("App.on_import_preferences()")
  2031. # Show file chooser
  2032. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2033. try:
  2034. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2035. directory=self.data_path,
  2036. filter=filter_)
  2037. except TypeError:
  2038. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2039. filter=filter_)
  2040. filename = str(filename)
  2041. if filename == "":
  2042. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2043. return
  2044. # Load in the defaults from the chosen file
  2045. self.defaults.load(filename=filename)
  2046. self.preferencesUiManager.on_preferences_edited()
  2047. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2048. def on_export_preferences(self):
  2049. """
  2050. Save the defaults dictionary to a file.
  2051. :return: None
  2052. """
  2053. self.defaults.report_usage("on_export_preferences")
  2054. App.log.debug("on_export_preferences()")
  2055. # defaults_file_content = None
  2056. # Show file chooser
  2057. date = str(datetime.today()).rpartition('.')[0]
  2058. date = ''.join(c for c in date if c not in ':-')
  2059. date = date.replace(' ', '_')
  2060. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2061. try:
  2062. filename, _f = FCFileSaveDialog.get_saved_filename(
  2063. caption=_("Export FlatCAM Preferences"),
  2064. directory=self.data_path + '/preferences_' + date,
  2065. filter=filter__
  2066. )
  2067. except TypeError:
  2068. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2069. filename = str(filename)
  2070. if filename == "":
  2071. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2072. return
  2073. # Update options
  2074. self.preferencesUiManager.defaults_read_form()
  2075. self.defaults.propagate_defaults()
  2076. # Save update options
  2077. try:
  2078. self.defaults.write(filename=filename)
  2079. except Exception:
  2080. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2081. return
  2082. if self.defaults["global_open_style"] is False:
  2083. self.file_opened.emit("preferences", filename)
  2084. self.file_saved.emit("preferences", filename)
  2085. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2086. def save_to_file(self, content_to_save, txt_content):
  2087. """
  2088. Save something to a file.
  2089. :return: None
  2090. """
  2091. self.defaults.report_usage("save_to_file")
  2092. App.log.debug("save_to_file()")
  2093. self.date = str(datetime.today()).rpartition('.')[0]
  2094. self.date = ''.join(c for c in self.date if c not in ':-')
  2095. self.date = self.date.replace(' ', '_')
  2096. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2097. path_to_save = self.defaults["global_last_save_folder"] if\
  2098. self.defaults["global_last_save_folder"] is not None else self.data_path
  2099. try:
  2100. filename, _f = FCFileSaveDialog.get_saved_filename(
  2101. caption=_("Save to file"),
  2102. directory=path_to_save + '/file_' + self.date,
  2103. filter=filter__
  2104. )
  2105. except TypeError:
  2106. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2107. filename = str(filename)
  2108. if filename == "":
  2109. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2110. return
  2111. else:
  2112. try:
  2113. with open(filename, 'w') as f:
  2114. ___ = f.read()
  2115. except PermissionError:
  2116. self.inform.emit('[WARNING] %s' %
  2117. _("Permission denied, saving not possible.\n"
  2118. "Most likely another app is holding the file open and not accessible."))
  2119. return
  2120. except IOError:
  2121. App.log.debug('Creating a new file ...')
  2122. f = open(filename, 'w')
  2123. f.close()
  2124. except Exception:
  2125. e = sys.exc_info()[0]
  2126. App.log.error("Could not load the file.")
  2127. App.log.error(str(e))
  2128. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2129. return
  2130. # Save content
  2131. if filename.rpartition('.')[2].lower() == 'html':
  2132. file_content = content_to_save
  2133. else:
  2134. file_content = txt_content
  2135. try:
  2136. with open(filename, "w") as f:
  2137. f.write(file_content)
  2138. except Exception:
  2139. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2140. return
  2141. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2142. def save_geometry(self, x, y, width, height, notebook_width):
  2143. """
  2144. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2145. launch of the application.
  2146. :param x: X position of the main window
  2147. :param y: Y position of the main window
  2148. :param width: width of the main window
  2149. :param height: height of the main window
  2150. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2151. :return: None
  2152. """
  2153. self.defaults["global_def_win_x"] = x
  2154. self.defaults["global_def_win_y"] = y
  2155. self.defaults["global_def_win_w"] = width
  2156. self.defaults["global_def_win_h"] = height
  2157. self.defaults["global_def_notebook_width"] = notebook_width
  2158. self.preferencesUiManager.save_defaults()
  2159. def restore_main_win_geom(self):
  2160. try:
  2161. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2162. self.defaults["global_def_win_y"],
  2163. self.defaults["global_def_win_w"],
  2164. self.defaults["global_def_win_h"])
  2165. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2166. except KeyError as e:
  2167. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2168. def message_dialog(self, title, message, kind="info"):
  2169. """
  2170. Builds and show a custom QMessageBox to be used in FlatCAM.
  2171. :param title: title of the QMessageBox
  2172. :param message: message to be displayed
  2173. :param kind: type of QMessageBox; will display a specific icon.
  2174. :return:
  2175. """
  2176. icon = {"info": QtWidgets.QMessageBox.Information,
  2177. "warning": QtWidgets.QMessageBox.Warning,
  2178. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2179. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2180. dlg.setText(message)
  2181. dlg.exec_()
  2182. def register_recent(self, kind, filename):
  2183. """
  2184. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2185. dictionary.
  2186. :param kind: type of file that was opened
  2187. :param filename: the path and file name for the file that was opened
  2188. :return:
  2189. """
  2190. self.log.debug("register_recent()")
  2191. self.log.debug(" %s" % kind)
  2192. self.log.debug(" %s" % filename)
  2193. record = {'kind': str(kind), 'filename': str(filename)}
  2194. if record in self.recent:
  2195. return
  2196. if record in self.recent_projects:
  2197. return
  2198. if record['kind'] == 'project':
  2199. self.recent_projects.insert(0, record)
  2200. else:
  2201. self.recent.insert(0, record)
  2202. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2203. self.recent.pop()
  2204. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2205. self.recent_projects.pop()
  2206. try:
  2207. f = open(self.data_path + '/recent.json', 'w')
  2208. except IOError:
  2209. App.log.error("Failed to open recent items file for writing.")
  2210. self.inform.emit('[ERROR_NOTCL] %s' %
  2211. _('Failed to open recent files file for writing.'))
  2212. return
  2213. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2214. f.close()
  2215. try:
  2216. fp = open(self.data_path + '/recent_projects.json', 'w')
  2217. except IOError:
  2218. App.log.error("Failed to open recent items file for writing.")
  2219. self.inform.emit('[ERROR_NOTCL] %s' %
  2220. _('Failed to open recent projects file for writing.'))
  2221. return
  2222. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2223. fp.close()
  2224. # Re-build the recent items menu
  2225. self.setup_recent_items()
  2226. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2227. """
  2228. Creates a new specialized FlatCAMObj and attaches it to the application,
  2229. this is, updates the GUI accordingly, any other records and plots it.
  2230. This method is thread-safe.
  2231. Notes:
  2232. * If the name is in use, the self.collection will modify it
  2233. when appending it to the collection. There is no need to handle
  2234. name conflicts here.
  2235. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2236. :type kind: str
  2237. :param name: Name for the object.
  2238. :type name: str
  2239. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2240. The function is called with 2 parameters: the new object and the App instance.
  2241. :type initialize: function
  2242. :param active:
  2243. :param fit:
  2244. :param plot: If to plot the resulting object
  2245. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2246. self.collection
  2247. :return: None
  2248. :rtype: None
  2249. """
  2250. App.log.debug("new_object()")
  2251. obj_plot = plot
  2252. obj_autoselected = autoselected
  2253. t0 = time.time() # Debug
  2254. # ## Create object
  2255. classdict = {
  2256. "gerber": GerberObject,
  2257. "excellon": ExcellonObject,
  2258. "cncjob": CNCJobObject,
  2259. "geometry": GeometryObject,
  2260. "script": ScriptObject,
  2261. "document": DocumentObject
  2262. }
  2263. App.log.debug("Calling object constructor...")
  2264. # Object creation/instantiation
  2265. obj = classdict[kind](name)
  2266. obj.units = self.options["units"]
  2267. # IMPORTANT
  2268. # The key names in defaults and options dictionary's are not random:
  2269. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2270. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2271. # copied to self.options. After that, below, depending on the type of
  2272. # object that is created, it will strip the name of the object and the underline (if the original key was
  2273. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2274. # "toolchange"
  2275. for option in self.options:
  2276. if option.find(kind + "_") == 0:
  2277. oname = option[len(kind) + 1:]
  2278. obj.options[oname] = self.options[option]
  2279. obj.isHovering = False
  2280. obj.notHovering = True
  2281. # Initialize as per user request
  2282. # User must take care to implement initialize
  2283. # in a thread-safe way as is is likely that we
  2284. # have been invoked in a separate thread.
  2285. t1 = time.time()
  2286. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2287. try:
  2288. return_value = initialize(obj, self)
  2289. except Exception as e:
  2290. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2291. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2292. msg += traceback.format_exc()
  2293. self.inform.emit(msg)
  2294. return "fail"
  2295. t2 = time.time()
  2296. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2297. if return_value == 'fail':
  2298. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2299. return "fail"
  2300. # Check units and convert if necessary
  2301. # This condition CAN be true because initialize() can change obj.units
  2302. if self.options["units"].upper() != obj.units.upper():
  2303. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2304. obj.convert_units(self.options["units"])
  2305. t3 = time.time()
  2306. self.log.debug("%f seconds converting units." % (t3 - t2))
  2307. # Create the bounding box for the object and then add the results to the obj.options
  2308. # But not for Scripts or for Documents
  2309. if kind != 'document' and kind != 'script':
  2310. try:
  2311. xmin, ymin, xmax, ymax = obj.bounds()
  2312. obj.options['xmin'] = xmin
  2313. obj.options['ymin'] = ymin
  2314. obj.options['xmax'] = xmax
  2315. obj.options['ymax'] = ymax
  2316. except Exception as e:
  2317. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2318. return "fail"
  2319. try:
  2320. if kind == 'excellon':
  2321. obj.fill_color = self.defaults["excellon_plot_fill"]
  2322. obj.outline_color = self.defaults["excellon_plot_line"]
  2323. if kind == 'gerber':
  2324. obj.fill_color = self.defaults["gerber_plot_fill"]
  2325. obj.outline_color = self.defaults["gerber_plot_line"]
  2326. except Exception as e:
  2327. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2328. # update the KeyWords list with the name of the file
  2329. self.myKeywords.append(obj.options['name'])
  2330. log.debug("Moving new object back to main thread.")
  2331. # Move the object to the main thread and let the app know that it is available.
  2332. obj.moveToThread(self.main_thread)
  2333. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2334. return obj
  2335. def new_excellon_object(self):
  2336. """
  2337. Creates a new, blank Excellon object.
  2338. :return: None
  2339. """
  2340. self.defaults.report_usage("new_excellon_object()")
  2341. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2342. def new_geometry_object(self):
  2343. """
  2344. Creates a new, blank and single-tool Geometry object.
  2345. :return: None
  2346. """
  2347. self.defaults.report_usage("new_geometry_object()")
  2348. def initialize(obj, app):
  2349. obj.multitool = False
  2350. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2351. def new_gerber_object(self):
  2352. """
  2353. Creates a new, blank Gerber object.
  2354. :return: None
  2355. """
  2356. self.defaults.report_usage("new_gerber_object()")
  2357. def initialize(grb_obj, app):
  2358. grb_obj.multitool = False
  2359. grb_obj.source_file = []
  2360. grb_obj.multigeo = False
  2361. grb_obj.follow = False
  2362. grb_obj.apertures = {}
  2363. grb_obj.solid_geometry = []
  2364. try:
  2365. grb_obj.options['xmin'] = 0
  2366. grb_obj.options['ymin'] = 0
  2367. grb_obj.options['xmax'] = 0
  2368. grb_obj.options['ymax'] = 0
  2369. except KeyError:
  2370. pass
  2371. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2372. def new_script_object(self, name=None, text=None):
  2373. """
  2374. Creates a new, blank TCL Script object.
  2375. :param name: a name for the new object
  2376. :param text: pass a source file to the newly created script to be loaded in it
  2377. :return: None
  2378. """
  2379. self.defaults.report_usage("new_script_object()")
  2380. if text is not None:
  2381. new_source_file = text
  2382. else:
  2383. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2384. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2385. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2386. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2387. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2388. # "ListSys, MillDrills,\n" \
  2389. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2390. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2391. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2392. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2393. # "# SubtractRectangle, Version, WriteGCode\n"
  2394. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2395. '# %s:\n' % _('TCL Tutorial is here') + \
  2396. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2397. '# %s:\n' % _("FlatCAM commands list")
  2398. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2399. "(displayed in Tcl Shell).")
  2400. def initialize(obj, app):
  2401. obj.source_file = deepcopy(new_source_file)
  2402. if name is None:
  2403. outname = 'new_script'
  2404. else:
  2405. outname = name
  2406. self.new_object('script', outname, initialize, plot=False)
  2407. def new_document_object(self):
  2408. """
  2409. Creates a new, blank Document object.
  2410. :return: None
  2411. """
  2412. self.defaults.report_usage("new_document_object()")
  2413. def initialize(obj, app):
  2414. obj.source_file = ""
  2415. self.new_object('document', 'new_document', initialize, plot=False)
  2416. def on_object_created(self, obj, plot, auto_select):
  2417. """
  2418. Event callback for object creation.
  2419. It will add the new object to the collection. After that it will plot the object in a threaded way
  2420. :param obj: The newly created FlatCAM object.
  2421. :param plot: if the newly create object t obe plotted
  2422. :param auto_select: if the newly created object to be autoselected after creation
  2423. :return: None
  2424. """
  2425. t0 = time.time() # DEBUG
  2426. self.log.debug("on_object_created()")
  2427. # The Collection might change the name if there is a collision
  2428. self.collection.append(obj)
  2429. # after adding the object to the collection always update the list of objects that are in the collection
  2430. self.all_objects_list = self.collection.get_list()
  2431. # self.inform.emit('[selected] %s created & selected: %s' %
  2432. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2433. if obj.kind == 'gerber':
  2434. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2435. kind=obj.kind.capitalize(),
  2436. color='green',
  2437. name=str(obj.options['name']), tx=_("created/selected"))
  2438. )
  2439. elif obj.kind == 'excellon':
  2440. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2441. kind=obj.kind.capitalize(),
  2442. color='brown',
  2443. name=str(obj.options['name']), tx=_("created/selected"))
  2444. )
  2445. elif obj.kind == 'cncjob':
  2446. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2447. kind=obj.kind.capitalize(),
  2448. color='blue',
  2449. name=str(obj.options['name']), tx=_("created/selected"))
  2450. )
  2451. elif obj.kind == 'geometry':
  2452. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2453. kind=obj.kind.capitalize(),
  2454. color='red',
  2455. name=str(obj.options['name']), tx=_("created/selected"))
  2456. )
  2457. elif obj.kind == 'script':
  2458. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2459. kind=obj.kind.capitalize(),
  2460. color='orange',
  2461. name=str(obj.options['name']), tx=_("created/selected"))
  2462. )
  2463. elif obj.kind == 'document':
  2464. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2465. kind=obj.kind.capitalize(),
  2466. color='darkCyan',
  2467. name=str(obj.options['name']), tx=_("created/selected"))
  2468. )
  2469. # update the SHELL auto-completer model with the name of the new object
  2470. self.shell._edit.set_model_data(self.myKeywords)
  2471. if auto_select:
  2472. # select the just opened object but deselect the previous ones
  2473. self.collection.set_all_inactive()
  2474. self.collection.set_active(obj.options["name"])
  2475. else:
  2476. self.collection.set_all_inactive()
  2477. # here it is done the object plotting
  2478. def worker_task(t_obj):
  2479. with self.proc_container.new(_("Plotting")):
  2480. if isinstance(t_obj, CNCJobObject):
  2481. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2482. else:
  2483. t_obj.plot()
  2484. t1 = time.time() # DEBUG
  2485. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2486. self.object_plotted.emit(t_obj)
  2487. # Send to worker
  2488. # self.worker.add_task(worker_task, [self])
  2489. if plot is True:
  2490. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2491. def on_object_changed(self, obj):
  2492. """
  2493. Called whenever the geometry of the object was changed in some way.
  2494. This require the update of it's bounding values so it can be the selected on canvas.
  2495. Update the bounding box data from obj.options
  2496. :param obj: the object that was changed
  2497. :return: None
  2498. """
  2499. xmin, ymin, xmax, ymax = obj.bounds()
  2500. obj.options['xmin'] = xmin
  2501. obj.options['ymin'] = ymin
  2502. obj.options['xmax'] = xmax
  2503. obj.options['ymax'] = ymax
  2504. log.debug("Object changed, updating the bounding box data on self.options")
  2505. # delete the old selection shape
  2506. self.delete_selection_shape()
  2507. self.should_we_save = True
  2508. def on_object_plotted(self):
  2509. """
  2510. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2511. :return: None
  2512. """
  2513. self.on_zoom_fit(None)
  2514. def on_about(self):
  2515. """
  2516. Displays the "about" dialog found in the Menu --> Help.
  2517. :return: None
  2518. """
  2519. self.defaults.report_usage("on_about")
  2520. version = self.version
  2521. version_date = self.version_date
  2522. beta = self.beta
  2523. class AboutDialog(QtWidgets.QDialog):
  2524. def __init__(self, app, parent=None):
  2525. QtWidgets.QDialog.__init__(self, parent)
  2526. self.app = app
  2527. # Icon and title
  2528. self.setWindowIcon(parent.app_icon)
  2529. self.setWindowTitle(_("About FlatCAM"))
  2530. self.resize(600, 200)
  2531. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2532. # self.setStyleSheet(
  2533. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2534. # "background-attachment: fixed"
  2535. # )
  2536. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2537. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2538. # palette = QtGui.QPalette()
  2539. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2540. # self.setPalette(palette)
  2541. logo = QtWidgets.QLabel()
  2542. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2543. title = QtWidgets.QLabel(
  2544. "<font size=8><B>FlatCAM</B></font><BR>"
  2545. "{title}<BR>"
  2546. "<BR>"
  2547. "<BR>"
  2548. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2549. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2550. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2551. "<B>{issue}</B></a><BR>".format(
  2552. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2553. devel=_("Development"),
  2554. down=_("DOWNLOAD"),
  2555. issue=_("Issue tracker"))
  2556. )
  2557. title.setOpenExternalLinks(True)
  2558. closebtn = QtWidgets.QPushButton(_("Close"))
  2559. tab_widget = QtWidgets.QTabWidget()
  2560. description_label = QtWidgets.QLabel(
  2561. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2562. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2563. version=version,
  2564. beta=('BETA' if beta else ''),
  2565. date=version_date,
  2566. arch=platform.architecture()[0])
  2567. )
  2568. description_label.setOpenExternalLinks(True)
  2569. lic_lbl_header = QtWidgets.QLabel(
  2570. '%s:<br>%s<br>' % (
  2571. _('Licensed under the MIT license'),
  2572. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2573. "http://www.opensource.org/licenses/mit-license.php</a>"
  2574. )
  2575. )
  2576. lic_lbl_header.setOpenExternalLinks(True)
  2577. lic_lbl_body = QtWidgets.QLabel(
  2578. _(
  2579. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2580. 'of this software and associated documentation files (the "Software"), to deal\n'
  2581. 'in the Software without restriction, including without limitation the rights\n'
  2582. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2583. 'copies of the Software, and to permit persons to whom the Software is\n'
  2584. 'furnished to do so, subject to the following conditions:\n\n'
  2585. 'The above copyright notice and this permission notice shall be included in\n'
  2586. 'all copies or substantial portions of the Software.\n\n'
  2587. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2588. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2589. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2590. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2591. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2592. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2593. 'THE SOFTWARE.'
  2594. )
  2595. )
  2596. attributions_label = QtWidgets.QLabel(
  2597. _(
  2598. 'Some of the icons used are from the following sources:<br>'
  2599. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2600. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2601. 'title="Flaticon">www.flaticon.com</a></div>'
  2602. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2603. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2604. )
  2605. )
  2606. attributions_label.setOpenExternalLinks(True)
  2607. # layouts
  2608. layout1 = QtWidgets.QVBoxLayout()
  2609. layout1_1 = QtWidgets.QHBoxLayout()
  2610. layout1_2 = QtWidgets.QHBoxLayout()
  2611. layout2 = QtWidgets.QHBoxLayout()
  2612. layout3 = QtWidgets.QHBoxLayout()
  2613. self.setLayout(layout1)
  2614. layout1.addLayout(layout1_1)
  2615. layout1.addLayout(layout1_2)
  2616. layout1.addLayout(layout2)
  2617. layout1.addLayout(layout3)
  2618. layout1_1.addStretch()
  2619. layout1_1.addWidget(description_label)
  2620. layout1_2.addWidget(tab_widget)
  2621. self.splash_tab = QtWidgets.QWidget()
  2622. self.splash_tab.setObjectName("splash_about")
  2623. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2624. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2625. tab_widget.addTab(self.splash_tab, _("Splash"))
  2626. self.programmmers_tab = QtWidgets.QWidget()
  2627. self.programmmers_tab.setObjectName("programmers_about")
  2628. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2629. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2630. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2631. self.translators_tab = QtWidgets.QWidget()
  2632. self.translators_tab.setObjectName("translators_about")
  2633. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2634. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2635. tab_widget.addTab(self.translators_tab, _("Translators"))
  2636. self.license_tab = QtWidgets.QWidget()
  2637. self.license_tab.setObjectName("license_about")
  2638. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2639. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2640. tab_widget.addTab(self.license_tab, _("License"))
  2641. self.attributions_tab = QtWidgets.QWidget()
  2642. self.attributions_tab.setObjectName("attributions_about")
  2643. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2644. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2645. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2646. self.splash_tab_layout.addWidget(logo, stretch=0)
  2647. self.splash_tab_layout.addWidget(title, stretch=1)
  2648. pal = QtGui.QPalette()
  2649. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2650. self.prog_grid_lay = QtWidgets.QGridLayout()
  2651. self.prog_grid_lay.setHorizontalSpacing(20)
  2652. self.prog_grid_lay.setColumnStretch(0, 0)
  2653. self.prog_grid_lay.setColumnStretch(2, 1)
  2654. prog_widget = QtWidgets.QWidget()
  2655. prog_widget.setLayout(self.prog_grid_lay)
  2656. prog_scroll = QtWidgets.QScrollArea()
  2657. prog_scroll.setWidget(prog_widget)
  2658. prog_scroll.setWidgetResizable(True)
  2659. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2660. prog_scroll.setPalette(pal)
  2661. self.programmmers_tab_layout.addWidget(prog_scroll)
  2662. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2663. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2664. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2665. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2704. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2705. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2706. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2707. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2708. self.translator_grid_lay = QtWidgets.QGridLayout()
  2709. self.translator_grid_lay.setColumnStretch(0, 0)
  2710. self.translator_grid_lay.setColumnStretch(1, 0)
  2711. self.translator_grid_lay.setColumnStretch(2, 1)
  2712. self.translator_grid_lay.setColumnStretch(3, 0)
  2713. # trans_widget = QtWidgets.QWidget()
  2714. # trans_widget.setLayout(self.translator_grid_lay)
  2715. # self.translators_tab_layout.addWidget(trans_widget)
  2716. # self.translators_tab_layout.addStretch()
  2717. trans_widget = QtWidgets.QWidget()
  2718. trans_widget.setLayout(self.translator_grid_lay)
  2719. trans_scroll = QtWidgets.QScrollArea()
  2720. trans_scroll.setWidget(trans_widget)
  2721. trans_scroll.setWidgetResizable(True)
  2722. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2723. trans_scroll.setPalette(pal)
  2724. self.translators_tab_layout.addWidget(trans_scroll)
  2725. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2726. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2727. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2728. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  2750. self.translator_grid_lay.setColumnStretch(0, 0)
  2751. self.translators_tab_layout.addStretch()
  2752. self.license_tab_layout.addWidget(lic_lbl_header)
  2753. self.license_tab_layout.addWidget(lic_lbl_body)
  2754. self.license_tab_layout.addStretch()
  2755. self.attributions_tab_layout.addWidget(attributions_label)
  2756. self.attributions_tab_layout.addStretch()
  2757. layout3.addStretch()
  2758. layout3.addWidget(closebtn)
  2759. closebtn.clicked.connect(self.accept)
  2760. AboutDialog(app=self, parent=self.ui).exec_()
  2761. def install_bookmarks(self, book_dict=None):
  2762. """
  2763. Install the bookmarks actions in the Help menu -> Bookmarks
  2764. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2765. :return: None
  2766. """
  2767. if book_dict is None:
  2768. self.defaults["global_bookmarks"].update(
  2769. {
  2770. '1': ['FlatCAM', "http://flatcam.org"],
  2771. '2': ['Backup Site', ""]
  2772. }
  2773. )
  2774. else:
  2775. self.defaults["global_bookmarks"].clear()
  2776. self.defaults["global_bookmarks"].update(book_dict)
  2777. # first try to disconnect if somehow they get connected from elsewhere
  2778. for act in self.ui.menuhelp_bookmarks.actions():
  2779. try:
  2780. act.triggered.disconnect()
  2781. except TypeError:
  2782. pass
  2783. # clear all actions except the last one who is the Bookmark manager
  2784. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2785. pass
  2786. else:
  2787. self.ui.menuhelp_bookmarks.removeAction(act)
  2788. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2789. if self.defaults["global_bookmarks"]:
  2790. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2791. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2792. # the JSON is first making the keys as strings (therefore I have to use strings too
  2793. # or do the conversion :(
  2794. # )
  2795. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2796. # the '10' entry jsut after '1' therefore ordering as strings
  2797. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2798. key=lambda x: int(x[0]))
  2799. for entry, bookmark in sorted_bookmarks:
  2800. title = bookmark[0]
  2801. weblink = bookmark[1]
  2802. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2803. act.setText(title)
  2804. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2805. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2806. if title == 'Backup Site' and weblink == "":
  2807. act.triggered.connect(self.on_backup_site)
  2808. else:
  2809. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2810. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2811. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2812. def on_bookmarks_manager(self):
  2813. """
  2814. Adds the bookmark manager in a Tab in Plot Area
  2815. :return:
  2816. """
  2817. for idx in range(self.ui.plot_tab_area.count()):
  2818. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2819. # there can be only one instance of Bookmark Manager at one time
  2820. return
  2821. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2822. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2823. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2824. # add the tab if it was closed
  2825. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2826. # delete the absolute and relative position and messages in the infobar
  2827. self.ui.position_label.setText("")
  2828. self.ui.rel_position_label.setText("")
  2829. # Switch plot_area to preferences page
  2830. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2831. def on_backup_site(self):
  2832. msgbox = QtWidgets.QMessageBox()
  2833. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2834. "1. FlatCAM.org website is down\n"
  2835. "2. Someone forked FlatCAM project and wants to point\n"
  2836. "to his own website\n\n"
  2837. "If you can't get any informations about FlatCAM beta\n"
  2838. "use the YouTube channel link from the Help menu."))
  2839. msgbox.setWindowTitle(_("Alternative website"))
  2840. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2841. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2842. msgbox.setDefaultButton(bt_yes)
  2843. msgbox.exec_()
  2844. # response = msgbox.clickedButton()
  2845. def on_file_savedefaults(self):
  2846. """
  2847. Callback for menu item File->Save Defaults. Saves application default options
  2848. ``self.defaults`` to current_defaults.FlatConfig.
  2849. :return: None
  2850. """
  2851. self.preferencesUiManager.save_defaults()
  2852. def final_save(self):
  2853. """
  2854. Callback for doing a preferences save to file whenever the application is about to quit.
  2855. If the project has changes, it will ask the user to save the project.
  2856. :return: None
  2857. """
  2858. if self.save_in_progress:
  2859. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2860. return
  2861. if self.should_we_save and self.collection.get_list():
  2862. msgbox = QtWidgets.QMessageBox()
  2863. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2864. "\n"
  2865. "Do you want to Save the project?"))
  2866. msgbox.setWindowTitle(_("Save changes"))
  2867. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2868. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2869. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2870. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2871. msgbox.setDefaultButton(bt_yes)
  2872. msgbox.exec_()
  2873. response = msgbox.clickedButton()
  2874. if response == bt_yes:
  2875. try:
  2876. self.trayIcon.hide()
  2877. except Exception:
  2878. pass
  2879. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2880. elif response == bt_no:
  2881. try:
  2882. self.trayIcon.hide()
  2883. except Exception:
  2884. pass
  2885. self.quit_application()
  2886. elif response == bt_cancel:
  2887. return
  2888. else:
  2889. try:
  2890. self.trayIcon.hide()
  2891. except Exception:
  2892. pass
  2893. self.quit_application()
  2894. def quit_application(self):
  2895. """
  2896. Called (as a pyslot or not) when the application is quit.
  2897. :return: None
  2898. """
  2899. self.preferencesUiManager.save_defaults(silent=True)
  2900. log.debug("App.quit_application() --> App Defaults saved.")
  2901. if self.cmd_line_headless != 1:
  2902. # save app state to file
  2903. stgs = QSettings("Open Source", "FlatCAM")
  2904. stgs.setValue('saved_gui_state', self.ui.saveState())
  2905. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2906. stgs.setValue(
  2907. 'language',
  2908. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2909. )
  2910. stgs.setValue(
  2911. 'notebook_font_size',
  2912. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2913. )
  2914. stgs.setValue(
  2915. 'axis_font_size',
  2916. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2917. )
  2918. stgs.setValue(
  2919. 'textbox_font_size',
  2920. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2921. )
  2922. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2923. stgs.setValue(
  2924. 'machinist',
  2925. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2926. )
  2927. # This will write the setting to the platform specific storage.
  2928. del stgs
  2929. log.debug("App.quit_application() --> App UI state saved.")
  2930. # try to quit the Socket opened by ArgsThread class
  2931. try:
  2932. self.new_launch.thread_exit = True
  2933. self.new_launch.listener.close()
  2934. except Exception as err:
  2935. log.debug("App.quit_application() --> %s" % str(err))
  2936. # try to quit the QThread that run ArgsThread class
  2937. try:
  2938. self.th.terminate()
  2939. except Exception as e:
  2940. log.debug("App.quit_application() --> %s" % str(e))
  2941. # terminate workers
  2942. self.workers.__del__()
  2943. # quit app by signalling for self.kill_app() method
  2944. # self.close_app_signal.emit()
  2945. QtWidgets.qApp.quit()
  2946. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2947. # we use the following command
  2948. # sys.exit(0)
  2949. os._exit(0) # fix to work with Python 3.8
  2950. @staticmethod
  2951. def kill_app():
  2952. # QtCore.QCoreApplication.quit()
  2953. QtWidgets.qApp.quit()
  2954. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2955. # we use the following command
  2956. sys.exit(0)
  2957. def on_portable_checked(self, state):
  2958. """
  2959. Callback called when the checkbox in Preferences GUI is checked.
  2960. It will set the application as portable by creating the preferences and recent files in the
  2961. 'config' folder found in the FlatCAM installation folder.
  2962. :param state: boolean, the state of the checkbox when clicked/checked
  2963. :return:
  2964. """
  2965. line_no = 0
  2966. data = None
  2967. if sys.platform != 'win32':
  2968. # this won't work in Linux or MacOS
  2969. return
  2970. # test if the app was frozen and choose the path for the configuration file
  2971. if getattr(sys, "frozen", False) is True:
  2972. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2973. else:
  2974. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2975. config_file = current_data_path + '\\configuration.txt'
  2976. try:
  2977. with open(config_file, 'r') as f:
  2978. try:
  2979. data = f.readlines()
  2980. except Exception as e:
  2981. log.debug('App.__init__() -->%s' % str(e))
  2982. return
  2983. except FileNotFoundError:
  2984. pass
  2985. for line in data:
  2986. line = line.strip('\n')
  2987. param = str(line).rpartition('=')
  2988. if param[0] == 'portable':
  2989. break
  2990. line_no += 1
  2991. if state:
  2992. data[line_no] = 'portable=True\n'
  2993. # create the new defauults files
  2994. # create current_defaults.FlatConfig file if there is none
  2995. try:
  2996. f = open(current_data_path + '/current_defaults.FlatConfig')
  2997. f.close()
  2998. except IOError:
  2999. App.log.debug('Creating empty current_defaults.FlatConfig')
  3000. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3001. json.dump({}, f)
  3002. f.close()
  3003. # create factory_defaults.FlatConfig file if there is none
  3004. try:
  3005. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3006. f.close()
  3007. except IOError:
  3008. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3009. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3010. json.dump({}, f)
  3011. f.close()
  3012. try:
  3013. f = open(current_data_path + '/recent.json')
  3014. f.close()
  3015. except IOError:
  3016. App.log.debug('Creating empty recent.json')
  3017. f = open(current_data_path + '/recent.json', 'w')
  3018. json.dump([], f)
  3019. f.close()
  3020. try:
  3021. fp = open(current_data_path + '/recent_projects.json')
  3022. fp.close()
  3023. except IOError:
  3024. App.log.debug('Creating empty recent_projects.json')
  3025. fp = open(current_data_path + '/recent_projects.json', 'w')
  3026. json.dump([], fp)
  3027. fp.close()
  3028. # save the current defaults to the new defaults file
  3029. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3030. else:
  3031. data[line_no] = 'portable=False\n'
  3032. with open(config_file, 'w') as f:
  3033. f.writelines(data)
  3034. def on_register_files(self, obj_type=None):
  3035. """
  3036. Called whenever there is a need to register file extensions with FlatCAM.
  3037. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3038. :param obj_type: the type of object to be register for.
  3039. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3040. :return: None
  3041. """
  3042. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3043. new_reg_path = 'Software\\Classes\\'
  3044. # find if the current user is admin
  3045. try:
  3046. is_admin = os.getuid() == 0
  3047. except AttributeError:
  3048. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3049. if is_admin is True:
  3050. root_path = winreg.HKEY_LOCAL_MACHINE
  3051. else:
  3052. root_path = winreg.HKEY_CURRENT_USER
  3053. # create the keys
  3054. def set_reg(name, root_pth, new_reg_path, value):
  3055. try:
  3056. winreg.CreateKey(root_pth, new_reg_path)
  3057. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3058. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3059. return True
  3060. except WindowsError:
  3061. return False
  3062. # delete key in registry
  3063. def delete_reg(root_pth, reg_path, key_to_del):
  3064. key_to_del_path = reg_path + key_to_del
  3065. try:
  3066. winreg.DeleteKey(root_pth, key_to_del_path)
  3067. return True
  3068. except WindowsError:
  3069. return False
  3070. if obj_type is None or obj_type == 'excellon':
  3071. exc_list = \
  3072. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3073. exc_list = [x for x in exc_list if x != '']
  3074. # register all keys in the Preferences window
  3075. for ext in exc_list:
  3076. new_k = new_reg_path + '.%s' % ext
  3077. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3078. # and unregister those that are no longer in the Preferences windows but are in the file
  3079. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3080. if ext not in exc_list:
  3081. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3082. # now write the updated extensions to the self.defaults
  3083. # new_ext = ''
  3084. # for ext in exc_list:
  3085. # new_ext = new_ext + ext + ', '
  3086. # self.defaults["fa_excellon"] = new_ext
  3087. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3088. if obj_type is None or obj_type == 'gcode':
  3089. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3090. gco_list = [x for x in gco_list if x != '']
  3091. # register all keys in the Preferences window
  3092. for ext in gco_list:
  3093. new_k = new_reg_path + '.%s' % ext
  3094. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3095. # and unregister those that are no longer in the Preferences windows but are in the file
  3096. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3097. if ext not in gco_list:
  3098. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3099. # now write the updated extensions to the self.defaults
  3100. # new_ext = ''
  3101. # for ext in gco_list:
  3102. # new_ext = new_ext + ext + ', '
  3103. # self.defaults["fa_gcode"] = new_ext
  3104. self.inform.emit('[success] %s' %
  3105. _("Selected GCode file extensions registered with FlatCAM."))
  3106. if obj_type is None or obj_type == 'gerber':
  3107. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3108. grb_list = [x for x in grb_list if x != '']
  3109. # register all keys in the Preferences window
  3110. for ext in grb_list:
  3111. new_k = new_reg_path + '.%s' % ext
  3112. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3113. # and unregister those that are no longer in the Preferences windows but are in the file
  3114. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3115. if ext not in grb_list:
  3116. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3117. # now write the updated extensions to the self.defaults
  3118. # new_ext = ''
  3119. # for ext in grb_list:
  3120. # new_ext = new_ext + ext + ', '
  3121. # self.defaults["fa_gerber"] = new_ext
  3122. self.inform.emit('[success] %s' %
  3123. _("Selected Gerber file extensions registered with FlatCAM."))
  3124. def add_extension(self, ext_type):
  3125. """
  3126. Add a file extension to the list for a specific object
  3127. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3128. :return:
  3129. """
  3130. if ext_type == 'excellon':
  3131. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3132. if new_ext == '':
  3133. return
  3134. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3135. if new_ext in old_val:
  3136. return
  3137. old_val.append(new_ext)
  3138. old_val.sort()
  3139. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3140. if ext_type == 'gcode':
  3141. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3142. if new_ext == '':
  3143. return
  3144. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3145. if new_ext in old_val:
  3146. return
  3147. old_val.append(new_ext)
  3148. old_val.sort()
  3149. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3150. if ext_type == 'gerber':
  3151. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3152. if new_ext == '':
  3153. return
  3154. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3155. if new_ext in old_val:
  3156. return
  3157. old_val.append(new_ext)
  3158. old_val.sort()
  3159. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3160. if ext_type == 'keyword':
  3161. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3162. if new_kw == '':
  3163. return
  3164. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3165. if new_kw in old_val:
  3166. return
  3167. old_val.append(new_kw)
  3168. old_val.sort()
  3169. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3170. # update the self.myKeywords so the model is updated
  3171. self.autocomplete_kw_list = \
  3172. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3173. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3174. self.shell._edit.set_model_data(self.myKeywords)
  3175. def del_extension(self, ext_type):
  3176. """
  3177. Remove a file extension from the list for a specific object
  3178. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3179. :return:
  3180. """
  3181. if ext_type == 'excellon':
  3182. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3183. if new_ext == '':
  3184. return
  3185. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3186. if new_ext not in old_val:
  3187. return
  3188. old_val.remove(new_ext)
  3189. old_val.sort()
  3190. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3191. if ext_type == 'gcode':
  3192. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3193. if new_ext == '':
  3194. return
  3195. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3196. if new_ext not in old_val:
  3197. return
  3198. old_val.remove(new_ext)
  3199. old_val.sort()
  3200. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3201. if ext_type == 'gerber':
  3202. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3203. if new_ext == '':
  3204. return
  3205. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3206. if new_ext not in old_val:
  3207. return
  3208. old_val.remove(new_ext)
  3209. old_val.sort()
  3210. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3211. if ext_type == 'keyword':
  3212. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3213. if new_kw == '':
  3214. return
  3215. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3216. if new_kw not in old_val:
  3217. return
  3218. old_val.remove(new_kw)
  3219. old_val.sort()
  3220. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3221. # update the self.myKeywords so the model is updated
  3222. self.autocomplete_kw_list = \
  3223. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3224. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3225. self.shell._edit.set_model_data(self.myKeywords)
  3226. def restore_extensions(self, ext_type):
  3227. """
  3228. Restore all file extensions associations with FlatCAM, for a specific object
  3229. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3230. :return:
  3231. """
  3232. if ext_type == 'excellon':
  3233. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3234. # for the ability to open Excellon files with .txt extension
  3235. new_exc_list = deepcopy(self.exc_list)
  3236. try:
  3237. new_exc_list.remove('txt')
  3238. except ValueError:
  3239. pass
  3240. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3241. if ext_type == 'gcode':
  3242. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3243. if ext_type == 'gerber':
  3244. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3245. if ext_type == 'keyword':
  3246. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3247. # update the self.myKeywords so the model is updated
  3248. self.autocomplete_kw_list = self.default_keywords
  3249. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3250. self.shell._edit.set_model_data(self.myKeywords)
  3251. def delete_all_extensions(self, ext_type):
  3252. """
  3253. Delete all file extensions associations with FlatCAM, for a specific object
  3254. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3255. :return:
  3256. """
  3257. if ext_type == 'excellon':
  3258. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3259. if ext_type == 'gcode':
  3260. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3261. if ext_type == 'gerber':
  3262. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3263. if ext_type == 'keyword':
  3264. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3265. # update the self.myKeywords so the model is updated
  3266. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3267. self.shell._edit.set_model_data(self.myKeywords)
  3268. def on_edit_join(self, name=None):
  3269. """
  3270. Callback for Edit->Join. Joins the selected geometry objects into
  3271. a new one.
  3272. :return: None
  3273. """
  3274. self.defaults.report_usage("on_edit_join()")
  3275. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3276. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3277. geo_type_set = set()
  3278. objs = self.collection.get_selected()
  3279. if len(objs) < 2:
  3280. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3281. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3282. return 'fail'
  3283. for obj in objs:
  3284. geo_type_set.add(obj.multigeo)
  3285. # if len(geo_type_list) == 1 means that all list elements are the same
  3286. if len(geo_type_set) != 1:
  3287. self.inform.emit('[ERROR] %s' %
  3288. _("Failed join. The Geometry objects are of different types.\n"
  3289. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3290. "convert from one to another and retry joining \n"
  3291. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3292. "the result may not be what was expected. \n"
  3293. "Check the generated GCODE."))
  3294. return
  3295. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3296. if True in geo_type_set:
  3297. def initialize(geo_obj, app):
  3298. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3299. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3300. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3301. for v in geo_obj.tools.values():
  3302. v['data']['name'] = obj_name_multi
  3303. self.new_object("geometry", obj_name_multi, initialize)
  3304. else:
  3305. def initialize(geo_obj, app):
  3306. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3307. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3308. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3309. for v in geo_obj.tools.values():
  3310. v['data']['name'] = obj_name_single
  3311. self.new_object("geometry", obj_name_single, initialize)
  3312. self.should_we_save = True
  3313. def on_edit_join_exc(self):
  3314. """
  3315. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3316. a new Excellon.
  3317. :return: None
  3318. """
  3319. self.defaults.report_usage("on_edit_join_exc()")
  3320. objs = self.collection.get_selected()
  3321. for obj in objs:
  3322. if not isinstance(obj, ExcellonObject):
  3323. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3324. return
  3325. if len(objs) < 2:
  3326. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3327. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3328. return 'fail'
  3329. def initialize(exc_obj, app):
  3330. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3331. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3332. self.new_object("excellon", 'Combo_Excellon', initialize)
  3333. self.should_we_save = True
  3334. def on_edit_join_grb(self):
  3335. """
  3336. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3337. a new Gerber object.
  3338. :return: None
  3339. """
  3340. self.defaults.report_usage("on_edit_join_grb()")
  3341. objs = self.collection.get_selected()
  3342. for obj in objs:
  3343. if not isinstance(obj, GerberObject):
  3344. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3345. return
  3346. if len(objs) < 2:
  3347. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3348. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3349. return 'fail'
  3350. def initialize(grb_obj, app):
  3351. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3352. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3353. self.new_object("gerber", 'Combo_Gerber', initialize)
  3354. self.should_we_save = True
  3355. def on_convert_singlegeo_to_multigeo(self):
  3356. """
  3357. Called for converting a Geometry object from single-geo to multi-geo.
  3358. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3359. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3360. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3361. the solid-geometry of that tool.
  3362. :return: None
  3363. """
  3364. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3365. obj = self.collection.get_active()
  3366. if obj is None:
  3367. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3368. return
  3369. if not isinstance(obj, GeometryObject):
  3370. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3371. return
  3372. obj.multigeo = True
  3373. for tooluid, dict_value in obj.tools.items():
  3374. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3375. if not isinstance(obj.solid_geometry, list):
  3376. obj.solid_geometry = [obj.solid_geometry]
  3377. obj.solid_geometry[:] = []
  3378. obj.plot()
  3379. self.should_we_save = True
  3380. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3381. def on_convert_multigeo_to_singlegeo(self):
  3382. """
  3383. Called for converting a Geometry object from multi-geo to single-geo.
  3384. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3385. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3386. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3387. the solid-geometry of that tool.
  3388. :return: None
  3389. """
  3390. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3391. obj = self.collection.get_active()
  3392. if obj is None:
  3393. self.inform.emit('[ERROR_NOTCL] %s' %
  3394. _("Failed. Select a Geometry Object and try again."))
  3395. return
  3396. if not isinstance(obj, GeometryObject):
  3397. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3398. (_("Expected a GeometryObject, got"), type(obj)))
  3399. return
  3400. obj.multigeo = False
  3401. total_solid_geometry = []
  3402. for tooluid, dict_value in obj.tools.items():
  3403. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3404. # clear the original geometry
  3405. dict_value['solid_geometry'][:] = []
  3406. obj.solid_geometry = deepcopy(total_solid_geometry)
  3407. obj.plot()
  3408. self.should_we_save = True
  3409. self.inform.emit('[success] %s' %
  3410. _("A Geometry object was converted to SingleGeo type."))
  3411. def on_defaults_dict_change(self, field):
  3412. """
  3413. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3414. Edit -> Preferences tab window.
  3415. :param field: the key of the self.defaults dictionary that was changed.
  3416. :return: None
  3417. """
  3418. self.preferencesUiManager.defaults_write_form_field(field=field)
  3419. if field == "units":
  3420. self.set_screen_units(self.defaults['units'])
  3421. def set_screen_units(self, units):
  3422. """
  3423. Set the FlatCAM units on the status bar.
  3424. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3425. :return: None
  3426. """
  3427. self.ui.units_label.setText("[" + units.lower() + "]")
  3428. def on_toggle_units_click(self):
  3429. try:
  3430. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3431. except (TypeError, AttributeError):
  3432. pass
  3433. if self.defaults["units"] == 'MM':
  3434. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3435. else:
  3436. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3437. self.on_toggle_units(no_pref=True)
  3438. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3439. lambda: self.on_toggle_units(no_pref=False))
  3440. def on_toggle_units(self, no_pref=False):
  3441. """
  3442. Callback for the Units radio-button change in the Preferences tab.
  3443. Changes the application's default units adn for the project too.
  3444. If changing the project's units, the change propagates to all of
  3445. the objects in the project.
  3446. :return: None
  3447. """
  3448. self.defaults.report_usage("on_toggle_units")
  3449. if self.toggle_units_ignore:
  3450. return
  3451. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3452. # If option is the same, then ignore
  3453. if new_units == self.defaults["units"].upper():
  3454. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3455. return
  3456. # Options to scale
  3457. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3458. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3459. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3460. "gerber_editor_ma_high",
  3461. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3462. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3463. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3464. "excellon_feedrate_probe", "excellon_milling_dia",
  3465. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3466. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3467. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3468. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3469. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3470. "geometry_extracut_length", "geometry_z_pdepth",
  3471. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3472. 'cncjob_tooldia',
  3473. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3474. "tools_paintnewdia",
  3475. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3476. "tools_nccnewdia", "tools_ncc_offset_value",
  3477. "tools_2sided_drilldia",
  3478. "tools_film_boundary", "tools_film_scale_stroke",
  3479. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3480. "tools_cutout_depthperpass",
  3481. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3482. "tools_panelize_spacing_rows",
  3483. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3484. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3485. "tools_transform_buffer_dis",
  3486. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3487. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3488. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3489. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3490. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3491. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3492. "tools_cr_h2h_val", "tools_cr_dh_val",
  3493. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3494. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3495. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3496. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3497. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3498. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3499. "tools_copper_thieving_mask_clearance",
  3500. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3501. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3502. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3503. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3504. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3505. "tools_invert_margin",
  3506. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3507. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3508. def scale_defaults(sfactor):
  3509. for dim in dimensions:
  3510. if dim == 'gerber_editor_newdim':
  3511. if self.defaults["gerber_editor_newdim"] is None or self.defaults["gerber_editor_newdim"] == '':
  3512. continue
  3513. coordinates = self.defaults["gerber_editor_newdim"].split(",")
  3514. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3515. coords_xy[0] *= sfactor
  3516. coords_xy[1] *= sfactor
  3517. self.defaults['gerber_editor_newdim'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3518. self.decimals, coords_xy[1])
  3519. if dim == 'excellon_toolchangexy':
  3520. if self.defaults["excellon_toolchangexy"] is None or self.defaults["excellon_toolchangexy"] == '':
  3521. continue
  3522. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3523. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3524. coords_xy[0] *= sfactor
  3525. coords_xy[1] *= sfactor
  3526. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3527. self.decimals, coords_xy[1])
  3528. elif dim == 'geometry_toolchangexy':
  3529. if self.defaults["geometry_toolchangexy"] is None or self.defaults["geometry_toolchangexy"] == '':
  3530. continue
  3531. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3532. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3533. coords_xy[0] *= sfactor
  3534. coords_xy[1] *= sfactor
  3535. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3536. self.decimals, coords_xy[1])
  3537. elif dim == 'excellon_endxy':
  3538. if self.defaults["excellon_endxy"] is None or self.defaults["excellon_endxy"] == '':
  3539. continue
  3540. coordinates = self.defaults["excellon_endxy"].split(",")
  3541. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3542. end_coords_xy[0] *= sfactor
  3543. end_coords_xy[1] *= sfactor
  3544. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3545. self.decimals, end_coords_xy[1])
  3546. elif dim == 'geometry_endxy':
  3547. if self.defaults["geometry_endxy"] is None or self.defaults["geometry_endxy"] == '':
  3548. continue
  3549. coordinates = self.defaults["geometry_endxy"].split(",")
  3550. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3551. end_coords_xy[0] *= sfactor
  3552. end_coords_xy[1] *= sfactor
  3553. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3554. self.decimals, end_coords_xy[1])
  3555. elif dim == 'geometry_cnctooldia':
  3556. if self.defaults["geometry_cnctooldia"] is None or self.defaults["geometry_cnctooldia"] == '':
  3557. continue
  3558. if type(self.defaults["geometry_cnctooldia"]) is float:
  3559. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  3560. else:
  3561. try:
  3562. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3563. tools_diameters = [eval(a) for a in tools_string if a != '']
  3564. except Exception as e:
  3565. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3566. continue
  3567. self.defaults['geometry_cnctooldia'] = ''
  3568. for t in range(len(tools_diameters)):
  3569. tools_diameters[t] *= sfactor
  3570. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  3571. elif dim == 'tools_ncctools':
  3572. if self.defaults["tools_ncctools"] is None or self.defaults["tools_ncctools"] == '':
  3573. continue
  3574. if type(self.defaults["tools_ncctools"]) == float:
  3575. ncctools = [self.defaults["tools_ncctools"]]
  3576. else:
  3577. try:
  3578. tools_string = self.defaults["tools_ncctools"].split(",")
  3579. ncctools = [eval(a) for a in tools_string if a != '']
  3580. except Exception as e:
  3581. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3582. continue
  3583. self.defaults['tools_ncctools'] = ''
  3584. for t in range(len(ncctools)):
  3585. ncctools[t] *= sfactor
  3586. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  3587. elif dim == 'tools_solderpaste_tools':
  3588. if self.defaults["tools_solderpaste_tools"] is None or \
  3589. self.defaults["tools_solderpaste_tools"] == '':
  3590. continue
  3591. if type(self.defaults["tools_solderpaste_tools"]) == float:
  3592. sptools = [self.defaults["tools_solderpaste_tools"]]
  3593. else:
  3594. try:
  3595. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3596. sptools = [eval(a) for a in tools_string if a != '']
  3597. except Exception as e:
  3598. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3599. continue
  3600. self.defaults['tools_solderpaste_tools'] = ""
  3601. for t in range(len(sptools)):
  3602. sptools[t] *= sfactor
  3603. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  3604. elif dim == 'tools_solderpaste_xy_toolchange':
  3605. if self.defaults["tools_solderpaste_xy_toolchange"] is None or \
  3606. self.defaults["tools_solderpaste_xy_toolchange"] == '':
  3607. continue
  3608. try:
  3609. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3610. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3611. sp_coords[0] *= sfactor
  3612. sp_coords[1] *= sfactor
  3613. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  3614. self.decimals, sp_coords[1])
  3615. except Exception as e:
  3616. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3617. continue
  3618. elif dim == 'tools_cal_toolchange_xy':
  3619. if self.defaults["tools_cal_toolchange_xy"] is None or \
  3620. self.defaults["tools_cal_toolchange_xy"] == '':
  3621. continue
  3622. coordinates = self.defaults["tools_cal_toolchange_xy"].split(",")
  3623. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3624. end_coords_xy[0] *= sfactor
  3625. end_coords_xy[1] *= sfactor
  3626. self.defaults['tools_cal_toolchange_xy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3627. self.decimals, end_coords_xy[1])
  3628. elif dim == 'global_gridx' or dim == 'global_gridy':
  3629. if new_units == 'IN':
  3630. try:
  3631. val = float(self.defaults[dim]) * sfactor
  3632. except Exception as e:
  3633. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3634. continue
  3635. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3636. else:
  3637. try:
  3638. val = float(self.defaults[dim]) * sfactor
  3639. except Exception as e:
  3640. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3641. continue
  3642. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3643. else:
  3644. if self.defaults[dim]:
  3645. try:
  3646. val = float(self.defaults[dim]) * sfactor
  3647. except Exception as e:
  3648. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3649. continue
  3650. self.defaults[dim] = val
  3651. # The scaling factor depending on choice of units.
  3652. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3653. # Changing project units. Warn user.
  3654. msgbox = QtWidgets.QMessageBox()
  3655. msgbox.setWindowTitle(_("Toggle Units"))
  3656. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3657. msgbox.setText(_("Changing the units of the project\n"
  3658. "will scale all objects.\n\n"
  3659. "Do you want to continue?"))
  3660. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3661. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3662. msgbox.setDefaultButton(bt_ok)
  3663. msgbox.exec_()
  3664. response = msgbox.clickedButton()
  3665. if response == bt_ok:
  3666. if no_pref is False:
  3667. self.preferencesUiManager.defaults_read_form()
  3668. scale_defaults(factor)
  3669. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3670. self.defaults["units"] = new_units
  3671. # update the defaults from form, some may assume that the conversion is enough and it's not
  3672. self.on_options_app2project()
  3673. # update the objects
  3674. for obj in self.collection.get_list():
  3675. obj.convert_units(new_units)
  3676. # make that the properties stored in the object are also updated
  3677. self.object_changed.emit(obj)
  3678. # rebuild the object UI
  3679. obj.build_ui()
  3680. # change this only if the workspace is active
  3681. if self.defaults['global_workspace'] is True:
  3682. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3683. # adjust the grid values on the main toolbar
  3684. val_x = float(self.defaults['global_gridx']) * factor
  3685. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3686. current = self.collection.get_active()
  3687. if current is not None:
  3688. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3689. if not isinstance(current, GeometryObject):
  3690. current.to_form()
  3691. # replot all objects
  3692. self.plot_all()
  3693. # set the status labels to reflect the current FlatCAM units
  3694. self.set_screen_units(new_units)
  3695. # signal to the app that we changed the object properties and it shoud save the project
  3696. self.should_we_save = True
  3697. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3698. else:
  3699. # Undo toggling
  3700. self.toggle_units_ignore = True
  3701. if self.defaults['units'].upper() == 'MM':
  3702. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3703. else:
  3704. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3705. self.toggle_units_ignore = False
  3706. # store the grid values so they are not changed in the next step
  3707. val_x = float(self.defaults['global_gridx'])
  3708. val_y = float(self.defaults['global_gridy'])
  3709. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3710. self.preferencesUiManager.defaults_read_form()
  3711. # the self.preferencesUiManager.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  3712. # I don't want it for the grid values, so I update them here
  3713. self.defaults['global_gridx'] = val_x
  3714. self.defaults['global_gridy'] = val_y
  3715. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3716. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3717. def on_fullscreen(self, disable=False):
  3718. self.defaults.report_usage("on_fullscreen()")
  3719. flags = self.ui.windowFlags()
  3720. if self.toggle_fscreen is False and disable is False:
  3721. # self.ui.showFullScreen()
  3722. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3723. a = self.ui.geometry()
  3724. self.x_pos = a.x()
  3725. self.y_pos = a.y()
  3726. self.width = a.width()
  3727. self.height = a.height()
  3728. # set new geometry to full desktop rect
  3729. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3730. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3731. # everything else will not work without this hack. This happen in Windows.
  3732. # https://bugreports.qt.io/browse/QTBUG-41309
  3733. desktop = QtWidgets.QApplication.desktop()
  3734. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3735. rec = desktop.screenGeometry(screen)
  3736. x = rec.x() - 1
  3737. y = rec.y() - 1
  3738. h = rec.height() + 2
  3739. w = rec.width() + 2
  3740. self.ui.setGeometry(x, y, w, h)
  3741. self.ui.show()
  3742. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3743. tb.setVisible(False)
  3744. self.ui.splitter_left.setVisible(False)
  3745. self.toggle_fscreen = True
  3746. elif self.toggle_fscreen is True or disable is True:
  3747. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3748. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3749. self.ui.showNormal()
  3750. self.restore_toolbar_view()
  3751. self.ui.splitter_left.setVisible(True)
  3752. self.toggle_fscreen = False
  3753. def on_toggle_plotarea(self):
  3754. self.defaults.report_usage("on_toggle_plotarea()")
  3755. try:
  3756. name = self.ui.plot_tab_area.widget(0).objectName()
  3757. except AttributeError:
  3758. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3759. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3760. self.ui.plot_tab_area.protectTab(0)
  3761. return
  3762. if name != 'plotarea':
  3763. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3764. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3765. self.ui.plot_tab_area.protectTab(0)
  3766. else:
  3767. self.ui.plot_tab_area.closeTab(0)
  3768. def on_toggle_notebook(self):
  3769. if self.ui.splitter.sizes()[0] == 0:
  3770. self.ui.splitter.setSizes([1, 1])
  3771. self.ui.menu_toggle_nb.setChecked(True)
  3772. else:
  3773. self.ui.splitter.setSizes([0, 1])
  3774. self.ui.menu_toggle_nb.setChecked(False)
  3775. def on_toggle_axis(self):
  3776. self.defaults.report_usage("on_toggle_axis()")
  3777. if self.toggle_axis is False:
  3778. if self.is_legacy is False:
  3779. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3780. parent=self.plotcanvas.view.scene)
  3781. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3782. parent=self.plotcanvas.view.scene)
  3783. else:
  3784. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3785. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3786. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3787. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3788. self.plotcanvas.canvas.draw()
  3789. self.toggle_axis = True
  3790. else:
  3791. if self.is_legacy is False:
  3792. self.plotcanvas.v_line.parent = None
  3793. self.plotcanvas.h_line.parent = None
  3794. else:
  3795. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3796. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3797. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3798. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3799. self.plotcanvas.canvas.draw()
  3800. self.toggle_axis = False
  3801. def on_toggle_grid(self):
  3802. self.defaults.report_usage("on_toggle_grid()")
  3803. self.ui.grid_snap_btn.trigger()
  3804. self.on_grid_snap_triggered(state=True)
  3805. def on_toggle_grid_lines(self):
  3806. self.defaults.report_usage("on_toggle_grd_lines()")
  3807. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3808. if tt_settings.contains("theme"):
  3809. theme = tt_settings.value('theme', type=str)
  3810. else:
  3811. theme = 'white'
  3812. if self.toggle_grid_lines is False:
  3813. if self.is_legacy is False:
  3814. if theme == 'white':
  3815. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3816. else:
  3817. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3818. else:
  3819. self.plotcanvas.axes.grid(True)
  3820. try:
  3821. self.plotcanvas.canvas.draw()
  3822. except IndexError:
  3823. pass
  3824. pass
  3825. self.toggle_grid_lines = True
  3826. else:
  3827. if self.is_legacy is False:
  3828. if theme == 'white':
  3829. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3830. else:
  3831. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3832. else:
  3833. self.plotcanvas.axes.grid(False)
  3834. try:
  3835. self.plotcanvas.canvas.draw()
  3836. except IndexError:
  3837. pass
  3838. self.toggle_grid_lines = False
  3839. if self.is_legacy is False:
  3840. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3841. # - perhaps is a bug in VisPy implementation
  3842. if self.grid_status() is True:
  3843. self.app_cursor.enabled = False
  3844. self.app_cursor.enabled = True
  3845. else:
  3846. self.app_cursor.enabled = True
  3847. self.app_cursor.enabled = False
  3848. def on_update_exc_export(self, state):
  3849. """
  3850. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3851. if the update_excellon_cb checkbox is checked
  3852. :param state: state of the checkbox whose signals is tied to his slot
  3853. :return:
  3854. """
  3855. if state:
  3856. # first try to disconnect
  3857. try:
  3858. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3859. disconnect(self.on_excellon_format_changed)
  3860. except TypeError:
  3861. pass
  3862. try:
  3863. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3864. disconnect(self.on_excellon_format_changed)
  3865. except TypeError:
  3866. pass
  3867. try:
  3868. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3869. disconnect(self.on_excellon_format_changed)
  3870. except TypeError:
  3871. pass
  3872. try:
  3873. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3874. disconnect(self.on_excellon_format_changed)
  3875. except TypeError:
  3876. pass
  3877. try:
  3878. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3879. disconnect(self.on_excellon_zeros_changed)
  3880. except TypeError:
  3881. pass
  3882. try:
  3883. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3884. disconnect(self.on_excellon_zeros_changed)
  3885. except TypeError:
  3886. pass
  3887. # the connect them
  3888. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3889. self.on_excellon_format_changed)
  3890. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3891. self.on_excellon_format_changed)
  3892. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3893. self.on_excellon_format_changed)
  3894. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3895. self.on_excellon_format_changed)
  3896. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3897. self.on_excellon_zeros_changed)
  3898. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3899. self.on_excellon_units_changed)
  3900. else:
  3901. # disconnect the signals
  3902. try:
  3903. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3904. disconnect(self.on_excellon_format_changed)
  3905. except TypeError:
  3906. pass
  3907. try:
  3908. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3909. disconnect(self.on_excellon_format_changed)
  3910. except TypeError:
  3911. pass
  3912. try:
  3913. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3914. disconnect(self.on_excellon_format_changed)
  3915. except TypeError:
  3916. pass
  3917. try:
  3918. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3919. disconnect(self.on_excellon_format_changed)
  3920. except TypeError:
  3921. pass
  3922. try:
  3923. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3924. disconnect(self.on_excellon_zeros_changed)
  3925. except TypeError:
  3926. pass
  3927. try:
  3928. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3929. disconnect(self.on_excellon_zeros_changed)
  3930. except TypeError:
  3931. pass
  3932. def on_excellon_format_changed(self):
  3933. """
  3934. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3935. :return: None
  3936. """
  3937. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3938. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3939. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3940. )
  3941. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3942. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3943. )
  3944. else:
  3945. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3946. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3947. )
  3948. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3949. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3950. )
  3951. def on_excellon_zeros_changed(self):
  3952. """
  3953. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3954. :return: None
  3955. """
  3956. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3957. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3958. )
  3959. def on_excellon_units_changed(self):
  3960. """
  3961. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3962. :return: None
  3963. """
  3964. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3965. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3966. )
  3967. self.on_excellon_format_changed()
  3968. def on_film_color_entry(self):
  3969. self.defaults['tools_film_color'] = \
  3970. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3971. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3972. "background-color:%s;"
  3973. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3974. )
  3975. def on_film_color_button(self):
  3976. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3977. c_dialog = QtWidgets.QColorDialog()
  3978. film_color = c_dialog.getColor(initial=current_color)
  3979. if film_color.isValid() is False:
  3980. return
  3981. # if new color is different then mark that the Preferences are changed
  3982. if film_color != current_color:
  3983. self.preferencesUiManager.on_preferences_edited()
  3984. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3985. "background-color:%s;"
  3986. "border-color: dimgray" % str(film_color.name())
  3987. )
  3988. new_val_sel = str(film_color.name())
  3989. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3990. self.defaults['tools_film_color'] = new_val_sel
  3991. def on_qrcode_fill_color_entry(self):
  3992. self.defaults['tools_qrcode_fill_color'] = \
  3993. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3994. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3995. "background-color:%s;"
  3996. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3997. )
  3998. def on_qrcode_fill_color_button(self):
  3999. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  4000. c_dialog = QtWidgets.QColorDialog()
  4001. fill_color = c_dialog.getColor(initial=current_color)
  4002. if fill_color.isValid() is False:
  4003. return
  4004. # if new color is different then mark that the Preferences are changed
  4005. if fill_color != current_color:
  4006. self.preferencesUiManager.on_preferences_edited()
  4007. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4008. "background-color:%s;"
  4009. "border-color: dimgray" % str(fill_color.name())
  4010. )
  4011. new_val_sel = str(fill_color.name())
  4012. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  4013. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  4014. def on_qrcode_back_color_entry(self):
  4015. self.defaults['tools_qrcode_back_color'] = \
  4016. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  4017. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4018. "background-color:%s;"
  4019. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  4020. )
  4021. def on_qrcode_back_color_button(self):
  4022. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  4023. c_dialog = QtWidgets.QColorDialog()
  4024. back_color = c_dialog.getColor(initial=current_color)
  4025. if back_color.isValid() is False:
  4026. return
  4027. # if new color is different then mark that the Preferences are changed
  4028. if back_color != current_color:
  4029. self.preferencesUiManager.on_preferences_edited()
  4030. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4031. "background-color:%s;"
  4032. "border-color: dimgray" % str(back_color.name())
  4033. )
  4034. new_val_sel = str(back_color.name())
  4035. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  4036. self.defaults['tools_qrcode_back_color'] = new_val_sel
  4037. def on_tab_rmb_click(self, checked):
  4038. self.ui.notebook.set_detachable(val=checked)
  4039. self.defaults["global_tabs_detachable"] = checked
  4040. self.ui.plot_tab_area.set_detachable(val=checked)
  4041. self.defaults["global_tabs_detachable"] = checked
  4042. def on_tab_setup_context_menu(self):
  4043. initial_checked = self.defaults["global_tabs_detachable"]
  4044. action_name = str(_("Detachable Tabs"))
  4045. action = QtWidgets.QAction(self)
  4046. action.setCheckable(True)
  4047. action.setText(action_name)
  4048. action.setChecked(initial_checked)
  4049. self.ui.notebook.tabBar.addAction(action)
  4050. self.ui.plot_tab_area.tabBar.addAction(action)
  4051. try:
  4052. action.triggered.disconnect()
  4053. except TypeError:
  4054. pass
  4055. action.triggered.connect(self.on_tab_rmb_click)
  4056. def on_deselect_all(self):
  4057. self.collection.set_all_inactive()
  4058. self.delete_selection_shape()
  4059. def on_workspace_modified(self):
  4060. # self.save_defaults(silent=True)
  4061. if self.is_legacy is True:
  4062. self.plotcanvas.delete_workspace()
  4063. self.preferencesUiManager.defaults_read_form()
  4064. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4065. def on_workspace(self):
  4066. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4067. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4068. else:
  4069. self.plotcanvas.delete_workspace()
  4070. self.preferencesUiManager.defaults_read_form()
  4071. # self.save_defaults(silent=True)
  4072. def on_workspace_toggle(self):
  4073. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4074. try:
  4075. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4076. except TypeError:
  4077. pass
  4078. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4079. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4080. self.on_workspace()
  4081. def on_cursor_type(self, val):
  4082. """
  4083. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4084. :return: None
  4085. """
  4086. self.app_cursor.enabled = False
  4087. if val == 'small':
  4088. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4089. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4090. self.app_cursor = self.plotcanvas.new_cursor()
  4091. else:
  4092. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4093. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4094. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4095. if self.ui.grid_snap_btn.isChecked():
  4096. self.app_cursor.enabled = True
  4097. else:
  4098. self.app_cursor.enabled = False
  4099. def on_tool_add_keypress(self):
  4100. # ## Current application units in Upper Case
  4101. self.units = self.defaults['units'].upper()
  4102. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4103. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4104. if notebook_widget_name == 'selected_tab':
  4105. if self.collection.get_active().kind == 'geometry':
  4106. # Tool add works for Geometry only if Advanced is True in Preferences
  4107. if self.defaults["global_app_level"] == 'a':
  4108. tool_add_popup = FCInputDialog(title="New Tool ...",
  4109. text='Enter a Tool Diameter:',
  4110. min=0.0000, max=99.9999, decimals=4)
  4111. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4112. val, ok = tool_add_popup.get_value()
  4113. if ok:
  4114. if float(val) == 0:
  4115. self.inform.emit('[WARNING_NOTCL] %s' %
  4116. _("Please enter a tool diameter with non-zero value, in Float format."))
  4117. return
  4118. self.collection.get_active().on_tool_add(dia=float(val))
  4119. else:
  4120. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4121. else:
  4122. msgbox = QtWidgets.QMessageBox()
  4123. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4124. "Go to Preferences -> General - Show Advanced Options."))
  4125. msgbox.setWindowTitle("Tool adding ...")
  4126. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4127. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4128. msgbox.setDefaultButton(bt_ok)
  4129. msgbox.exec_()
  4130. # work only if the notebook tab on focus is the Tools_Tab
  4131. if notebook_widget_name == 'tool_tab':
  4132. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4133. # and only if the tool is NCC Tool
  4134. if tool_widget == self.ncclear_tool.toolName:
  4135. self.ncclear_tool.on_add_tool_by_key()
  4136. # and only if the tool is Paint Area Tool
  4137. elif tool_widget == self.paint_tool.toolName:
  4138. self.paint_tool.on_add_tool_by_key()
  4139. # and only if the tool is Solder Paste Dispensing Tool
  4140. elif tool_widget == self.paste_tool.toolName:
  4141. self.paste_tool.on_add_tool_by_key()
  4142. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4143. # See description bellow.
  4144. def on_delete_keypress(self):
  4145. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4146. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4147. if notebook_widget_name == 'selected_tab':
  4148. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4149. self.collection.get_active().on_tool_delete()
  4150. # work only if the notebook tab on focus is the Tools_Tab
  4151. elif notebook_widget_name == 'tool_tab':
  4152. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4153. # and only if the tool is NCC Tool
  4154. if tool_widget == self.ncclear_tool.toolName:
  4155. self.ncclear_tool.on_tool_delete()
  4156. # and only if the tool is Paint Tool
  4157. elif tool_widget == self.paint_tool.toolName:
  4158. self.paint_tool.on_tool_delete()
  4159. # and only if the tool is Solder Paste Dispensing Tool
  4160. elif tool_widget == self.paste_tool.toolName:
  4161. self.paste_tool.on_tool_delete()
  4162. else:
  4163. self.on_delete()
  4164. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4165. # some screens you have to be careful where you hover with your mouse.
  4166. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4167. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4168. # Complicated, I know :)
  4169. def on_delete(self, force_deletion=False):
  4170. """
  4171. Delete the currently selected FlatCAMObjs.
  4172. :param force_deletion: used by Tcl command
  4173. :return: None
  4174. """
  4175. self.defaults.report_usage("on_delete()")
  4176. response = None
  4177. bt_ok = None
  4178. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4179. # a geometry object before we update it.
  4180. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4181. and self.grb_editor.editor_active is False:
  4182. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4183. msgbox = QtWidgets.QMessageBox()
  4184. msgbox.setWindowTitle(_("Delete objects"))
  4185. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4186. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4187. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4188. "the selected objects?"))
  4189. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4190. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4191. msgbox.setDefaultButton(bt_ok)
  4192. msgbox.exec_()
  4193. response = msgbox.clickedButton()
  4194. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4195. response = bt_ok
  4196. if response == bt_ok:
  4197. if self.collection.get_active():
  4198. self.log.debug("App.on_delete()")
  4199. for obj_active in self.collection.get_selected():
  4200. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4201. if isinstance(obj_active, GerberObject):
  4202. for el in obj_active.mark_shapes:
  4203. obj_active.mark_shapes[el].clear(update=True)
  4204. obj_active.mark_shapes[el].enabled = False
  4205. # obj_active.mark_shapes[el] = None
  4206. del el
  4207. elif isinstance(obj_active, CNCJobObject):
  4208. try:
  4209. obj_active.text_col.enabled = False
  4210. del obj_active.text_col
  4211. obj_active.annotation.clear(update=True)
  4212. del obj_active.annotation
  4213. except AttributeError as e:
  4214. log.debug(
  4215. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4216. )
  4217. while self.collection.get_selected():
  4218. self.delete_first_selected()
  4219. self.inform.emit('%s...' % _("Object(s) deleted"))
  4220. # make sure that the selection shape is deleted, too
  4221. self.delete_selection_shape()
  4222. else:
  4223. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4224. else:
  4225. self.inform.emit(_("Save the work in Editor and try again ..."))
  4226. def delete_first_selected(self):
  4227. # Keep this for later
  4228. try:
  4229. sel_obj = self.collection.get_active()
  4230. name = sel_obj.options["name"]
  4231. isPlotted = sel_obj.options["plot"]
  4232. except AttributeError:
  4233. self.log.debug("Nothing selected for deletion")
  4234. return
  4235. if self.is_legacy is True:
  4236. # Remove plot only if the object was plotted otherwise delaxes will fail
  4237. if isPlotted:
  4238. try:
  4239. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4240. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4241. except Exception as e:
  4242. log.debug("App.delete_first_selected() --> %s" % str(e))
  4243. self.plotcanvas.auto_adjust_axes()
  4244. # Remove from dictionary
  4245. self.collection.delete_active()
  4246. # Clear form
  4247. self.setup_component_editor()
  4248. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4249. def on_set_origin(self):
  4250. """
  4251. Set the origin to the left mouse click position
  4252. :return: None
  4253. """
  4254. # display the message for the user
  4255. # and ask him to click on the desired position
  4256. self.defaults.report_usage("on_set_origin()")
  4257. def origin_replot():
  4258. def worker_task():
  4259. with self.proc_container.new('%s...' % _("Plotting")):
  4260. for obj in self.collection.get_list():
  4261. obj.plot()
  4262. self.plotcanvas.fit_view()
  4263. if self.is_legacy:
  4264. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4265. else:
  4266. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4267. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4268. self.inform.emit(_('Click to set the origin ...'))
  4269. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4270. # first disconnect it as it may have been used by something else
  4271. try:
  4272. self.replot_signal.disconnect()
  4273. except TypeError:
  4274. pass
  4275. self.replot_signal[list].connect(origin_replot)
  4276. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4277. """
  4278. :param event:
  4279. :param location:
  4280. :param noplot:
  4281. :param use_thread:
  4282. :return:
  4283. """
  4284. noplot_sig = noplot
  4285. def worker_task():
  4286. with self.proc_container.new(_("Setting Origin...")):
  4287. obj_list = self.collection.get_list()
  4288. for obj in obj_list:
  4289. obj.offset((x, y))
  4290. self.object_changed.emit(obj)
  4291. # Update the object bounding box options
  4292. a, b, c, d = obj.bounds()
  4293. obj.options['xmin'] = a
  4294. obj.options['ymin'] = b
  4295. obj.options['xmax'] = c
  4296. obj.options['ymax'] = d
  4297. self.inform.emit('[success] %s...' % _('Origin set'))
  4298. for obj in obj_list:
  4299. out_name = obj.options["name"]
  4300. if obj.kind == 'gerber':
  4301. obj.source_file = self.export_gerber(
  4302. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4303. elif obj.kind == 'excellon':
  4304. obj.source_file = self.export_excellon(
  4305. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4306. if noplot_sig is False:
  4307. self.replot_signal.emit([])
  4308. if location is not None:
  4309. if len(location) != 2:
  4310. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4311. return 'fail'
  4312. x, y = location
  4313. if use_thread is True:
  4314. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4315. else:
  4316. worker_task()
  4317. self.should_we_save = True
  4318. return
  4319. if event.button == 1:
  4320. if self.is_legacy is False:
  4321. event_pos = event.pos
  4322. else:
  4323. event_pos = (event.xdata, event.ydata)
  4324. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4325. if self.grid_status():
  4326. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4327. else:
  4328. pos = pos_canvas
  4329. x = 0 - pos[0]
  4330. y = 0 - pos[1]
  4331. if use_thread is True:
  4332. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4333. else:
  4334. worker_task()
  4335. self.should_we_save = True
  4336. def on_move2origin(self, use_thread=True):
  4337. """
  4338. Move selected objects to origin.
  4339. :param use_thread: Control if to use threaded operation. Boolean.
  4340. :return:
  4341. """
  4342. def worker_task():
  4343. with self.proc_container.new(_("Moving to Origin...")):
  4344. obj_list = self.collection.get_selected()
  4345. if not obj_list:
  4346. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4347. return
  4348. xminlist = []
  4349. yminlist = []
  4350. # first get a bounding box to fit all
  4351. for obj in obj_list:
  4352. xmin, ymin, xmax, ymax = obj.bounds()
  4353. xminlist.append(xmin)
  4354. yminlist.append(ymin)
  4355. # get the minimum x,y for all objects selected
  4356. x = min(xminlist)
  4357. y = min(yminlist)
  4358. for obj in obj_list:
  4359. obj.offset((-x, -y))
  4360. self.object_changed.emit(obj)
  4361. # Update the object bounding box options
  4362. a, b, c, d = obj.bounds()
  4363. obj.options['xmin'] = a
  4364. obj.options['ymin'] = b
  4365. obj.options['xmax'] = c
  4366. obj.options['ymax'] = d
  4367. for obj in obj_list:
  4368. obj.plot()
  4369. for obj in obj_list:
  4370. out_name = obj.options["name"]
  4371. if obj.kind == 'gerber':
  4372. obj.source_file = self.export_gerber(
  4373. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4374. elif obj.kind == 'excellon':
  4375. obj.source_file = self.export_excellon(
  4376. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4377. self.inform.emit('[success] %s...' % _('Origin set'))
  4378. if use_thread is True:
  4379. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4380. else:
  4381. worker_task()
  4382. self.should_we_save = True
  4383. def on_jump_to(self, custom_location=None, fit_center=True):
  4384. """
  4385. Jump to a location by setting the mouse cursor location.
  4386. :param custom_location: Jump to a specified point. (x, y) tuple.
  4387. :param fit_center: If to fit view. Boolean.
  4388. :return:
  4389. """
  4390. self.defaults.report_usage("on_jump_to()")
  4391. if not custom_location:
  4392. dia_box_location = None
  4393. try:
  4394. dia_box_location = eval(self.clipboard.text())
  4395. except Exception:
  4396. pass
  4397. if type(dia_box_location) == tuple:
  4398. dia_box_location = str(dia_box_location)
  4399. else:
  4400. dia_box_location = None
  4401. # dia_box = Dialog_box(title=_("Jump to ..."),
  4402. # label=_("Enter the coordinates in format X,Y:"),
  4403. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4404. # initial_text=dia_box_location)
  4405. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4406. label=_("Enter the coordinates in format X,Y:"),
  4407. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4408. initial_text=dia_box_location,
  4409. reference=self.defaults['global_jump_ref'])
  4410. if dia_box.ok is True:
  4411. try:
  4412. location = eval(dia_box.location)
  4413. if not isinstance(location, tuple):
  4414. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4415. return
  4416. if dia_box.reference == 'rel':
  4417. rel_x = self.mouse[0] + location[0]
  4418. rel_y = self.mouse[1] + location[1]
  4419. location = (rel_x, rel_y)
  4420. self.defaults['global_jump_ref'] = dia_box.reference
  4421. except Exception:
  4422. return
  4423. else:
  4424. return
  4425. else:
  4426. location = custom_location
  4427. self.jump_signal.emit(location)
  4428. if fit_center:
  4429. self.plotcanvas.fit_center(loc=location)
  4430. cursor = QtGui.QCursor()
  4431. if self.is_legacy is False:
  4432. # I don't know where those differences come from but they are constant for the current
  4433. # execution of the application and they are multiples of a value around 0.0263mm.
  4434. # In a random way sometimes they are more sometimes they are less
  4435. # if units == 'MM':
  4436. # cal_factor = 0.0263
  4437. # else:
  4438. # cal_factor = 0.0263 / 25.4
  4439. cal_location = (location[0], location[1])
  4440. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4441. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4442. j_pos = (
  4443. int(canvas_origin.x() + round(jump_loc[0])),
  4444. int(canvas_origin.y() + round(jump_loc[1]))
  4445. )
  4446. cursor.setPos(j_pos[0], j_pos[1])
  4447. else:
  4448. # find the canvas origin which is in the top left corner
  4449. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4450. # determine the coordinates for the lowest left point of the canvas
  4451. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4452. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4453. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4454. # canvas) and the point (width, height) is in the top-right location
  4455. loc = self.plotcanvas.axes.transData.transform_point(location)
  4456. j_pos = (
  4457. int(x0 + loc[0]),
  4458. int(y0 - loc[1])
  4459. )
  4460. cursor.setPos(j_pos[0], j_pos[1])
  4461. self.plotcanvas.mouse = [location[0], location[1]]
  4462. if self.defaults["global_cursor_color_enabled"] is True:
  4463. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4464. else:
  4465. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4466. if self.grid_status():
  4467. # Update cursor
  4468. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4469. symbol='++', edge_color=self.cursor_color_3D,
  4470. edge_width=self.defaults["global_cursor_width"],
  4471. size=self.defaults["global_cursor_size"])
  4472. # Set the position label
  4473. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4474. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4475. # Set the relative position label
  4476. dx = location[0] - float(self.rel_point1[0])
  4477. dy = location[1] - float(self.rel_point1[1])
  4478. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4479. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4480. self.inform.emit('[success] %s' % _("Done."))
  4481. return location
  4482. def on_locate(self, obj, fit_center=True):
  4483. """
  4484. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4485. :param obj: The object on which to locate certain points
  4486. :param fit_center: If to fit view. Boolean.
  4487. :return: A point location. (x, y) tuple.
  4488. """
  4489. self.defaults.report_usage("on_locate()")
  4490. if obj is None:
  4491. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4492. return 'fail'
  4493. class DialogBoxChoice(QtWidgets.QDialog):
  4494. def __init__(self, title=None, icon=None, choice='bl'):
  4495. """
  4496. :param title: string with the window title
  4497. """
  4498. super(DialogBoxChoice, self).__init__()
  4499. self.ok = False
  4500. self.setWindowIcon(icon)
  4501. self.setWindowTitle(str(title))
  4502. self.form = QtWidgets.QFormLayout(self)
  4503. self.ref_radio = RadioSet([
  4504. {"label": _("Bottom-Left"), "value": "bl"},
  4505. {"label": _("Top-Left"), "value": "tl"},
  4506. {"label": _("Bottom-Right"), "value": "br"},
  4507. {"label": _("Top-Right"), "value": "tr"},
  4508. {"label": _("Center"), "value": "c"}
  4509. ], orientation='vertical', stretch=False)
  4510. self.ref_radio.set_value(choice)
  4511. self.form.addRow(self.ref_radio)
  4512. self.button_box = QtWidgets.QDialogButtonBox(
  4513. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4514. Qt.Horizontal, parent=self)
  4515. self.form.addRow(self.button_box)
  4516. self.button_box.accepted.connect(self.accept)
  4517. self.button_box.rejected.connect(self.reject)
  4518. if self.exec_() == QtWidgets.QDialog.Accepted:
  4519. self.ok = True
  4520. self.location_point = self.ref_radio.get_value()
  4521. else:
  4522. self.ok = False
  4523. self.location_point = None
  4524. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4525. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4526. choice=self.defaults['global_locate_pt'])
  4527. if dia_box.ok is True:
  4528. try:
  4529. location_point = dia_box.location_point
  4530. self.defaults['global_locate_pt'] = dia_box.location_point
  4531. except Exception:
  4532. return
  4533. else:
  4534. return
  4535. loc_b = obj.bounds()
  4536. if location_point == 'bl':
  4537. location = (loc_b[0], loc_b[1])
  4538. elif location_point == 'tl':
  4539. location = (loc_b[0], loc_b[3])
  4540. elif location_point == 'br':
  4541. location = (loc_b[2], loc_b[1])
  4542. elif location_point == 'tr':
  4543. location = (loc_b[2], loc_b[3])
  4544. else:
  4545. # center
  4546. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4547. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4548. location = (cx, cy)
  4549. self.locate_signal.emit(location, location_point)
  4550. if fit_center:
  4551. self.plotcanvas.fit_center(loc=location)
  4552. cursor = QtGui.QCursor()
  4553. if self.is_legacy is False:
  4554. # I don't know where those differences come from but they are constant for the current
  4555. # execution of the application and they are multiples of a value around 0.0263mm.
  4556. # In a random way sometimes they are more sometimes they are less
  4557. # if units == 'MM':
  4558. # cal_factor = 0.0263
  4559. # else:
  4560. # cal_factor = 0.0263 / 25.4
  4561. cal_location = (location[0], location[1])
  4562. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4563. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4564. j_pos = (
  4565. int(canvas_origin.x() + round(jump_loc[0])),
  4566. int(canvas_origin.y() + round(jump_loc[1]))
  4567. )
  4568. cursor.setPos(j_pos[0], j_pos[1])
  4569. else:
  4570. # find the canvas origin which is in the top left corner
  4571. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4572. # determine the coordinates for the lowest left point of the canvas
  4573. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4574. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4575. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4576. # canvas) and the point (width, height) is in the top-right location
  4577. loc = self.plotcanvas.axes.transData.transform_point(location)
  4578. j_pos = (
  4579. int(x0 + loc[0]),
  4580. int(y0 - loc[1])
  4581. )
  4582. cursor.setPos(j_pos[0], j_pos[1])
  4583. self.plotcanvas.mouse = [location[0], location[1]]
  4584. if self.defaults["global_cursor_color_enabled"] is True:
  4585. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4586. else:
  4587. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4588. if self.grid_status():
  4589. # Update cursor
  4590. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4591. symbol='++', edge_color=self.cursor_color_3D,
  4592. edge_width=self.defaults["global_cursor_width"],
  4593. size=self.defaults["global_cursor_size"])
  4594. # Set the position label
  4595. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4596. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4597. # Set the relative position label
  4598. self.dx = location[0] - float(self.rel_point1[0])
  4599. self.dy = location[1] - float(self.rel_point1[1])
  4600. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4601. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4602. self.inform.emit('[success] %s' % _("Done."))
  4603. return location
  4604. def on_copy_command(self):
  4605. """
  4606. Will copy a selection of objects, creating new objects.
  4607. :return:
  4608. """
  4609. self.defaults.report_usage("on_copy_command()")
  4610. def initialize(obj_init, app):
  4611. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4612. try:
  4613. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4614. except AttributeError:
  4615. pass
  4616. try:
  4617. obj_init.apertures = deepcopy(obj.apertures)
  4618. except AttributeError:
  4619. pass
  4620. try:
  4621. if obj.tools:
  4622. obj_init.tools = deepcopy(obj.tools)
  4623. except Exception as err:
  4624. log.debug("App.on_copy_command() --> %s" % str(err))
  4625. try:
  4626. obj_init.source_file = deepcopy(obj.source_file)
  4627. except (AttributeError, TypeError):
  4628. pass
  4629. def initialize_excellon(obj_init, app):
  4630. obj_init.source_file = deepcopy(obj.source_file)
  4631. obj_init.tools = deepcopy(obj.tools)
  4632. # drills are offset, so they need to be deep copied
  4633. obj_init.drills = deepcopy(obj.drills)
  4634. # slots are offset, so they need to be deep copied
  4635. obj_init.slots = deepcopy(obj.slots)
  4636. obj_init.create_geometry()
  4637. def initialize_script(obj_init, app_obj):
  4638. obj_init.source_file = deepcopy(obj.source_file)
  4639. def initialize_document(obj_init, app_obj):
  4640. obj_init.source_file = deepcopy(obj.source_file)
  4641. for obj in self.collection.get_selected():
  4642. obj_name = obj.options["name"]
  4643. try:
  4644. if isinstance(obj, ExcellonObject):
  4645. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4646. elif isinstance(obj, GerberObject):
  4647. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4648. elif isinstance(obj, GeometryObject):
  4649. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4650. elif isinstance(obj, ScriptObject):
  4651. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4652. elif isinstance(obj, DocumentObject):
  4653. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4654. except Exception as e:
  4655. return "Operation failed: %s" % str(e)
  4656. def on_copy_object2(self, custom_name):
  4657. def initialize_geometry(obj_init, app):
  4658. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4659. try:
  4660. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4661. except AttributeError:
  4662. pass
  4663. try:
  4664. obj_init.apertures = deepcopy(obj.apertures)
  4665. except AttributeError:
  4666. pass
  4667. try:
  4668. if obj.tools:
  4669. obj_init.tools = deepcopy(obj.tools)
  4670. except Exception as ee:
  4671. log.debug("on_copy_object2() --> %s" % str(ee))
  4672. def initialize_gerber(obj_init, app):
  4673. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4674. obj_init.apertures = deepcopy(obj.apertures)
  4675. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4676. def initialize_excellon(obj_init, app):
  4677. obj_init.tools = deepcopy(obj.tools)
  4678. # drills are offset, so they need to be deep copied
  4679. obj_init.drills = deepcopy(obj.drills)
  4680. # slots are offset, so they need to be deep copied
  4681. obj_init.slots = deepcopy(obj.slots)
  4682. obj_init.create_geometry()
  4683. for obj in self.collection.get_selected():
  4684. obj_name = obj.options["name"]
  4685. try:
  4686. if isinstance(obj, ExcellonObject):
  4687. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4688. elif isinstance(obj, GerberObject):
  4689. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4690. elif isinstance(obj, GeometryObject):
  4691. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4692. except Exception as er:
  4693. return "Operation failed: %s" % str(er)
  4694. def on_rename_object(self, text):
  4695. """
  4696. Will rename an object.
  4697. :param text: New name for the object.
  4698. :return:
  4699. """
  4700. self.defaults.report_usage("on_rename_object()")
  4701. named_obj = self.collection.get_active()
  4702. for obj in named_obj:
  4703. if obj is list:
  4704. self.on_rename_object(text)
  4705. else:
  4706. try:
  4707. obj.options['name'] = text
  4708. except Exception as e:
  4709. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4710. def convert_any2geo(self):
  4711. """
  4712. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4713. :return:
  4714. """
  4715. self.defaults.report_usage("convert_any2geo()")
  4716. def initialize(obj_init, app):
  4717. obj_init.solid_geometry = obj.solid_geometry
  4718. try:
  4719. obj_init.follow_geometry = obj.follow_geometry
  4720. except AttributeError:
  4721. pass
  4722. try:
  4723. obj_init.apertures = obj.apertures
  4724. except AttributeError:
  4725. pass
  4726. try:
  4727. if obj.tools:
  4728. obj_init.tools = obj.tools
  4729. except AttributeError:
  4730. pass
  4731. def initialize_excellon(obj_init, app):
  4732. # objs = self.collection.get_selected()
  4733. # GeometryObject.merge(objs, obj)
  4734. solid_geo = []
  4735. for tool in obj.tools:
  4736. for geo in obj.tools[tool]['solid_geometry']:
  4737. solid_geo.append(geo)
  4738. obj_init.solid_geometry = deepcopy(solid_geo)
  4739. if not self.collection.get_selected():
  4740. log.warning("App.convert_any2geo --> No object selected")
  4741. self.inform.emit('[WARNING_NOTCL] %s' %
  4742. _("No object is selected. Select an object and try again."))
  4743. return
  4744. for obj in self.collection.get_selected():
  4745. obj_name = obj.options["name"]
  4746. try:
  4747. if isinstance(obj, ExcellonObject):
  4748. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4749. else:
  4750. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4751. except Exception as e:
  4752. return "Operation failed: %s" % str(e)
  4753. def convert_any2gerber(self):
  4754. """
  4755. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4756. :return:
  4757. """
  4758. self.defaults.report_usage("convert_any2gerber()")
  4759. def initialize_geometry(obj_init, app):
  4760. apertures = {}
  4761. apid = 0
  4762. apertures[str(apid)] = {}
  4763. apertures[str(apid)]['geometry'] = []
  4764. for obj_orig in obj.solid_geometry:
  4765. new_elem = {}
  4766. new_elem['solid'] = obj_orig
  4767. try:
  4768. new_elem['follow'] = obj_orig.exterior
  4769. except AttributeError:
  4770. pass
  4771. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4772. apertures[str(apid)]['size'] = 0.0
  4773. apertures[str(apid)]['type'] = 'C'
  4774. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4775. obj_init.apertures = deepcopy(apertures)
  4776. def initialize_excellon(obj_init, app):
  4777. apertures = {}
  4778. apid = 10
  4779. for tool in obj.tools:
  4780. apertures[str(apid)] = {}
  4781. apertures[str(apid)]['geometry'] = []
  4782. for geo in obj.tools[tool]['solid_geometry']:
  4783. new_el = {}
  4784. new_el['solid'] = geo
  4785. new_el['follow'] = geo.exterior
  4786. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4787. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4788. apertures[str(apid)]['type'] = 'C'
  4789. apid += 1
  4790. # create solid_geometry
  4791. solid_geometry = []
  4792. for apid in apertures:
  4793. for geo_el in apertures[apid]['geometry']:
  4794. solid_geometry.append(geo_el['solid'])
  4795. solid_geometry = MultiPolygon(solid_geometry)
  4796. solid_geometry = solid_geometry.buffer(0.0000001)
  4797. obj_init.solid_geometry = deepcopy(solid_geometry)
  4798. obj_init.apertures = deepcopy(apertures)
  4799. # clear the working objects (perhaps not necessary due of Python GC)
  4800. apertures.clear()
  4801. if not self.collection.get_selected():
  4802. log.warning("App.convert_any2gerber --> No object selected")
  4803. self.inform.emit('[WARNING_NOTCL] %s' %
  4804. _("No object is selected. Select an object and try again."))
  4805. return
  4806. for obj in self.collection.get_selected():
  4807. obj_name = obj.options["name"]
  4808. try:
  4809. if isinstance(obj, ExcellonObject):
  4810. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4811. elif isinstance(obj, GeometryObject):
  4812. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4813. else:
  4814. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4815. except Exception as e:
  4816. return "Operation failed: %s" % str(e)
  4817. def abort_all_tasks(self):
  4818. """
  4819. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4820. on the first possible occasion.
  4821. :return:
  4822. """
  4823. if self.abort_flag is False:
  4824. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4825. self.abort_flag = True
  4826. self.cleanup.emit()
  4827. def app_is_idle(self):
  4828. if self.abort_flag:
  4829. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4830. self.abort_flag = False
  4831. def on_selectall(self):
  4832. """
  4833. Will draw a selection box shape around the selected objects.
  4834. :return:
  4835. """
  4836. self.defaults.report_usage("on_selectall()")
  4837. # delete the possible selection box around a possible selected object
  4838. self.delete_selection_shape()
  4839. for name in self.collection.get_names():
  4840. self.collection.set_active(name)
  4841. curr_sel_obj = self.collection.get_by_name(name)
  4842. # create the selection box around the selected object
  4843. if self.defaults['global_selection_shape'] is True:
  4844. self.draw_selection_shape(curr_sel_obj)
  4845. def on_preferences(self):
  4846. """
  4847. Adds the Preferences in a Tab in Plot Area
  4848. :return:
  4849. """
  4850. # add the tab if it was closed
  4851. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4852. # delete the absolute and relative position and messages in the infobar
  4853. self.ui.position_label.setText("")
  4854. self.ui.rel_position_label.setText("")
  4855. # Switch plot_area to preferences page
  4856. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4857. # self.ui.show()
  4858. # detect changes in the preferences
  4859. for idx in range(self.ui.pref_tab_area.count()):
  4860. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4861. try:
  4862. try:
  4863. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4864. except (TypeError, AttributeError):
  4865. pass
  4866. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4867. except AttributeError:
  4868. pass
  4869. try:
  4870. try:
  4871. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4872. except (TypeError, AttributeError):
  4873. pass
  4874. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4875. except AttributeError:
  4876. pass
  4877. try:
  4878. try:
  4879. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4880. except (TypeError, AttributeError):
  4881. pass
  4882. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4883. except AttributeError:
  4884. pass
  4885. try:
  4886. try:
  4887. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4888. except (TypeError, AttributeError):
  4889. pass
  4890. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4891. except AttributeError:
  4892. pass
  4893. try:
  4894. try:
  4895. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4896. except (TypeError, AttributeError):
  4897. pass
  4898. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4899. except AttributeError:
  4900. pass
  4901. def on_tools_database(self, source='app'):
  4902. """
  4903. Adds the Tools Database in a Tab in Plot Area.
  4904. :return:
  4905. """
  4906. for idx in range(self.ui.plot_tab_area.count()):
  4907. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4908. # there can be only one instance of Tools Database at one time
  4909. return
  4910. if source == 'app':
  4911. self.tools_db_tab = ToolsDB2(
  4912. app=self,
  4913. parent=self.ui,
  4914. callback_on_edited=self.on_tools_db_edited,
  4915. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4916. )
  4917. elif source == 'ncc':
  4918. self.tools_db_tab = ToolsDB2(
  4919. app=self,
  4920. parent=self.ui,
  4921. callback_on_edited=self.on_tools_db_edited,
  4922. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4923. )
  4924. elif source == 'paint':
  4925. self.tools_db_tab = ToolsDB2(
  4926. app=self,
  4927. parent=self.ui,
  4928. callback_on_edited=self.on_tools_db_edited,
  4929. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4930. )
  4931. # add the tab if it was closed
  4932. try:
  4933. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4934. self.tools_db_tab.setObjectName("database_tab")
  4935. except Exception as e:
  4936. log.debug("App.on_tools_database() --> %s" % str(e))
  4937. return
  4938. # delete the absolute and relative position and messages in the infobar
  4939. self.ui.position_label.setText("")
  4940. self.ui.rel_position_label.setText("")
  4941. # Switch plot_area to preferences page
  4942. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4943. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4944. self.tools_db_tab.ui_connect()
  4945. def on_tools_db_edited(self):
  4946. """
  4947. Executed whenever a tool is edited in Tools Database.
  4948. Will color the text of the Tools Database tab to Red color.
  4949. :return:
  4950. """
  4951. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4952. for idx in range(self.ui.plot_tab_area.count()):
  4953. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4954. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4955. self.tools_db_changed_flag = True
  4956. def on_geometry_tool_add_from_db_executed(self, tool):
  4957. """
  4958. Here add the tool from DB in the selected geometry object.
  4959. :return:
  4960. """
  4961. tool_from_db = deepcopy(tool)
  4962. obj = self.collection.get_active()
  4963. if isinstance(obj, GeometryObject):
  4964. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4965. # close the tab and delete it
  4966. for idx in range(self.ui.plot_tab_area.count()):
  4967. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4968. wdg = self.ui.plot_tab_area.widget(idx)
  4969. wdg.deleteLater()
  4970. self.ui.plot_tab_area.removeTab(idx)
  4971. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4972. else:
  4973. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4974. def on_plot_area_tab_closed(self, tab_obj_name):
  4975. """
  4976. Executed whenever a QTab is closed in the Plot Area.
  4977. :param title: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4978. :return:
  4979. """
  4980. if tab_obj_name == "preferences_tab":
  4981. self.preferencesUiManager.on_close_preferences_tab()
  4982. elif tab_obj_name == "database_tab":
  4983. # disconnect the signals from the table widget in tab
  4984. self.tools_db_tab.ui_disconnect()
  4985. if self.tools_db_changed_flag is True:
  4986. msgbox = QtWidgets.QMessageBox()
  4987. msgbox.setText(_("One or more Tools are edited.\n"
  4988. "Do you want to update the Tools Database?"))
  4989. msgbox.setWindowTitle(_("Save Tools Database"))
  4990. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4991. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4992. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4993. msgbox.setDefaultButton(bt_yes)
  4994. msgbox.exec_()
  4995. response = msgbox.clickedButton()
  4996. if response == bt_yes:
  4997. self.tools_db_tab.on_save_tools_db()
  4998. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4999. else:
  5000. self.tools_db_changed_flag = False
  5001. self.inform.emit('')
  5002. return
  5003. self.tools_db_tab.deleteLater()
  5004. elif tab_obj_name == "text_editor_tab":
  5005. self.toggle_codeeditor = False
  5006. elif tab_obj_name == "bookmarks_tab":
  5007. self.book_dialog_tab.rebuild_actions()
  5008. self.book_dialog_tab.deleteLater()
  5009. else:
  5010. return
  5011. def on_plotarea_tab_closed(self, tab_idx):
  5012. """
  5013. :param tab_idx: Index of the Tab from the plotarea that was closed
  5014. :return:
  5015. """
  5016. widget = self.ui.plot_tab_area.widget(tab_idx)
  5017. if widget is not None:
  5018. widget.deleteLater()
  5019. self.ui.plot_tab_area.removeTab(tab_idx)
  5020. def on_flipy(self):
  5021. """
  5022. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  5023. :return:
  5024. """
  5025. self.defaults.report_usage("on_flipy()")
  5026. obj_list = self.collection.get_selected()
  5027. xminlist = []
  5028. yminlist = []
  5029. xmaxlist = []
  5030. ymaxlist = []
  5031. if not obj_list:
  5032. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  5033. else:
  5034. try:
  5035. # first get a bounding box to fit all
  5036. for obj in obj_list:
  5037. xmin, ymin, xmax, ymax = obj.bounds()
  5038. xminlist.append(xmin)
  5039. yminlist.append(ymin)
  5040. xmaxlist.append(xmax)
  5041. ymaxlist.append(ymax)
  5042. # get the minimum x,y and maximum x,y for all objects selected
  5043. xminimal = min(xminlist)
  5044. yminimal = min(yminlist)
  5045. xmaximal = max(xmaxlist)
  5046. ymaximal = max(ymaxlist)
  5047. px = 0.5 * (xminimal + xmaximal)
  5048. py = 0.5 * (yminimal + ymaximal)
  5049. # execute mirroring
  5050. for obj in obj_list:
  5051. obj.mirror('X', [px, py])
  5052. obj.plot()
  5053. self.object_changed.emit(obj)
  5054. self.inform.emit('[success] %s' %
  5055. _("Flip on Y axis done."))
  5056. except Exception as e:
  5057. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5058. return
  5059. def on_flipx(self):
  5060. """
  5061. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5062. :return:
  5063. """
  5064. self.defaults.report_usage("on_flipx()")
  5065. obj_list = self.collection.get_selected()
  5066. xminlist = []
  5067. yminlist = []
  5068. xmaxlist = []
  5069. ymaxlist = []
  5070. if not obj_list:
  5071. self.inform.emit('[WARNING_NOTCL] %s' %
  5072. _("No object selected to Flip on X axis."))
  5073. else:
  5074. try:
  5075. # first get a bounding box to fit all
  5076. for obj in obj_list:
  5077. xmin, ymin, xmax, ymax = obj.bounds()
  5078. xminlist.append(xmin)
  5079. yminlist.append(ymin)
  5080. xmaxlist.append(xmax)
  5081. ymaxlist.append(ymax)
  5082. # get the minimum x,y and maximum x,y for all objects selected
  5083. xminimal = min(xminlist)
  5084. yminimal = min(yminlist)
  5085. xmaximal = max(xmaxlist)
  5086. ymaximal = max(ymaxlist)
  5087. px = 0.5 * (xminimal + xmaximal)
  5088. py = 0.5 * (yminimal + ymaximal)
  5089. # execute mirroring
  5090. for obj in obj_list:
  5091. obj.mirror('Y', [px, py])
  5092. obj.plot()
  5093. self.object_changed.emit(obj)
  5094. self.inform.emit('[success] %s' %
  5095. _("Flip on X axis done."))
  5096. except Exception as e:
  5097. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5098. return
  5099. def on_rotate(self, silent=False, preset=None):
  5100. """
  5101. Executed when Options -> Rotate Selection menu entry is clicked.
  5102. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5103. :param preset: A value to be used as predefined angle for rotation.
  5104. :return:
  5105. """
  5106. self.defaults.report_usage("on_rotate()")
  5107. obj_list = self.collection.get_selected()
  5108. xminlist = []
  5109. yminlist = []
  5110. xmaxlist = []
  5111. ymaxlist = []
  5112. if not obj_list:
  5113. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5114. else:
  5115. if silent is False:
  5116. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5117. min=-360, max=360, decimals=4,
  5118. init_val=float(self.defaults['tools_transform_rotate']))
  5119. num, ok = rotatebox.get_value()
  5120. else:
  5121. num = preset
  5122. ok = True
  5123. if ok:
  5124. try:
  5125. # first get a bounding box to fit all
  5126. for obj in obj_list:
  5127. xmin, ymin, xmax, ymax = obj.bounds()
  5128. xminlist.append(xmin)
  5129. yminlist.append(ymin)
  5130. xmaxlist.append(xmax)
  5131. ymaxlist.append(ymax)
  5132. # get the minimum x,y and maximum x,y for all objects selected
  5133. xminimal = min(xminlist)
  5134. yminimal = min(yminlist)
  5135. xmaximal = max(xmaxlist)
  5136. ymaximal = max(ymaxlist)
  5137. px = 0.5 * (xminimal + xmaximal)
  5138. py = 0.5 * (yminimal + ymaximal)
  5139. for sel_obj in obj_list:
  5140. sel_obj.rotate(-float(num), point=(px, py))
  5141. sel_obj.plot()
  5142. self.object_changed.emit(sel_obj)
  5143. self.inform.emit('[success] %s' %
  5144. _("Rotation done."))
  5145. except Exception as e:
  5146. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5147. return
  5148. def on_skewx(self):
  5149. """
  5150. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5151. :return:
  5152. """
  5153. self.defaults.report_usage("on_skewx()")
  5154. obj_list = self.collection.get_selected()
  5155. xminlist = []
  5156. yminlist = []
  5157. if not obj_list:
  5158. self.inform.emit('[WARNING_NOTCL] %s' %
  5159. _("No object selected to Skew/Shear on X axis."))
  5160. else:
  5161. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5162. min=-360, max=360, decimals=4,
  5163. init_val=float(self.defaults['tools_transform_skew_x']))
  5164. num, ok = skewxbox.get_value()
  5165. if ok:
  5166. # first get a bounding box to fit all
  5167. for obj in obj_list:
  5168. xmin, ymin, xmax, ymax = obj.bounds()
  5169. xminlist.append(xmin)
  5170. yminlist.append(ymin)
  5171. # get the minimum x,y and maximum x,y for all objects selected
  5172. xminimal = min(xminlist)
  5173. yminimal = min(yminlist)
  5174. for obj in obj_list:
  5175. obj.skew(num, 0, point=(xminimal, yminimal))
  5176. obj.plot()
  5177. self.object_changed.emit(obj)
  5178. self.inform.emit('[success] %s' %
  5179. _("Skew on X axis done."))
  5180. def on_skewy(self):
  5181. """
  5182. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5183. :return:
  5184. """
  5185. self.defaults.report_usage("on_skewy()")
  5186. obj_list = self.collection.get_selected()
  5187. xminlist = []
  5188. yminlist = []
  5189. if not obj_list:
  5190. self.inform.emit('[WARNING_NOTCL] %s' %
  5191. _("No object selected to Skew/Shear on Y axis."))
  5192. else:
  5193. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5194. min=-360, max=360, decimals=4,
  5195. init_val=float(self.defaults['tools_transform_skew_y']))
  5196. num, ok = skewybox.get_value()
  5197. if ok:
  5198. # first get a bounding box to fit all
  5199. for obj in obj_list:
  5200. xmin, ymin, xmax, ymax = obj.bounds()
  5201. xminlist.append(xmin)
  5202. yminlist.append(ymin)
  5203. # get the minimum x,y and maximum x,y for all objects selected
  5204. xminimal = min(xminlist)
  5205. yminimal = min(yminlist)
  5206. for obj in obj_list:
  5207. obj.skew(0, num, point=(xminimal, yminimal))
  5208. obj.plot()
  5209. self.object_changed.emit(obj)
  5210. self.inform.emit('[success] %s' %
  5211. _("Skew on Y axis done."))
  5212. def on_plots_updated(self):
  5213. """
  5214. Callback used to report when the plots have changed.
  5215. Adjust axes and zooms to fit.
  5216. :return: None
  5217. """
  5218. if self.is_legacy is False:
  5219. self.plotcanvas.update()
  5220. else:
  5221. self.plotcanvas.auto_adjust_axes()
  5222. self.on_zoom_fit(None)
  5223. self.collection.update_view()
  5224. # self.inform.emit(_("Plots updated ..."))
  5225. def on_toolbar_replot(self):
  5226. """
  5227. Callback for toolbar button. Re-plots all objects.
  5228. :return: None
  5229. """
  5230. self.defaults.report_usage("on_toolbar_replot")
  5231. self.log.debug("on_toolbar_replot()")
  5232. try:
  5233. self.collection.get_active().read_form()
  5234. except AttributeError:
  5235. self.log.debug("on_toolbar_replot(): AttributeError")
  5236. pass
  5237. self.plot_all()
  5238. def on_row_activated(self, index):
  5239. if index.isValid():
  5240. if index.internalPointer().parent_item != self.collection.root_item:
  5241. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5242. self.collection.on_item_activated(index)
  5243. def on_row_selected(self, obj_name):
  5244. """
  5245. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5246. It mean we clicked outside of the items and deselected all
  5247. :param obj_name:
  5248. :return:
  5249. """
  5250. if obj_name == 'none':
  5251. for act in self.ui.menuobjects.actions():
  5252. act.setChecked(False)
  5253. return
  5254. # get the name of the selected objects and add them to a list
  5255. name_list = []
  5256. for obj in self.collection.get_selected():
  5257. name_list.append(obj.options['name'])
  5258. # set all actions as unchecked but the ones selected make them checked
  5259. for act in self.ui.menuobjects.actions():
  5260. act.setChecked(False)
  5261. if act.text() in name_list:
  5262. act.setChecked(True)
  5263. def on_collection_updated(self, obj, state, old_name):
  5264. """
  5265. Create a menu from the object loaded in the collection.
  5266. :param obj: object that was changed (added, deleted, renamed)
  5267. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5268. :param old_name: the old name of the object before the action that triggered this slot happened
  5269. :return: None
  5270. """
  5271. icon_files = {
  5272. "gerber": self.resource_location + "/flatcam_icon16.png",
  5273. "excellon": self.resource_location + "/drill16.png",
  5274. "cncjob": self.resource_location + "/cnc16.png",
  5275. "geometry": self.resource_location + "/geometry16.png",
  5276. "script": self.resource_location + "/script_new16.png",
  5277. "document": self.resource_location + "/notes16_1.png"
  5278. }
  5279. if state == 'append':
  5280. for act in self.ui.menuobjects.actions():
  5281. try:
  5282. act.triggered.disconnect()
  5283. except TypeError:
  5284. pass
  5285. self.ui.menuobjects.clear()
  5286. gerber_list = []
  5287. exc_list = []
  5288. cncjob_list = []
  5289. geo_list = []
  5290. script_list = []
  5291. doc_list = []
  5292. for name in self.collection.get_names():
  5293. obj_named = self.collection.get_by_name(name)
  5294. if obj_named.kind == 'gerber':
  5295. gerber_list.append(name)
  5296. elif obj_named.kind == 'excellon':
  5297. exc_list.append(name)
  5298. elif obj_named.kind == 'cncjob':
  5299. cncjob_list.append(name)
  5300. elif obj_named.kind == 'geometry':
  5301. geo_list.append(name)
  5302. elif obj_named.kind == 'script':
  5303. script_list.append(name)
  5304. elif obj_named.kind == 'document':
  5305. doc_list.append(name)
  5306. def add_act(o_name):
  5307. obj_for_icon = self.collection.get_by_name(o_name)
  5308. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5309. add_action.setCheckable(True)
  5310. add_action.setText(o_name)
  5311. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5312. add_action.triggered.connect(
  5313. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5314. self.collection.set_inactive(o_name))
  5315. self.ui.menuobjects.addAction(add_action)
  5316. for name in gerber_list:
  5317. add_act(name)
  5318. self.ui.menuobjects.addSeparator()
  5319. for name in exc_list:
  5320. add_act(name)
  5321. self.ui.menuobjects.addSeparator()
  5322. for name in cncjob_list:
  5323. add_act(name)
  5324. self.ui.menuobjects.addSeparator()
  5325. for name in geo_list:
  5326. add_act(name)
  5327. self.ui.menuobjects.addSeparator()
  5328. for name in script_list:
  5329. add_act(name)
  5330. self.ui.menuobjects.addSeparator()
  5331. for name in doc_list:
  5332. add_act(name)
  5333. self.ui.menuobjects.addSeparator()
  5334. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5335. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5336. _('Select All')
  5337. )
  5338. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5339. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5340. _('Deselect All')
  5341. )
  5342. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5343. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5344. elif state == 'delete':
  5345. for act in self.ui.menuobjects.actions():
  5346. if act.text() == obj.options['name']:
  5347. try:
  5348. act.triggered.disconnect()
  5349. except TypeError:
  5350. pass
  5351. self.ui.menuobjects.removeAction(act)
  5352. break
  5353. elif state == 'rename':
  5354. for act in self.ui.menuobjects.actions():
  5355. if act.text() == old_name:
  5356. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5357. add_action.setText(obj.options['name'])
  5358. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5359. add_action.triggered.connect(
  5360. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5361. self.collection.set_inactive(obj.options['name']))
  5362. self.ui.menuobjects.insertAction(act, add_action)
  5363. try:
  5364. act.triggered.disconnect()
  5365. except TypeError:
  5366. pass
  5367. self.ui.menuobjects.removeAction(act)
  5368. break
  5369. elif state == 'delete_all':
  5370. for act in self.ui.menuobjects.actions():
  5371. try:
  5372. act.triggered.disconnect()
  5373. except TypeError:
  5374. pass
  5375. self.ui.menuobjects.clear()
  5376. self.ui.menuobjects.addSeparator()
  5377. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5378. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5379. _('Select All')
  5380. )
  5381. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5382. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5383. _('Deselect All')
  5384. )
  5385. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5386. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5387. def on_objects_selection(self, on_off):
  5388. obj_list = self.collection.get_names()
  5389. if on_off is True:
  5390. self.collection.set_all_active()
  5391. for act in self.ui.menuobjects.actions():
  5392. try:
  5393. act.setChecked(True)
  5394. except Exception:
  5395. pass
  5396. if obj_list:
  5397. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5398. else:
  5399. self.collection.set_all_inactive()
  5400. for act in self.ui.menuobjects.actions():
  5401. try:
  5402. act.setChecked(False)
  5403. except Exception:
  5404. pass
  5405. if obj_list:
  5406. self.inform.emit('%s' % _("Objects selection is cleared."))
  5407. else:
  5408. self.inform.emit('')
  5409. def grid_status(self):
  5410. if self.ui.grid_snap_btn.isChecked():
  5411. return True
  5412. else:
  5413. return False
  5414. def populate_cmenu_grids(self):
  5415. units = self.defaults['units'].lower()
  5416. # for act in self.ui.cmenu_gridmenu.actions():
  5417. # act.triggered.disconnect()
  5418. self.ui.cmenu_gridmenu.clear()
  5419. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5420. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5421. _("Grid On/Off"))
  5422. grid_toggle.setCheckable(True)
  5423. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5424. self.ui.cmenu_gridmenu.addSeparator()
  5425. for grid in sorted_list:
  5426. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5427. "%s" % str(grid))
  5428. action.triggered.connect(self.set_grid)
  5429. self.ui.cmenu_gridmenu.addSeparator()
  5430. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5431. _("Add"))
  5432. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5433. _("Delete"))
  5434. grid_add.triggered.connect(self.on_grid_add)
  5435. grid_delete.triggered.connect(self.on_grid_delete)
  5436. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5437. def set_grid(self):
  5438. menu_action = self.sender()
  5439. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5440. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5441. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5442. def on_grid_add(self):
  5443. # ## Current application units in lower Case
  5444. units = self.defaults['units'].lower()
  5445. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5446. text=_('Enter a Grid Value:'),
  5447. min=0.0000, max=99.9999, decimals=4)
  5448. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5449. val, ok = grid_add_popup.get_value()
  5450. if ok:
  5451. if float(val) == 0:
  5452. self.inform.emit('[WARNING_NOTCL] %s' %
  5453. _("Please enter a grid value with non-zero value, in Float format."))
  5454. return
  5455. else:
  5456. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5457. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5458. self.inform.emit('[success] %s...' %
  5459. _("New Grid added"))
  5460. else:
  5461. self.inform.emit('[WARNING_NOTCL] %s...' %
  5462. _("Grid already exists"))
  5463. else:
  5464. self.inform.emit('[WARNING_NOTCL] %s...' %
  5465. _("Adding New Grid cancelled"))
  5466. def on_grid_delete(self):
  5467. # ## Current application units in lower Case
  5468. units = self.defaults['units'].lower()
  5469. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5470. text='Enter a Grid Value:',
  5471. min=0.0000, max=99.9999, decimals=4)
  5472. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5473. val, ok = grid_del_popup.get_value()
  5474. if ok:
  5475. if float(val) == 0:
  5476. self.inform.emit('[WARNING_NOTCL] %s' %
  5477. _("Please enter a grid value with non-zero value, in Float format."))
  5478. return
  5479. else:
  5480. try:
  5481. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5482. except ValueError:
  5483. self.inform.emit('[ERROR_NOTCL]%s...' %
  5484. _(" Grid Value does not exist"))
  5485. return
  5486. self.inform.emit('[success] %s...' %
  5487. _("Grid Value deleted"))
  5488. else:
  5489. self.inform.emit('[WARNING_NOTCL] %s...' %
  5490. _("Delete Grid value cancelled"))
  5491. def on_shortcut_list(self):
  5492. self.defaults.report_usage("on_shortcut_list()")
  5493. # add the tab if it was closed
  5494. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5495. # delete the absolute and relative position and messages in the infobar
  5496. self.ui.position_label.setText("")
  5497. self.ui.rel_position_label.setText("")
  5498. # Switch plot_area to preferences page
  5499. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5500. # self.ui.show()
  5501. def on_select_tab(self, name):
  5502. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5503. if self.ui.splitter.sizes()[0] == 0:
  5504. self.ui.splitter.setSizes([1, 1])
  5505. else:
  5506. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5507. self.ui.splitter.setSizes([0, 1])
  5508. if name == 'project':
  5509. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5510. elif name == 'selected':
  5511. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5512. elif name == 'tool':
  5513. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5514. def on_copy_name(self):
  5515. self.defaults.report_usage("on_copy_name()")
  5516. obj = self.collection.get_active()
  5517. try:
  5518. name = obj.options["name"]
  5519. except AttributeError:
  5520. log.debug("on_copy_name() --> No object selected to copy it's name")
  5521. self.inform.emit('[WARNING_NOTCL]%s' %
  5522. _(" No object selected to copy it's name"))
  5523. return
  5524. self.clipboard.setText(name)
  5525. self.inform.emit(_("Name copied on clipboard ..."))
  5526. def on_mouse_click_over_plot(self, event):
  5527. """
  5528. Default actions are:
  5529. :param event: Contains information about the event, like which button
  5530. was clicked, the pixel coordinates and the axes coordinates.
  5531. :return: None
  5532. """
  5533. self.pos = []
  5534. if self.is_legacy is False:
  5535. event_pos = event.pos
  5536. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5537. # # Set the mouse button for panning
  5538. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5539. else:
  5540. event_pos = (event.xdata, event.ydata)
  5541. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5542. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5543. # So it can receive key presses
  5544. self.plotcanvas.native.setFocus()
  5545. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5546. if self.grid_status():
  5547. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5548. else:
  5549. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5550. try:
  5551. if event.button == 1:
  5552. # Reset here the relative coordinates so there is a new reference on the click position
  5553. if self.rel_point1 is None:
  5554. self.rel_point1 = self.pos
  5555. else:
  5556. self.rel_point2 = copy(self.rel_point1)
  5557. self.rel_point1 = self.pos
  5558. self.on_mouse_move_over_plot(event, origin_click=True)
  5559. except Exception as e:
  5560. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5561. def on_mouse_double_click_over_plot(self, event):
  5562. if event.button == 1:
  5563. self.doubleclick = True
  5564. def on_mouse_move_over_plot(self, event, origin_click=None):
  5565. """
  5566. Callback for the mouse motion event over the plot.
  5567. :param event: Contains information about the event.
  5568. :param origin_click
  5569. :return: None
  5570. """
  5571. if self.is_legacy is False:
  5572. event_pos = event.pos
  5573. if self.defaults["global_pan_button"] == '2':
  5574. pan_button = 2
  5575. else:
  5576. pan_button = 3
  5577. self.event_is_dragging = event.is_dragging
  5578. else:
  5579. event_pos = (event.xdata, event.ydata)
  5580. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5581. if self.defaults["global_pan_button"] == '2':
  5582. pan_button = 3
  5583. else:
  5584. pan_button = 2
  5585. self.event_is_dragging = self.plotcanvas.is_dragging
  5586. # So it can receive key presses but not when the Tcl Shell is active
  5587. if not self.ui.shell_dock.isVisible():
  5588. if not self.plotcanvas.native.hasFocus():
  5589. self.plotcanvas.native.setFocus()
  5590. self.pos_jump = event_pos
  5591. self.ui.popMenu.mouse_is_panning = False
  5592. if origin_click is None:
  5593. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5594. if event.button == pan_button and self.event_is_dragging == 1:
  5595. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5596. if self.ui.popMenu.popup_active:
  5597. self.ui.popMenu.popup_active = False
  5598. return
  5599. self.ui.popMenu.mouse_is_panning = True
  5600. return
  5601. if self.rel_point1 is not None:
  5602. try: # May fail in case mouse not within axes
  5603. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5604. if self.grid_status():
  5605. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5606. # Update cursor
  5607. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5608. symbol='++', edge_color=self.cursor_color_3D,
  5609. edge_width=self.defaults["global_cursor_width"],
  5610. size=self.defaults["global_cursor_size"])
  5611. else:
  5612. pos = (pos_canvas[0], pos_canvas[1])
  5613. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5614. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5615. self.dx = pos[0] - float(self.rel_point1[0])
  5616. self.dy = pos[1] - float(self.rel_point1[1])
  5617. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5618. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5619. self.mouse = [pos[0], pos[1]]
  5620. # if the mouse is moved and the LMB is clicked then the action is a selection
  5621. if self.event_is_dragging == 1 and event.button == 1:
  5622. self.delete_selection_shape()
  5623. if self.dx < 0:
  5624. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5625. face_color=self.defaults['global_alt_sel_fill'])
  5626. self.selection_type = False
  5627. elif self.dx >= 0:
  5628. self.draw_moving_selection_shape(self.pos, pos)
  5629. self.selection_type = True
  5630. else:
  5631. self.selection_type = None
  5632. else:
  5633. self.selection_type = None
  5634. # hover effect - enabled in Preferences -> General -> GUI Settings
  5635. if self.defaults['global_hover']:
  5636. for obj in self.collection.get_list():
  5637. try:
  5638. # select the object(s) only if it is enabled (plotted)
  5639. if obj.options['plot']:
  5640. if obj not in self.collection.get_selected():
  5641. poly_obj = Polygon(
  5642. [(obj.options['xmin'], obj.options['ymin']),
  5643. (obj.options['xmax'], obj.options['ymin']),
  5644. (obj.options['xmax'], obj.options['ymax']),
  5645. (obj.options['xmin'], obj.options['ymax'])]
  5646. )
  5647. if Point(pos).within(poly_obj):
  5648. if obj.isHovering is False:
  5649. obj.isHovering = True
  5650. obj.notHovering = True
  5651. # create the selection box around the selected object
  5652. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5653. else:
  5654. if obj.notHovering is True:
  5655. obj.notHovering = False
  5656. obj.isHovering = False
  5657. self.delete_hover_shape()
  5658. except Exception:
  5659. # the Exception here will happen if we try to select on screen and we have an
  5660. # newly (and empty) just created Geometry or Excellon object that do not have the
  5661. # xmin, xmax, ymin, ymax options.
  5662. # In this case poly_obj creation (see above) will fail
  5663. pass
  5664. except Exception:
  5665. self.ui.position_label.setText("")
  5666. self.ui.rel_position_label.setText("")
  5667. self.mouse = None
  5668. def on_mouse_click_release_over_plot(self, event):
  5669. """
  5670. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5671. and has been registered in ''self.__init__()''.
  5672. :param event: contains information about the event.
  5673. :return:
  5674. """
  5675. if self.is_legacy is False:
  5676. event_pos = event.pos
  5677. right_button = 2
  5678. else:
  5679. event_pos = (event.xdata, event.ydata)
  5680. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5681. right_button = 3
  5682. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5683. if self.grid_status():
  5684. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5685. else:
  5686. pos = (pos_canvas[0], pos_canvas[1])
  5687. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5688. # canvas menu
  5689. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5690. self.ui.popMenu.mouse_is_panning = False
  5691. self.cursor = QtGui.QCursor()
  5692. self.populate_cmenu_grids()
  5693. self.ui.popMenu.popup(self.cursor.pos())
  5694. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5695. # selection and then select a type of selection ("enclosing" or "touching")
  5696. if event.button == 1: # left click
  5697. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5698. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5699. if modifiers == QtCore.Qt.ShiftModifier:
  5700. # do not auto open the Project Tab
  5701. self.click_noproject = True
  5702. self.clipboard.setText(
  5703. self.defaults["global_point_clipboard_format"] %
  5704. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5705. )
  5706. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5707. return
  5708. if self.doubleclick is True:
  5709. self.doubleclick = False
  5710. if self.collection.get_selected():
  5711. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5712. if self.ui.splitter.sizes()[0] == 0:
  5713. self.ui.splitter.setSizes([1, 1])
  5714. try:
  5715. # delete the selection shape(S) as it may be in the way
  5716. self.delete_selection_shape()
  5717. self.delete_hover_shape()
  5718. except Exception as e:
  5719. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5720. return
  5721. else:
  5722. # WORKAROUND for LEGACY MODE
  5723. if self.is_legacy is True:
  5724. # if there is no move on canvas then we have no dragging selection
  5725. if self.dx == 0 or self.dy == 0:
  5726. self.selection_type = None
  5727. if self.selection_type is not None:
  5728. try:
  5729. self.selection_area_handler(self.pos, pos, self.selection_type)
  5730. self.selection_type = None
  5731. except Exception as e:
  5732. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5733. return
  5734. else:
  5735. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5736. if key_modifier == QtCore.Qt.ShiftModifier:
  5737. mod_key = 'Shift'
  5738. elif key_modifier == QtCore.Qt.ControlModifier:
  5739. mod_key = 'Control'
  5740. else:
  5741. mod_key = None
  5742. try:
  5743. if mod_key == self.defaults["global_mselect_key"]:
  5744. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5745. # deselect, and if it's not selected then it will be selected
  5746. # If there is no active command (self.command_active is None) then we check if we clicked
  5747. # on a object by checking the bounding limits against mouse click position
  5748. if self.command_active is None:
  5749. self.select_objects(key='multisel')
  5750. self.delete_hover_shape()
  5751. else:
  5752. # If there is no active command (self.command_active is None) then we check if we clicked
  5753. # on a object by checking the bounding limits against mouse click position
  5754. if self.command_active is None:
  5755. self.select_objects()
  5756. self.delete_hover_shape()
  5757. except Exception as e:
  5758. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5759. return
  5760. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5761. """
  5762. :param start_pos: mouse position when the selection LMB click was done
  5763. :param end_pos: mouse position when the left mouse button is released
  5764. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5765. :return:
  5766. """
  5767. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5768. # delete previous selection shape
  5769. self.delete_selection_shape()
  5770. # make all objects inactive
  5771. self.collection.set_all_inactive()
  5772. for obj in self.collection.get_list():
  5773. try:
  5774. # select the object(s) only if it is enabled (plotted)
  5775. if obj.options['plot']:
  5776. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5777. (obj.options['xmax'], obj.options['ymin']),
  5778. (obj.options['xmax'], obj.options['ymax']),
  5779. (obj.options['xmin'], obj.options['ymax'])])
  5780. if sel_type is True:
  5781. if poly_obj.within(poly_selection):
  5782. # create the selection box around the selected object
  5783. if self.defaults['global_selection_shape'] is True:
  5784. self.draw_selection_shape(obj)
  5785. self.collection.set_active(obj.options['name'])
  5786. else:
  5787. if poly_selection.intersects(poly_obj):
  5788. # create the selection box around the selected object
  5789. if self.defaults['global_selection_shape'] is True:
  5790. self.draw_selection_shape(obj)
  5791. self.collection.set_active(obj.options['name'])
  5792. obj.selection_shape_drawn = True
  5793. except Exception as e:
  5794. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5795. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5796. # In this case poly_obj creation (see above) will fail
  5797. log.debug("App.selection_area_handler() --> %s" % str(e))
  5798. def select_objects(self, key=None):
  5799. """
  5800. Will select objects clicked on canvas
  5801. :param key: for future use in cumulative selection
  5802. :return:
  5803. """
  5804. # list where we store the overlapped objects under our mouse left click position
  5805. if key is None:
  5806. self.objects_under_the_click_list = []
  5807. # Populate the list with the overlapped objects on the click position
  5808. curr_x, curr_y = self.pos
  5809. for obj in self.all_objects_list:
  5810. # ScriptObject and DocumentObject objects can't be selected
  5811. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5812. continue
  5813. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5814. continue
  5815. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5816. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5817. if obj.options['name'] not in self.objects_under_the_click_list:
  5818. if obj.options['plot']:
  5819. # add objects to the objects_under_the_click list only if the object is plotted
  5820. # (active and not disabled)
  5821. self.objects_under_the_click_list.append(obj.options['name'])
  5822. try:
  5823. if self.objects_under_the_click_list:
  5824. curr_sel_obj = self.collection.get_active()
  5825. # case when there is only an object under the click and we toggle it
  5826. if len(self.objects_under_the_click_list) == 1:
  5827. if curr_sel_obj is None:
  5828. self.collection.set_active(self.objects_under_the_click_list[0])
  5829. curr_sel_obj = self.collection.get_active()
  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. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5835. self.on_objects_selection(False)
  5836. self.delete_selection_shape()
  5837. curr_sel_obj.selection_shape_drawn = False
  5838. self.collection.set_active(self.objects_under_the_click_list[0])
  5839. curr_sel_obj = self.collection.get_active()
  5840. # create the selection box around the selected object
  5841. if self.defaults['global_selection_shape'] is True:
  5842. self.draw_selection_shape(curr_sel_obj)
  5843. curr_sel_obj.selection_shape_drawn = True
  5844. self.selected_message(curr_sel_obj=curr_sel_obj)
  5845. elif curr_sel_obj.selection_shape_drawn is False:
  5846. if self.defaults['global_selection_shape'] is True:
  5847. self.draw_selection_shape(curr_sel_obj)
  5848. curr_sel_obj.selection_shape_drawn = True
  5849. else:
  5850. self.on_objects_selection(False)
  5851. self.delete_selection_shape()
  5852. if self.call_source != 'app':
  5853. self.call_source = 'app'
  5854. self.selected_message(curr_sel_obj=curr_sel_obj)
  5855. else:
  5856. # If there is no selected object
  5857. # make active the first element of the overlapped objects list
  5858. if self.collection.get_active() is None:
  5859. self.collection.set_active(self.objects_under_the_click_list[0])
  5860. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5861. name_sel_obj = self.collection.get_active().options['name']
  5862. # In case that there is a selected object but it is not in the overlapped object list
  5863. # make that object inactive and activate the first element in the overlapped object list
  5864. if name_sel_obj not in self.objects_under_the_click_list:
  5865. self.collection.set_inactive(name_sel_obj)
  5866. name_sel_obj = self.objects_under_the_click_list[0]
  5867. self.collection.set_active(name_sel_obj)
  5868. else:
  5869. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5870. self.collection.set_all_inactive()
  5871. self.collection.set_active(
  5872. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5873. curr_sel_obj = self.collection.get_active()
  5874. # delete the possible selection box around a possible selected object
  5875. self.delete_selection_shape()
  5876. curr_sel_obj.selection_shape_drawn = False
  5877. # create the selection box around the selected object
  5878. if self.defaults['global_selection_shape'] is True:
  5879. self.draw_selection_shape(curr_sel_obj)
  5880. curr_sel_obj.selection_shape_drawn = True
  5881. self.selected_message(curr_sel_obj=curr_sel_obj)
  5882. else:
  5883. # deselect everything
  5884. self.on_objects_selection(False)
  5885. # delete the possible selection box around a possible selected object
  5886. self.delete_selection_shape()
  5887. for o in self.collection.get_list():
  5888. o.selection_shape_drawn = False
  5889. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5890. # only when working on App
  5891. if self.call_source == 'app':
  5892. if self.click_noproject is False:
  5893. # if the Tool Tab is in focus don't change focus to Project Tab
  5894. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5895. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5896. else:
  5897. # restore auto open the Project Tab
  5898. self.click_noproject = False
  5899. # delete any text in the status bar, implicitly the last object name that was selected
  5900. # self.inform.emit("")
  5901. else:
  5902. self.call_source = 'app'
  5903. except Exception as e:
  5904. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5905. def selected_message(self, curr_sel_obj):
  5906. if curr_sel_obj:
  5907. if curr_sel_obj.kind == 'gerber':
  5908. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5909. color='green',
  5910. name=str(curr_sel_obj.options['name']),
  5911. tx=_("selected"))
  5912. )
  5913. elif curr_sel_obj.kind == 'excellon':
  5914. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5915. color='brown',
  5916. name=str(curr_sel_obj.options['name']),
  5917. tx=_("selected"))
  5918. )
  5919. elif curr_sel_obj.kind == 'cncjob':
  5920. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5921. color='blue',
  5922. name=str(curr_sel_obj.options['name']),
  5923. tx=_("selected"))
  5924. )
  5925. elif curr_sel_obj.kind == 'geometry':
  5926. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5927. color='red',
  5928. name=str(curr_sel_obj.options['name']),
  5929. tx=_("selected"))
  5930. )
  5931. def delete_hover_shape(self):
  5932. self.hover_shapes.clear()
  5933. self.hover_shapes.redraw()
  5934. def draw_hover_shape(self, sel_obj, color=None):
  5935. """
  5936. :param sel_obj: The object for which the hover shape must be drawn
  5937. :param color: The color of the hover shape
  5938. :return: None
  5939. """
  5940. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5941. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5942. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5943. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5944. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5945. if self.defaults['units'].upper() == 'MM':
  5946. hover_rect = hover_rect.buffer(-0.1)
  5947. hover_rect = hover_rect.buffer(0.2)
  5948. else:
  5949. hover_rect = hover_rect.buffer(-0.00393)
  5950. hover_rect = hover_rect.buffer(0.00787)
  5951. # if color:
  5952. # face = Color(color)
  5953. # face.alpha = 0.2
  5954. # outline = Color(color, alpha=0.8)
  5955. # else:
  5956. # face = Color(self.defaults['global_sel_fill'])
  5957. # face.alpha = 0.2
  5958. # outline = self.defaults['global_sel_line']
  5959. if color:
  5960. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5961. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5962. else:
  5963. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5964. outline = self.defaults['global_sel_line']
  5965. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5966. if self.is_legacy is True:
  5967. self.hover_shapes.redraw()
  5968. def delete_selection_shape(self):
  5969. self.move_tool.sel_shapes.clear()
  5970. self.move_tool.sel_shapes.redraw()
  5971. def draw_selection_shape(self, sel_obj, color=None):
  5972. """
  5973. Will draw a selection shape around the selected object.
  5974. :param sel_obj: The object for which the selection shape must be drawn
  5975. :param color: The color for the selection shape.
  5976. :return: None
  5977. """
  5978. if sel_obj is None:
  5979. return
  5980. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5981. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5982. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5983. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5984. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5985. if self.defaults['units'].upper() == 'MM':
  5986. sel_rect = sel_rect.buffer(-0.1)
  5987. sel_rect = sel_rect.buffer(0.2)
  5988. else:
  5989. sel_rect = sel_rect.buffer(-0.00393)
  5990. sel_rect = sel_rect.buffer(0.00787)
  5991. if color:
  5992. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5993. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5994. else:
  5995. if self.is_legacy is False:
  5996. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5997. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5998. else:
  5999. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  6000. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  6001. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6002. color=outline,
  6003. face_color=face,
  6004. update=True,
  6005. layer=0,
  6006. tolerance=None))
  6007. if self.is_legacy is True:
  6008. self.move_tool.sel_shapes.redraw()
  6009. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6010. """
  6011. Will draw a selection shape when dragging mouse on canvas.
  6012. :param old_coords: Old coordinates
  6013. :param coords: New coordinates
  6014. :param kwargs: Keyword arguments
  6015. :return:
  6016. """
  6017. if 'color' in kwargs:
  6018. color = kwargs['color']
  6019. else:
  6020. color = self.defaults['global_sel_line']
  6021. if 'face_color' in kwargs:
  6022. face_color = kwargs['face_color']
  6023. else:
  6024. face_color = self.defaults['global_sel_fill']
  6025. if 'face_alpha' in kwargs:
  6026. face_alpha = kwargs['face_alpha']
  6027. else:
  6028. face_alpha = 0.3
  6029. x0, y0 = old_coords
  6030. x1, y1 = coords
  6031. pt1 = (x0, y0)
  6032. pt2 = (x1, y0)
  6033. pt3 = (x1, y1)
  6034. pt4 = (x0, y1)
  6035. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6036. # color_t = Color(face_color)
  6037. # color_t.alpha = face_alpha
  6038. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  6039. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6040. layer=0, tolerance=None)
  6041. if self.is_legacy is True:
  6042. self.move_tool.sel_shapes.redraw()
  6043. def on_file_new_click(self):
  6044. """
  6045. Callback for menu item File -> New.
  6046. Executed on clicking the Menu -> File -> New Project
  6047. :return:
  6048. """
  6049. if self.collection.get_list() and self.should_we_save:
  6050. msgbox = QtWidgets.QMessageBox()
  6051. # msgbox.setText("<B>Save changes ...</B>")
  6052. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6053. "Creating a New project will delete them.\n"
  6054. "Do you want to Save the project?"))
  6055. msgbox.setWindowTitle(_("Save changes"))
  6056. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6057. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6058. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6059. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6060. msgbox.setDefaultButton(bt_yes)
  6061. msgbox.exec_()
  6062. response = msgbox.clickedButton()
  6063. if response == bt_yes:
  6064. self.on_file_saveprojectas()
  6065. elif response == bt_cancel:
  6066. return
  6067. elif response == bt_no:
  6068. self.on_file_new()
  6069. else:
  6070. self.on_file_new()
  6071. self.inform.emit('[success] %s...' % _("New Project created"))
  6072. def on_file_new(self, cli=None):
  6073. """
  6074. Returns the application to its startup state. This method is thread-safe.
  6075. :param cli: Boolean. If True this method was run from command line
  6076. :return: None
  6077. """
  6078. self.defaults.report_usage("on_file_new")
  6079. # Remove everything from memory
  6080. App.log.debug("on_file_new()")
  6081. if self.call_source != 'app':
  6082. self.editor2object(cleanup=True)
  6083. # ## EDITOR section
  6084. self.geo_editor = FlatCAMGeoEditor(self)
  6085. self.exc_editor = FlatCAMExcEditor(self)
  6086. self.grb_editor = FlatCAMGrbEditor(self)
  6087. # Clear pool
  6088. self.clear_pool()
  6089. for obj in self.collection.get_list():
  6090. # delete shapes left drawn from mark shape_collections, if any
  6091. if isinstance(obj, GerberObject):
  6092. try:
  6093. for el in obj.mark_shapes:
  6094. obj.mark_shapes[el].clear(update=True)
  6095. obj.mark_shapes[el].enabled = False
  6096. del el
  6097. except AttributeError:
  6098. pass
  6099. # also delete annotation shapes, if any
  6100. elif isinstance(obj, CNCJobObject):
  6101. try:
  6102. obj.text_col.enabled = False
  6103. del obj.text_col
  6104. obj.annotation.clear(update=True)
  6105. del obj.annotation
  6106. except AttributeError:
  6107. pass
  6108. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6109. self.shell.init_tcl()
  6110. self.delete_selection_shape()
  6111. self.collection.delete_all()
  6112. self.setup_component_editor()
  6113. # Clear project filename
  6114. self.project_filename = None
  6115. # Load the application defaults
  6116. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6117. # Re-fresh project options
  6118. self.on_options_app2project()
  6119. # Init Tools
  6120. self.init_tools()
  6121. if cli is None:
  6122. # Close any Tabs opened in the Plot Tab Area section
  6123. for index in range(self.ui.plot_tab_area.count()):
  6124. self.ui.plot_tab_area.closeTab(index)
  6125. # for whatever reason previous command does not close the last tab so I do it manually
  6126. self.ui.plot_tab_area.closeTab(0)
  6127. # # And then add again the Plot Area
  6128. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6129. self.ui.plot_tab_area.protectTab(0)
  6130. # take the focus of the Notebook on Project Tab.
  6131. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6132. self.set_ui_title(name=_("New Project - Not saved"))
  6133. def obj_properties(self):
  6134. """
  6135. Will launch the object Properties Tool
  6136. :return:
  6137. """
  6138. self.defaults.report_usage("obj_properties()")
  6139. self.properties_tool.run(toggle=False)
  6140. def on_project_context_save(self):
  6141. """
  6142. Wrapper, will save the object function of it's type
  6143. :return:
  6144. """
  6145. obj = self.collection.get_active()
  6146. if type(obj) == GeometryObject:
  6147. self.on_file_exportdxf()
  6148. elif type(obj) == ExcellonObject:
  6149. self.on_file_saveexcellon()
  6150. elif type(obj) == CNCJobObject:
  6151. obj.on_exportgcode_button_click()
  6152. elif type(obj) == GerberObject:
  6153. self.on_file_savegerber()
  6154. elif type(obj) == ScriptObject:
  6155. self.on_file_savescript()
  6156. elif type(obj) == DocumentObject:
  6157. self.on_file_savedocument()
  6158. def obj_move(self):
  6159. """
  6160. Callback for the Move menu entry in various Context Menu's.
  6161. :return:
  6162. """
  6163. self.defaults.report_usage("obj_move()")
  6164. self.move_tool.run(toggle=False)
  6165. def on_fileopengerber(self, signal, name=None):
  6166. """
  6167. File menu callback for opening a Gerber.
  6168. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6169. :param name:
  6170. :return: None
  6171. """
  6172. self.defaults.report_usage("on_fileopengerber")
  6173. App.log.debug("on_fileopengerber()")
  6174. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6175. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6176. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6177. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6178. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6179. "*.mil);;" \
  6180. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6181. "Allegro Files (*.art);;" \
  6182. "Mentor Files (*.pho *.gdo);;" \
  6183. "All Files (*.*)"
  6184. if name is None:
  6185. try:
  6186. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6187. directory=self.get_last_folder(),
  6188. filter=_filter_)
  6189. except TypeError:
  6190. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6191. filenames = [str(filename) for filename in filenames]
  6192. else:
  6193. filenames = [name]
  6194. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6195. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6196. _("Opening Gerber file.")),
  6197. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6198. color=QtGui.QColor("gray"))
  6199. if len(filenames) == 0:
  6200. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6201. else:
  6202. for filename in filenames:
  6203. if filename != '':
  6204. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6205. def on_fileopenexcellon(self, signal, name=None):
  6206. """
  6207. File menu callback for opening an Excellon file.
  6208. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6209. :param name:
  6210. :return: None
  6211. """
  6212. self.defaults.report_usage("on_fileopenexcellon")
  6213. App.log.debug("on_fileopenexcellon()")
  6214. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6215. "All Files (*.*)"
  6216. if name is None:
  6217. try:
  6218. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6219. directory=self.get_last_folder(),
  6220. filter=_filter_)
  6221. except TypeError:
  6222. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6223. filenames = [str(filename) for filename in filenames]
  6224. else:
  6225. filenames = [str(name)]
  6226. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6227. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6228. _("Opening Excellon file.")),
  6229. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6230. color=QtGui.QColor("gray"))
  6231. if len(filenames) == 0:
  6232. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6233. else:
  6234. for filename in filenames:
  6235. if filename != '':
  6236. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6237. def on_fileopengcode(self, signal, name=None):
  6238. """
  6239. File menu call back for opening gcode.
  6240. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6241. :param name:
  6242. :return:
  6243. """
  6244. self.defaults.report_usage("on_fileopengcode")
  6245. App.log.debug("on_fileopengcode()")
  6246. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6247. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6248. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6249. "All Files (*.*)"
  6250. if name is None:
  6251. try:
  6252. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6253. directory=self.get_last_folder(),
  6254. filter=_filter_)
  6255. except TypeError:
  6256. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6257. filenames = [str(filename) for filename in filenames]
  6258. else:
  6259. filenames = [name]
  6260. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6261. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6262. _("Opening G-Code file.")),
  6263. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6264. color=QtGui.QColor("gray"))
  6265. if len(filenames) == 0:
  6266. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6267. else:
  6268. for filename in filenames:
  6269. if filename != '':
  6270. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6271. def on_file_openproject(self, signal):
  6272. """
  6273. File menu callback for opening a project.
  6274. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6275. :return: None
  6276. """
  6277. self.defaults.report_usage("on_file_openproject")
  6278. App.log.debug("on_file_openproject()")
  6279. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6280. try:
  6281. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6282. directory=self.get_last_folder(), filter=_filter_)
  6283. except TypeError:
  6284. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6285. # The Qt methods above will return a QString which can cause problems later.
  6286. # So far json.dump() will fail to serialize it.
  6287. # TODO: Improve the serialization methods and remove this fix.
  6288. filename = str(filename)
  6289. if filename == "":
  6290. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6291. else:
  6292. # self.worker_task.emit({'fcn': self.open_project,
  6293. # 'params': [filename]})
  6294. # The above was failing because open_project() is not
  6295. # thread safe. The new_project()
  6296. self.open_project(filename)
  6297. def on_fileopenhpgl2(self, signal, name=None):
  6298. """
  6299. File menu callback for opening a HPGL2.
  6300. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6301. :param name:
  6302. :return: None
  6303. """
  6304. self.defaults.report_usage("on_fileopenhpgl2")
  6305. App.log.debug("on_fileopenhpgl2()")
  6306. _filter_ = "HPGL2 Files (*.plt);;" \
  6307. "All Files (*.*)"
  6308. if name is None:
  6309. try:
  6310. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6311. directory=self.get_last_folder(),
  6312. filter=_filter_)
  6313. except TypeError:
  6314. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6315. filenames = [str(filename) for filename in filenames]
  6316. else:
  6317. filenames = [name]
  6318. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6319. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6320. _("Opening HPGL2 file.")),
  6321. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6322. color=QtGui.QColor("gray"))
  6323. if len(filenames) == 0:
  6324. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6325. else:
  6326. for filename in filenames:
  6327. if filename != '':
  6328. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6329. def on_file_openconfig(self, signal):
  6330. """
  6331. File menu callback for opening a config file.
  6332. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6333. :return: None
  6334. """
  6335. self.defaults.report_usage("on_file_openconfig")
  6336. App.log.debug("on_file_openconfig()")
  6337. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6338. try:
  6339. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6340. directory=self.data_path, filter=_filter_)
  6341. except TypeError:
  6342. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6343. filter=_filter_)
  6344. if filename == "":
  6345. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6346. else:
  6347. self.open_config_file(filename)
  6348. def on_file_exportsvg(self):
  6349. """
  6350. Callback for menu item File->Export SVG.
  6351. :return: None
  6352. """
  6353. self.defaults.report_usage("on_file_exportsvg")
  6354. App.log.debug("on_file_exportsvg()")
  6355. obj = self.collection.get_active()
  6356. if obj is None:
  6357. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6358. msg = _("Please Select a Geometry object to export")
  6359. msgbox = QtWidgets.QMessageBox()
  6360. msgbox.setInformativeText(msg)
  6361. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6362. msgbox.setDefaultButton(bt_ok)
  6363. msgbox.exec_()
  6364. return
  6365. # Check for more compatible types and add as required
  6366. if (not isinstance(obj, GeometryObject)
  6367. and not isinstance(obj, GerberObject)
  6368. and not isinstance(obj, CNCJobObject)
  6369. and not isinstance(obj, ExcellonObject)):
  6370. msg = '[ERROR_NOTCL] %s' % \
  6371. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6372. msgbox = QtWidgets.QMessageBox()
  6373. msgbox.setInformativeText(msg)
  6374. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6375. msgbox.setDefaultButton(bt_ok)
  6376. msgbox.exec_()
  6377. return
  6378. name = obj.options["name"]
  6379. _filter = "SVG File (*.svg);;All Files (*.*)"
  6380. try:
  6381. filename, _f = FCFileSaveDialog.get_saved_filename(
  6382. caption=_("Export SVG"),
  6383. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6384. filter=_filter)
  6385. except TypeError:
  6386. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6387. filename = str(filename)
  6388. if filename == "":
  6389. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6390. return
  6391. else:
  6392. self.export_svg(name, filename)
  6393. if self.defaults["global_open_style"] is False:
  6394. self.file_opened.emit("SVG", filename)
  6395. self.file_saved.emit("SVG", filename)
  6396. def on_file_exportpng(self):
  6397. self.defaults.report_usage("on_file_exportpng")
  6398. App.log.debug("on_file_exportpng()")
  6399. self.date = str(datetime.today()).rpartition('.')[0]
  6400. self.date = ''.join(c for c in self.date if c not in ':-')
  6401. self.date = self.date.replace(' ', '_')
  6402. if self.is_legacy is False:
  6403. image = _screenshot()
  6404. data = np.asarray(image)
  6405. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6406. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6407. return
  6408. filter_ = "PNG File (*.png);;All Files (*.*)"
  6409. try:
  6410. filename, _f = FCFileSaveDialog.get_saved_filename(
  6411. caption=_("Export PNG Image"),
  6412. directory=self.get_last_save_folder() + '/png_' + self.date,
  6413. filter=filter_)
  6414. except TypeError:
  6415. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6416. filename = str(filename)
  6417. if filename == "":
  6418. self.inform.emit(_("Cancelled."))
  6419. return
  6420. else:
  6421. if self.is_legacy is False:
  6422. write_png(filename, data)
  6423. else:
  6424. self.plotcanvas.figure.savefig(filename)
  6425. if self.defaults["global_open_style"] is False:
  6426. self.file_opened.emit("png", filename)
  6427. self.file_saved.emit("png", filename)
  6428. def on_file_savegerber(self):
  6429. """
  6430. Callback for menu item in Project context menu.
  6431. :return: None
  6432. """
  6433. self.defaults.report_usage("on_file_savegerber")
  6434. App.log.debug("on_file_savegerber()")
  6435. obj = self.collection.get_active()
  6436. if obj is None:
  6437. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6438. return
  6439. # Check for more compatible types and add as required
  6440. if not isinstance(obj, GerberObject):
  6441. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6442. return
  6443. name = self.collection.get_active().options["name"]
  6444. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6445. try:
  6446. filename, _f = FCFileSaveDialog.get_saved_filename(
  6447. caption="Save Gerber source file",
  6448. directory=self.get_last_save_folder() + '/' + name,
  6449. filter=_filter)
  6450. except TypeError:
  6451. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6452. filename = str(filename)
  6453. if filename == "":
  6454. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6455. return
  6456. else:
  6457. self.save_source_file(name, filename)
  6458. if self.defaults["global_open_style"] is False:
  6459. self.file_opened.emit("Gerber", filename)
  6460. self.file_saved.emit("Gerber", filename)
  6461. def on_file_savescript(self):
  6462. """
  6463. Callback for menu item in Project context menu.
  6464. :return: None
  6465. """
  6466. self.defaults.report_usage("on_file_savescript")
  6467. App.log.debug("on_file_savescript()")
  6468. obj = self.collection.get_active()
  6469. if obj is None:
  6470. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6471. return
  6472. # Check for more compatible types and add as required
  6473. if not isinstance(obj, ScriptObject):
  6474. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6475. return
  6476. name = self.collection.get_active().options["name"]
  6477. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6478. try:
  6479. filename, _f = FCFileSaveDialog.get_saved_filename(
  6480. caption="Save Script source file",
  6481. directory=self.get_last_save_folder() + '/' + name,
  6482. filter=_filter)
  6483. except TypeError:
  6484. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6485. filename = str(filename)
  6486. if filename == "":
  6487. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6488. return
  6489. else:
  6490. self.save_source_file(name, filename)
  6491. if self.defaults["global_open_style"] is False:
  6492. self.file_opened.emit("Script", filename)
  6493. self.file_saved.emit("Script", filename)
  6494. def on_file_savedocument(self):
  6495. """
  6496. Callback for menu item in Project context menu.
  6497. :return: None
  6498. """
  6499. self.defaults.report_usage("on_file_savedocument")
  6500. App.log.debug("on_file_savedocument()")
  6501. obj = self.collection.get_active()
  6502. if obj is None:
  6503. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6504. return
  6505. # Check for more compatible types and add as required
  6506. if not isinstance(obj, ScriptObject):
  6507. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6508. return
  6509. name = self.collection.get_active().options["name"]
  6510. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6511. try:
  6512. filename, _f = FCFileSaveDialog.get_saved_filename(
  6513. caption="Save Document source file",
  6514. directory=self.get_last_save_folder() + '/' + name,
  6515. filter=_filter)
  6516. except TypeError:
  6517. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6518. filename = str(filename)
  6519. if filename == "":
  6520. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6521. return
  6522. else:
  6523. self.save_source_file(name, filename)
  6524. if self.defaults["global_open_style"] is False:
  6525. self.file_opened.emit("Document", filename)
  6526. self.file_saved.emit("Document", filename)
  6527. def on_file_saveexcellon(self):
  6528. """
  6529. Callback for menu item in project context menu.
  6530. :return: None
  6531. """
  6532. self.defaults.report_usage("on_file_saveexcellon")
  6533. App.log.debug("on_file_saveexcellon()")
  6534. obj = self.collection.get_active()
  6535. if obj is None:
  6536. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6537. return
  6538. # Check for more compatible types and add as required
  6539. if not isinstance(obj, ExcellonObject):
  6540. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6541. return
  6542. name = self.collection.get_active().options["name"]
  6543. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6544. try:
  6545. filename, _f = FCFileSaveDialog.get_saved_filename(
  6546. caption=_("Save Excellon source file"),
  6547. directory=self.get_last_save_folder() + '/' + name,
  6548. filter=_filter)
  6549. except TypeError:
  6550. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6551. filename = str(filename)
  6552. if filename == "":
  6553. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6554. return
  6555. else:
  6556. self.save_source_file(name, filename)
  6557. if self.defaults["global_open_style"] is False:
  6558. self.file_opened.emit("Excellon", filename)
  6559. self.file_saved.emit("Excellon", filename)
  6560. def on_file_exportexcellon(self):
  6561. """
  6562. Callback for menu item File->Export->Excellon.
  6563. :return: None
  6564. """
  6565. self.defaults.report_usage("on_file_exportexcellon")
  6566. App.log.debug("on_file_exportexcellon()")
  6567. obj = self.collection.get_active()
  6568. if obj is None:
  6569. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6570. return
  6571. # Check for more compatible types and add as required
  6572. if not isinstance(obj, ExcellonObject):
  6573. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6574. return
  6575. name = self.collection.get_active().options["name"]
  6576. _filter = self.defaults["excellon_save_filters"]
  6577. try:
  6578. filename, _f = FCFileSaveDialog.get_saved_filename(
  6579. caption=_("Export Excellon"),
  6580. directory=self.get_last_save_folder() + '/' + name,
  6581. filter=_filter)
  6582. except TypeError:
  6583. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6584. filename = str(filename)
  6585. if filename == "":
  6586. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6587. return
  6588. else:
  6589. used_extension = filename.rpartition('.')[2]
  6590. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6591. self.export_excellon(name, filename)
  6592. if self.defaults["global_open_style"] is False:
  6593. self.file_opened.emit("Excellon", filename)
  6594. self.file_saved.emit("Excellon", filename)
  6595. def on_file_exportgerber(self):
  6596. """
  6597. Callback for menu item File->Export->Gerber.
  6598. :return: None
  6599. """
  6600. self.defaults.report_usage("on_file_exportgerber")
  6601. App.log.debug("on_file_exportgerber()")
  6602. obj = self.collection.get_active()
  6603. if obj is None:
  6604. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6605. return
  6606. # Check for more compatible types and add as required
  6607. if not isinstance(obj, GerberObject):
  6608. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6609. return
  6610. name = self.collection.get_active().options["name"]
  6611. _filter_ = self.defaults['gerber_save_filters']
  6612. try:
  6613. filename, _f = FCFileSaveDialog.get_saved_filename(
  6614. caption=_("Export Gerber"),
  6615. directory=self.get_last_save_folder() + '/' + name,
  6616. filter=_filter_)
  6617. except TypeError:
  6618. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6619. filename = str(filename)
  6620. if filename == "":
  6621. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6622. return
  6623. else:
  6624. used_extension = filename.rpartition('.')[2]
  6625. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6626. self.export_gerber(name, filename)
  6627. if self.defaults["global_open_style"] is False:
  6628. self.file_opened.emit("Gerber", filename)
  6629. self.file_saved.emit("Gerber", filename)
  6630. def on_file_exportdxf(self):
  6631. """
  6632. Callback for menu item File->Export DXF.
  6633. :return: None
  6634. """
  6635. self.defaults.report_usage("on_file_exportdxf")
  6636. App.log.debug("on_file_exportdxf()")
  6637. obj = self.collection.get_active()
  6638. if obj is None:
  6639. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6640. msg = _("Please Select a Geometry object to export")
  6641. msgbox = QtWidgets.QMessageBox()
  6642. msgbox.setInformativeText(msg)
  6643. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6644. msgbox.setDefaultButton(bt_ok)
  6645. msgbox.exec_()
  6646. return
  6647. # Check for more compatible types and add as required
  6648. if not isinstance(obj, GeometryObject):
  6649. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6650. msgbox = QtWidgets.QMessageBox()
  6651. msgbox.setInformativeText(msg)
  6652. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6653. msgbox.setDefaultButton(bt_ok)
  6654. msgbox.exec_()
  6655. return
  6656. name = self.collection.get_active().options["name"]
  6657. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6658. try:
  6659. filename, _f = FCFileSaveDialog.get_saved_filename(
  6660. caption=_("Export DXF"),
  6661. directory=self.get_last_save_folder() + '/' + name,
  6662. filter=_filter_)
  6663. except TypeError:
  6664. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6665. filename = str(filename)
  6666. if filename == "":
  6667. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6668. return
  6669. else:
  6670. self.export_dxf(name, filename)
  6671. if self.defaults["global_open_style"] is False:
  6672. self.file_opened.emit("DXF", filename)
  6673. self.file_saved.emit("DXF", filename)
  6674. def on_file_importsvg(self, type_of_obj):
  6675. """
  6676. Callback for menu item File->Import SVG.
  6677. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6678. :type type_of_obj: str
  6679. :return: None
  6680. """
  6681. self.defaults.report_usage("on_file_importsvg")
  6682. App.log.debug("on_file_importsvg()")
  6683. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6684. try:
  6685. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6686. directory=self.get_last_folder(), filter=_filter_)
  6687. except TypeError:
  6688. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6689. filter=_filter_)
  6690. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6691. type_of_obj = "geometry"
  6692. filenames = [str(filename) for filename in filenames]
  6693. if len(filenames) == 0:
  6694. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6695. else:
  6696. for filename in filenames:
  6697. if filename != '':
  6698. self.worker_task.emit({'fcn': self.import_svg,
  6699. 'params': [filename, type_of_obj]})
  6700. def on_file_importdxf(self, type_of_obj):
  6701. """
  6702. Callback for menu item File->Import DXF.
  6703. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6704. :type type_of_obj: str
  6705. :return: None
  6706. """
  6707. self.defaults.report_usage("on_file_importdxf")
  6708. App.log.debug("on_file_importdxf()")
  6709. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6710. try:
  6711. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6712. directory=self.get_last_folder(),
  6713. filter=_filter_)
  6714. except TypeError:
  6715. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6716. filter=_filter_)
  6717. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6718. type_of_obj = "geometry"
  6719. filenames = [str(filename) for filename in filenames]
  6720. if len(filenames) == 0:
  6721. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6722. else:
  6723. for filename in filenames:
  6724. if filename != '':
  6725. self.worker_task.emit({'fcn': self.import_dxf,
  6726. 'params': [filename, type_of_obj]})
  6727. # ###############################################################################################################
  6728. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6729. # ###############################################################################################################
  6730. def init_code_editor(self, name):
  6731. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6732. # add the tab if it was closed
  6733. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6734. self.text_editor_tab.setObjectName('text_editor_tab')
  6735. # delete the absolute and relative position and messages in the infobar
  6736. self.ui.position_label.setText("")
  6737. self.ui.rel_position_label.setText("")
  6738. # first clear previous text in text editor (if any)
  6739. self.text_editor_tab.code_editor.clear()
  6740. self.text_editor_tab.code_editor.setReadOnly(False)
  6741. self.toggle_codeeditor = True
  6742. self.text_editor_tab.code_editor.completer_enable = False
  6743. self.text_editor_tab.buttonRun.hide()
  6744. # make sure to keep a reference to the code editor
  6745. self.reference_code_editor = self.text_editor_tab.code_editor
  6746. # Switch plot_area to CNCJob tab
  6747. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6748. def on_view_source(self):
  6749. """
  6750. Called when the user wants to see the source file of the selected object
  6751. :return:
  6752. """
  6753. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6754. self.proc_container.view.set_busy(_("Loading..."))
  6755. try:
  6756. obj = self.collection.get_active()
  6757. except Exception as e:
  6758. log.debug("App.on_view_source() --> %s" % str(e))
  6759. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6760. return 'fail'
  6761. if obj is None:
  6762. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6763. return 'fail'
  6764. flt = "All Files (*.*)"
  6765. if obj.kind == 'gerber':
  6766. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6767. elif obj.kind == 'excellon':
  6768. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6769. elif obj.kind == 'cncjob':
  6770. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6771. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6772. # add the tab if it was closed
  6773. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6774. self.source_editor_tab.setObjectName('source_editor_tab')
  6775. # delete the absolute and relative position and messages in the infobar
  6776. self.ui.position_label.setText("")
  6777. self.ui.rel_position_label.setText("")
  6778. # first clear previous text in text editor (if any)
  6779. self.source_editor_tab.code_editor.clear()
  6780. self.source_editor_tab.code_editor.setReadOnly(False)
  6781. self.source_editor_tab.code_editor.completer_enable = False
  6782. self.source_editor_tab.buttonRun.hide()
  6783. # Switch plot_area to CNCJob tab
  6784. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6785. try:
  6786. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6787. except TypeError:
  6788. pass
  6789. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6790. try:
  6791. self.source_editor_tab.buttonSave.clicked.disconnect()
  6792. except TypeError:
  6793. pass
  6794. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6795. # then append the text from GCode to the text editor
  6796. if obj.kind == 'cncjob':
  6797. try:
  6798. file = obj.export_gcode(
  6799. preamble=self.defaults["cncjob_prepend"],
  6800. postamble=self.defaults["cncjob_append"],
  6801. to_file=True)
  6802. if file == 'fail':
  6803. return 'fail'
  6804. except AttributeError:
  6805. self.inform.emit('[WARNING_NOTCL] %s' %
  6806. _("There is no selected object for which to see it's source file code."))
  6807. return 'fail'
  6808. else:
  6809. try:
  6810. file = StringIO(obj.source_file)
  6811. except (AttributeError, TypeError):
  6812. self.inform.emit('[WARNING_NOTCL] %s' %
  6813. _("There is no selected object for which to see it's source file code."))
  6814. return 'fail'
  6815. self.source_editor_tab.t_frame.hide()
  6816. try:
  6817. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6818. # for line in file:
  6819. # QtWidgets.QApplication.processEvents()
  6820. # proc_line = str(line).strip('\n')
  6821. # self.source_editor_tab.code_editor.append(proc_line)
  6822. except Exception as e:
  6823. log.debug('App.on_view_source() -->%s' % str(e))
  6824. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6825. return
  6826. self.source_editor_tab.handleTextChanged()
  6827. self.source_editor_tab.t_frame.show()
  6828. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6829. self.proc_container.view.set_idle()
  6830. # self.ui.show()
  6831. def on_toggle_code_editor(self):
  6832. self.defaults.report_usage("on_toggle_code_editor()")
  6833. if self.toggle_codeeditor is False:
  6834. self.init_code_editor(name=_("Code Editor"))
  6835. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6836. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6837. self.text_editor_tab.buttonSave.clicked.disconnect()
  6838. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6839. else:
  6840. for idx in range(self.ui.plot_tab_area.count()):
  6841. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6842. self.ui.plot_tab_area.closeTab(idx)
  6843. break
  6844. self.toggle_codeeditor = False
  6845. def on_code_editor_close(self):
  6846. self.toggle_codeeditor = False
  6847. def goto_text_line(self):
  6848. """
  6849. Will scroll a text to the specified text line.
  6850. :return: None
  6851. """
  6852. dia_box = Dialog_box(title=_("Go to Line ..."),
  6853. label=_("Line:"),
  6854. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6855. initial_text='')
  6856. try:
  6857. line = int(dia_box.location) - 1
  6858. except (ValueError, TypeError):
  6859. line = 0
  6860. if dia_box.ok:
  6861. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6862. # at the top of the window
  6863. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6864. # get the document() of the TextEditor
  6865. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6866. # create a Text Cursor based on the searched line
  6867. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6868. # set cursor of the code editor with the cursor at the searcehd line
  6869. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6870. def on_filenewscript(self, silent=False, name=None, text=None):
  6871. """
  6872. Will create a new script file and open it in the Code Editor
  6873. :param silent: if True will not display status messages
  6874. :param name: if specified will be the name of the new script
  6875. :param text: pass a source file to the newly created script to be loaded in it
  6876. :return: None
  6877. """
  6878. if silent is False:
  6879. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6880. # delete the absolute and relative position and messages in the infobar
  6881. self.ui.position_label.setText("")
  6882. self.ui.rel_position_label.setText("")
  6883. if name is not None:
  6884. self.new_script_object(name=name, text=text)
  6885. else:
  6886. self.new_script_object(text=text)
  6887. # script_text = script_obj.source_file
  6888. #
  6889. # self.proc_container.view.set_busy(_("Loading..."))
  6890. # script_obj.script_editor_tab.t_frame.hide()
  6891. #
  6892. # script_obj.script_editor_tab.t_frame.show()
  6893. # self.proc_container.view.set_idle()
  6894. def on_fileopenscript(self, name=None, silent=False):
  6895. """
  6896. Will open a Tcl script file into the Code Editor
  6897. :param silent: if True will not display status messages
  6898. :param name: name of a Tcl script file to open
  6899. :return:
  6900. """
  6901. self.defaults.report_usage("on_fileopenscript")
  6902. App.log.debug("on_fileopenscript()")
  6903. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6904. "All Files (*.*)"
  6905. if name:
  6906. filenames = [name]
  6907. else:
  6908. try:
  6909. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6910. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6911. except TypeError:
  6912. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6913. if len(filenames) == 0:
  6914. if silent is False:
  6915. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6916. else:
  6917. for filename in filenames:
  6918. if filename != '':
  6919. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6920. def on_fileopenscript_example(self, name=None, silent=False):
  6921. """
  6922. Will open a Tcl script file into the Code Editor
  6923. :param silent: if True will not display status messages
  6924. :param name: name of a Tcl script file to open
  6925. :return:
  6926. """
  6927. self.report_usage("on_fileopenscript_example")
  6928. App.log.debug("on_fileopenscript_example()")
  6929. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6930. "All Files (*.*)"
  6931. # test if the app was frozen and choose the path for the configuration file
  6932. if getattr(sys, "frozen", False) is True:
  6933. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6934. else:
  6935. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6936. if name:
  6937. filenames = [name]
  6938. else:
  6939. try:
  6940. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6941. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6942. except TypeError:
  6943. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6944. if len(filenames) == 0:
  6945. if silent is False:
  6946. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6947. else:
  6948. for filename in filenames:
  6949. if filename != '':
  6950. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6951. def on_filerunscript(self, name=None, silent=False):
  6952. """
  6953. File menu callback for loading and running a TCL script.
  6954. :param silent: if True will not display status messages
  6955. :param name: name of a Tcl script file to be run by FlatCAM
  6956. :return: None
  6957. """
  6958. self.defaults.report_usage("on_filerunscript")
  6959. App.log.debug("on_file_runscript()")
  6960. if name:
  6961. filename = name
  6962. if self.cmd_line_headless != 1:
  6963. self.splash.showMessage('%s: %ssec\n%s' %
  6964. (_("Canvas initialization started.\n"
  6965. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6966. _("Executing ScriptObject file.")
  6967. ),
  6968. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6969. color=QtGui.QColor("gray"))
  6970. else:
  6971. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6972. "All Files (*.*)"
  6973. try:
  6974. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6975. directory=self.get_last_folder(), filter=_filter_)
  6976. except TypeError:
  6977. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6978. # The Qt methods above will return a QString which can cause problems later.
  6979. # So far json.dump() will fail to serialize it.
  6980. filename = str(filename)
  6981. if filename == "":
  6982. if silent is False:
  6983. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6984. else:
  6985. if self.cmd_line_headless != 1:
  6986. if self.ui.shell_dock.isHidden():
  6987. self.ui.shell_dock.show()
  6988. try:
  6989. with open(filename, "r") as tcl_script:
  6990. cmd_line_shellfile_content = tcl_script.read()
  6991. if self.cmd_line_headless != 1:
  6992. self.shell.exec_command(cmd_line_shellfile_content)
  6993. else:
  6994. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6995. if silent is False:
  6996. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6997. except Exception as e:
  6998. log.debug("App.on_filerunscript() -> %s" % str(e))
  6999. sys.exit(2)
  7000. def on_file_saveproject(self, silent=False):
  7001. """
  7002. Callback for menu item File->Save Project. Saves the project to
  7003. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7004. if set to None. The project is saved by calling ``self.save_project()``.
  7005. :param silent: if True will not display status messages
  7006. :return: None
  7007. """
  7008. self.defaults.report_usage("on_file_saveproject")
  7009. if self.project_filename is None:
  7010. self.on_file_saveprojectas()
  7011. else:
  7012. self.worker_task.emit({'fcn': self.save_project,
  7013. 'params': [self.project_filename, silent]})
  7014. if self.defaults["global_open_style"] is False:
  7015. self.file_opened.emit("project", self.project_filename)
  7016. self.file_saved.emit("project", self.project_filename)
  7017. self.set_ui_title(name=self.project_filename)
  7018. self.should_we_save = False
  7019. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7020. """
  7021. Callback for menu item File->Save Project As... Opens a file
  7022. chooser and saves the project to the given file via
  7023. ``self.save_project()``.
  7024. :param make_copy if to be create a copy of the project; boolean
  7025. :param use_thread: if to be run in a separate thread; boolean
  7026. :param quit_action: if to be followed by quiting the application; boolean
  7027. :return: None
  7028. """
  7029. self.defaults.report_usage("on_file_saveprojectas")
  7030. self.date = str(datetime.today()).rpartition('.')[0]
  7031. self.date = ''.join(c for c in self.date if c not in ':-')
  7032. self.date = self.date.replace(' ', '_')
  7033. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7034. try:
  7035. filename, _f = FCFileSaveDialog.get_saved_filename(
  7036. caption=_("Save Project As ..."),
  7037. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  7038. proj=_("Project")),
  7039. filter=filter_
  7040. )
  7041. except TypeError:
  7042. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  7043. filename = str(filename)
  7044. if filename == '':
  7045. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7046. return
  7047. if use_thread is True:
  7048. self.worker_task.emit({'fcn': self.save_project,
  7049. 'params': [filename, quit_action]})
  7050. else:
  7051. self.save_project(filename, quit_action)
  7052. # self.save_project(filename)
  7053. if self.defaults["global_open_style"] is False:
  7054. self.file_opened.emit("project", filename)
  7055. self.file_saved.emit("project", filename)
  7056. if not make_copy:
  7057. self.project_filename = filename
  7058. self.set_ui_title(name=self.project_filename)
  7059. self.should_we_save = False
  7060. def on_file_save_objects_pdf(self, use_thread=True):
  7061. self.date = str(datetime.today()).rpartition('.')[0]
  7062. self.date = ''.join(c for c in self.date if c not in ':-')
  7063. self.date = self.date.replace(' ', '_')
  7064. try:
  7065. obj_selection = self.collection.get_selected()
  7066. if len(obj_selection) == 1:
  7067. obj_name = str(obj_selection[0].options['name'])
  7068. else:
  7069. obj_name = _("FlatCAM objects print")
  7070. except AttributeError as err:
  7071. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7072. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7073. return
  7074. if not obj_selection:
  7075. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7076. return
  7077. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7078. try:
  7079. filename, _f = FCFileSaveDialog.get_saved_filename(
  7080. caption=_("Save Object as PDF ..."),
  7081. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7082. obj_name=obj_name,
  7083. date=self.date),
  7084. filter=filter_
  7085. )
  7086. except TypeError:
  7087. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7088. filename = str(filename)
  7089. if filename == '':
  7090. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7091. return
  7092. if use_thread is True:
  7093. proc = self.proc_container.new(_("Printing PDF ... Please wait."))
  7094. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7095. else:
  7096. self.save_pdf(filename, obj_selection)
  7097. # self.save_project(filename)
  7098. if self.defaults["global_open_style"] is False:
  7099. self.file_opened.emit("pdf", filename)
  7100. self.file_saved.emit("pdf", filename)
  7101. def save_pdf(self, file_name, obj_selection):
  7102. p_size = self.defaults['global_workspaceT']
  7103. orientation = self.defaults['global_workspace_orientation']
  7104. color = 'black'
  7105. transparency_level = 1.0
  7106. self.pagesize = {}
  7107. self.pagesize.update(
  7108. {
  7109. 'Bounds': None,
  7110. 'A0': (841 * mm, 1189 * mm),
  7111. 'A1': (594 * mm, 841 * mm),
  7112. 'A2': (420 * mm, 594 * mm),
  7113. 'A3': (297 * mm, 420 * mm),
  7114. 'A4': (210 * mm, 297 * mm),
  7115. 'A5': (148 * mm, 210 * mm),
  7116. 'A6': (105 * mm, 148 * mm),
  7117. 'A7': (74 * mm, 105 * mm),
  7118. 'A8': (52 * mm, 74 * mm),
  7119. 'A9': (37 * mm, 52 * mm),
  7120. 'A10': (26 * mm, 37 * mm),
  7121. 'B0': (1000 * mm, 1414 * mm),
  7122. 'B1': (707 * mm, 1000 * mm),
  7123. 'B2': (500 * mm, 707 * mm),
  7124. 'B3': (353 * mm, 500 * mm),
  7125. 'B4': (250 * mm, 353 * mm),
  7126. 'B5': (176 * mm, 250 * mm),
  7127. 'B6': (125 * mm, 176 * mm),
  7128. 'B7': (88 * mm, 125 * mm),
  7129. 'B8': (62 * mm, 88 * mm),
  7130. 'B9': (44 * mm, 62 * mm),
  7131. 'B10': (31 * mm, 44 * mm),
  7132. 'C0': (917 * mm, 1297 * mm),
  7133. 'C1': (648 * mm, 917 * mm),
  7134. 'C2': (458 * mm, 648 * mm),
  7135. 'C3': (324 * mm, 458 * mm),
  7136. 'C4': (229 * mm, 324 * mm),
  7137. 'C5': (162 * mm, 229 * mm),
  7138. 'C6': (114 * mm, 162 * mm),
  7139. 'C7': (81 * mm, 114 * mm),
  7140. 'C8': (57 * mm, 81 * mm),
  7141. 'C9': (40 * mm, 57 * mm),
  7142. 'C10': (28 * mm, 40 * mm),
  7143. # American paper sizes
  7144. 'LETTER': (8.5 * inch, 11 * inch),
  7145. 'LEGAL': (8.5 * inch, 14 * inch),
  7146. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7147. # From https://en.wikipedia.org/wiki/Paper_size
  7148. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7149. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7150. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7151. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7152. 'LEDGER': (17 * inch, 11 * inch),
  7153. }
  7154. )
  7155. exported_svg = []
  7156. for obj in obj_selection:
  7157. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7158. scale_factor_x=None, scale_factor_y=None,
  7159. skew_factor_x=None, skew_factor_y=None,
  7160. mirror=None)
  7161. if obj.kind.lower() == 'gerber':
  7162. # color = self.defaults["gerber_plot_fill"][:-2]
  7163. color = obj.fill_color[:-2]
  7164. elif obj.kind.lower() == 'excellon':
  7165. color = '#C40000'
  7166. elif obj.kind.lower() == 'geometry':
  7167. color = self.defaults["global_draw_color"]
  7168. # Change the attributes of the exported SVG
  7169. # We don't need stroke-width
  7170. # We set opacity to maximum
  7171. # We set the colour to WHITE
  7172. root = ET.fromstring(svg_obj)
  7173. for child in root:
  7174. child.set('fill', str(color))
  7175. child.set('opacity', str(transparency_level))
  7176. child.set('stroke', str(color))
  7177. exported_svg.append(ET.tostring(root))
  7178. xmin = Inf
  7179. ymin = Inf
  7180. xmax = -Inf
  7181. ymax = -Inf
  7182. for obj in obj_selection:
  7183. try:
  7184. gxmin, gymin, gxmax, gymax = obj.bounds()
  7185. xmin = min([xmin, gxmin])
  7186. ymin = min([ymin, gymin])
  7187. xmax = max([xmax, gxmax])
  7188. ymax = max([ymax, gymax])
  7189. except Exception as e:
  7190. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7191. # Determine bounding area for svg export
  7192. bounds = [xmin, ymin, xmax, ymax]
  7193. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7194. # This contain the measure units
  7195. uom = obj_selection[0].units.lower()
  7196. # Define a boundary around SVG of about 1.0mm (~39mils)
  7197. if uom in "mm":
  7198. boundary = 1.0
  7199. else:
  7200. boundary = 0.0393701
  7201. # Convert everything to strings for use in the xml doc
  7202. svgwidth = str(size[0] + (2 * boundary))
  7203. svgheight = str(size[1] + (2 * boundary))
  7204. minx = str(bounds[0] - boundary)
  7205. miny = str(bounds[1] + boundary + size[1])
  7206. # Add a SVG Header and footer to the svg output from shapely
  7207. # The transform flips the Y Axis so that everything renders
  7208. # properly within svg apps such as inkscape
  7209. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7210. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7211. svg_header += 'width="' + svgwidth + uom + '" '
  7212. svg_header += 'height="' + svgheight + uom + '" '
  7213. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7214. svg_header += '>'
  7215. svg_header += '<g transform="scale(1,-1)">'
  7216. svg_footer = '</g> </svg>'
  7217. svg_elem = str(svg_header)
  7218. for svg_item in exported_svg:
  7219. svg_elem += str(svg_item)
  7220. svg_elem += str(svg_footer)
  7221. # Parse the xml through a xml parser just to add line feeds
  7222. # and to make it look more pretty for the output
  7223. doc = parse_xml_string(svg_elem)
  7224. doc_final = doc.toprettyxml()
  7225. try:
  7226. if self.defaults['units'].upper() == 'IN':
  7227. unit = inch
  7228. else:
  7229. unit = mm
  7230. doc_final = StringIO(doc_final)
  7231. drawing = svg2rlg(doc_final)
  7232. if p_size == 'Bounds':
  7233. renderPDF.drawToFile(drawing, file_name)
  7234. else:
  7235. if orientation == 'p':
  7236. page_size = portrait(self.pagesize[p_size])
  7237. else:
  7238. page_size = landscape(self.pagesize[p_size])
  7239. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7240. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7241. renderPDF.draw(drawing, my_canvas, 0, 0)
  7242. my_canvas.save()
  7243. except Exception as e:
  7244. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7245. return 'fail'
  7246. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7247. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7248. """
  7249. Exports a Geometry Object to an SVG file.
  7250. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7251. :param filename: Path to the SVG file to save to.
  7252. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7253. :return:
  7254. """
  7255. self.defaults.report_usage("export_svg()")
  7256. if filename is None:
  7257. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7258. is not None else self.defaults["global_last_folder"]
  7259. self.log.debug("export_svg()")
  7260. try:
  7261. obj = self.collection.get_by_name(str(obj_name))
  7262. except Exception:
  7263. # TODO: The return behavior has not been established... should raise exception?
  7264. return "Could not retrieve object: %s" % obj_name
  7265. with self.proc_container.new(_("Exporting SVG")) as proc:
  7266. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7267. # Determine bounding area for svg export
  7268. bounds = obj.bounds()
  7269. size = obj.size()
  7270. # Convert everything to strings for use in the xml doc
  7271. svgwidth = str(size[0])
  7272. svgheight = str(size[1])
  7273. minx = str(bounds[0])
  7274. miny = str(bounds[1] - size[1])
  7275. uom = obj.units.lower()
  7276. # Add a SVG Header and footer to the svg output from shapely
  7277. # The transform flips the Y Axis so that everything renders
  7278. # properly within svg apps such as inkscape
  7279. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7280. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7281. svg_header += 'width="' + svgwidth + uom + '" '
  7282. svg_header += 'height="' + svgheight + uom + '" '
  7283. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7284. svg_header += '<g transform="scale(1,-1)">'
  7285. svg_footer = '</g> </svg>'
  7286. svg_elem = svg_header + exported_svg + svg_footer
  7287. # Parse the xml through a xml parser just to add line feeds
  7288. # and to make it look more pretty for the output
  7289. svgcode = parse_xml_string(svg_elem)
  7290. svgcode = svgcode.toprettyxml()
  7291. try:
  7292. with open(filename, 'w') as fp:
  7293. fp.write(svgcode)
  7294. except PermissionError:
  7295. self.inform.emit('[WARNING] %s' %
  7296. _("Permission denied, saving not possible.\n"
  7297. "Most likely another app is holding the file open and not accessible."))
  7298. return 'fail'
  7299. if self.defaults["global_open_style"] is False:
  7300. self.file_opened.emit("SVG", filename)
  7301. self.file_saved.emit("SVG", filename)
  7302. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7303. def save_source_file(self, obj_name, filename, use_thread=True):
  7304. """
  7305. Exports a FlatCAM Object to an Gerber/Excellon file.
  7306. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7307. :param filename: Path to the Gerber file to save to.
  7308. :param use_thread: if to be run in a separate thread
  7309. :return:
  7310. """
  7311. self.defaults.report_usage("save source file()")
  7312. if filename is None:
  7313. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7314. is not None else self.defaults["global_last_folder"]
  7315. self.log.debug("save source file()")
  7316. obj = self.collection.get_by_name(obj_name)
  7317. file_string = StringIO(obj.source_file)
  7318. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7319. if file_string.getvalue() == '':
  7320. self.inform.emit('[ERROR_NOTCL] %s' %
  7321. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7322. return 'fail'
  7323. try:
  7324. with open(filename, 'w') as file:
  7325. file.writelines('G04*\n')
  7326. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7327. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7328. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7329. file.writelines('G04 Created on : %s*\n' % time_string)
  7330. for line in file_string:
  7331. file.writelines(line)
  7332. except PermissionError:
  7333. self.inform.emit('[WARNING] %s' %
  7334. _("Permission denied, saving not possible.\n"
  7335. "Most likely another app is holding the file open and not accessible."))
  7336. return 'fail'
  7337. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7338. """
  7339. Exports a Excellon Object to an Excellon file.
  7340. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7341. :param filename: Path to the Excellon file to save to.
  7342. :param local_use:
  7343. :param use_thread: if to be run in a separate thread
  7344. :return:
  7345. """
  7346. self.defaults.report_usage("export_excellon()")
  7347. if filename is None:
  7348. if self.defaults["global_last_save_folder"]:
  7349. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7350. else:
  7351. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7352. self.log.debug("export_excellon()")
  7353. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7354. self.defaults["excellon_exp_decimals"]
  7355. )
  7356. if local_use is None:
  7357. try:
  7358. obj = self.collection.get_by_name(str(obj_name))
  7359. except Exception:
  7360. return "Could not retrieve object: %s" % obj_name
  7361. else:
  7362. obj = local_use
  7363. if not isinstance(obj, ExcellonObject):
  7364. self.inform.emit('[ERROR_NOTCL] %s' %
  7365. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7366. return
  7367. # updated units
  7368. eunits = self.defaults["excellon_exp_units"]
  7369. ewhole = self.defaults["excellon_exp_integer"]
  7370. efract = self.defaults["excellon_exp_decimals"]
  7371. ezeros = self.defaults["excellon_exp_zeros"]
  7372. eformat = self.defaults["excellon_exp_format"]
  7373. slot_type = self.defaults["excellon_exp_slot_type"]
  7374. fc_units = self.defaults['units'].upper()
  7375. if fc_units == 'MM':
  7376. factor = 1 if eunits == 'METRIC' else 0.03937
  7377. else:
  7378. factor = 25.4 if eunits == 'METRIC' else 1
  7379. def make_excellon():
  7380. try:
  7381. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7382. header = 'M48\n'
  7383. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7384. (str(self.version), str(self.version_date))
  7385. header += ';Filename: %s' % str(obj_name) + '\n'
  7386. header += ';Created on : %s' % time_str + '\n'
  7387. if eformat == 'dec':
  7388. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7389. header += eunits + '\n'
  7390. for tool in obj.tools:
  7391. if eunits == 'METRIC':
  7392. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7393. tool=str(tool),
  7394. dec=2)
  7395. else:
  7396. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7397. tool=str(tool),
  7398. dec=4)
  7399. else:
  7400. if ezeros == 'LZ':
  7401. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7402. form='ndec', e_zeros='LZ', factor=factor,
  7403. slot_type=slot_type)
  7404. header += '%s,%s\n' % (eunits, 'LZ')
  7405. header += format_exc
  7406. for tool in obj.tools:
  7407. if eunits == 'METRIC':
  7408. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7409. tool=str(tool),
  7410. dec=2)
  7411. else:
  7412. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7413. tool=str(tool),
  7414. dec=4)
  7415. else:
  7416. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7417. form='ndec', e_zeros='TZ', factor=factor,
  7418. slot_type=slot_type)
  7419. header += '%s,%s\n' % (eunits, 'TZ')
  7420. header += format_exc
  7421. for tool in obj.tools:
  7422. if eunits == 'METRIC':
  7423. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7424. tool=str(tool),
  7425. dec=2)
  7426. else:
  7427. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7428. tool=str(tool),
  7429. dec=4)
  7430. header += '%\n'
  7431. footer = 'M30\n'
  7432. exported_excellon = header
  7433. exported_excellon += excellon_code
  7434. exported_excellon += footer
  7435. if local_use is None:
  7436. try:
  7437. with open(filename, 'w') as fp:
  7438. fp.write(exported_excellon)
  7439. except PermissionError:
  7440. self.inform.emit('[WARNING] %s' %
  7441. _("Permission denied, saving not possible.\n"
  7442. "Most likely another app is holding the file open and not accessible."))
  7443. return 'fail'
  7444. if self.defaults["global_open_style"] is False:
  7445. self.file_opened.emit("Excellon", filename)
  7446. self.file_saved.emit("Excellon", filename)
  7447. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7448. else:
  7449. return exported_excellon
  7450. except Exception as e:
  7451. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7452. return 'fail'
  7453. if use_thread is True:
  7454. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7455. def job_thread_exc(app_obj):
  7456. ret = make_excellon()
  7457. if ret == 'fail':
  7458. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7459. return
  7460. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7461. else:
  7462. eret = make_excellon()
  7463. if eret == 'fail':
  7464. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7465. return 'fail'
  7466. if local_use is not None:
  7467. return eret
  7468. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7469. """
  7470. Exports a Gerber Object to an Gerber file.
  7471. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7472. :param filename: Path to the Gerber file to save to.
  7473. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7474. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7475. :param use_thread: if to be run in a separate thread
  7476. :return:
  7477. """
  7478. self.defaults.report_usage("export_gerber()")
  7479. if filename is None:
  7480. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7481. is not None else self.defaults["global_last_folder"]
  7482. self.log.debug("export_gerber()")
  7483. if local_use is None:
  7484. try:
  7485. obj = self.collection.get_by_name(str(obj_name))
  7486. except Exception:
  7487. return "Could not retrieve object: %s" % obj_name
  7488. else:
  7489. obj = local_use
  7490. # updated units
  7491. gunits = self.defaults["gerber_exp_units"]
  7492. gwhole = self.defaults["gerber_exp_integer"]
  7493. gfract = self.defaults["gerber_exp_decimals"]
  7494. gzeros = self.defaults["gerber_exp_zeros"]
  7495. fc_units = self.defaults['units'].upper()
  7496. if fc_units == 'MM':
  7497. factor = 1 if gunits == 'MM' else 0.03937
  7498. else:
  7499. factor = 25.4 if gunits == 'MM' else 1
  7500. def make_gerber():
  7501. try:
  7502. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7503. header = 'G04*\n'
  7504. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7505. (str(self.version), str(self.version_date))
  7506. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7507. header += 'G04 Created on : %s*' % time_str + '\n'
  7508. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7509. header += "%MO{units}*%\n".format(units=gunits)
  7510. for apid in obj.apertures:
  7511. if obj.apertures[apid]['type'] == 'C':
  7512. header += "%ADD{apid}{type},{size}*%\n".format(
  7513. apid=str(apid),
  7514. type='C',
  7515. size=(factor * obj.apertures[apid]['size'])
  7516. )
  7517. elif obj.apertures[apid]['type'] == 'R':
  7518. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7519. apid=str(apid),
  7520. type='R',
  7521. width=(factor * obj.apertures[apid]['width']),
  7522. height=(factor * obj.apertures[apid]['height'])
  7523. )
  7524. elif obj.apertures[apid]['type'] == 'O':
  7525. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7526. apid=str(apid),
  7527. type='O',
  7528. width=(factor * obj.apertures[apid]['width']),
  7529. height=(factor * obj.apertures[apid]['height'])
  7530. )
  7531. header += '\n'
  7532. # obsolete units but some software may need it
  7533. if gunits == 'IN':
  7534. header += 'G70*\n'
  7535. else:
  7536. header += 'G71*\n'
  7537. # Absolute Mode
  7538. header += 'G90*\n'
  7539. header += 'G01*\n'
  7540. # positive polarity
  7541. header += '%LPD*%\n'
  7542. footer = 'M02*\n'
  7543. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7544. exported_gerber = header
  7545. exported_gerber += gerber_code
  7546. exported_gerber += footer
  7547. if local_use is None:
  7548. try:
  7549. with open(filename, 'w') as fp:
  7550. fp.write(exported_gerber)
  7551. except PermissionError:
  7552. self.inform.emit('[WARNING] %s' %
  7553. _("Permission denied, saving not possible.\n"
  7554. "Most likely another app is holding the file open and not accessible."))
  7555. return 'fail'
  7556. if self.defaults["global_open_style"] is False:
  7557. self.file_opened.emit("Gerber", filename)
  7558. self.file_saved.emit("Gerber", filename)
  7559. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7560. else:
  7561. return exported_gerber
  7562. except Exception as e:
  7563. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7564. return 'fail'
  7565. if use_thread is True:
  7566. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7567. def job_thread_grb(app_obj):
  7568. ret = make_gerber()
  7569. if ret == 'fail':
  7570. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7571. return
  7572. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7573. else:
  7574. gret = make_gerber()
  7575. if gret == 'fail':
  7576. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7577. return 'fail'
  7578. if local_use is not None:
  7579. return gret
  7580. def export_dxf(self, obj_name, filename, use_thread=True):
  7581. """
  7582. Exports a Geometry Object to an DXF file.
  7583. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7584. :param filename: Path to the DXF file to save to.
  7585. :param use_thread: if to be run in a separate thread
  7586. :return:
  7587. """
  7588. self.defaults.report_usage("export_dxf()")
  7589. if filename is None:
  7590. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7591. is not None else self.defaults["global_last_folder"]
  7592. self.log.debug("export_dxf()")
  7593. try:
  7594. obj = self.collection.get_by_name(str(obj_name))
  7595. except Exception:
  7596. # TODO: The return behavior has not been established... should raise exception?
  7597. return "Could not retrieve object: %s" % obj_name
  7598. def make_dxf():
  7599. try:
  7600. dxf_code = obj.export_dxf()
  7601. dxf_code.saveas(filename)
  7602. if self.defaults["global_open_style"] is False:
  7603. self.file_opened.emit("DXF", filename)
  7604. self.file_saved.emit("DXF", filename)
  7605. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7606. except Exception:
  7607. return 'fail'
  7608. if use_thread is True:
  7609. with self.proc_container.new(_("Exporting DXF")) as proc:
  7610. def job_thread_exc(app_obj):
  7611. ret_dxf_val = make_dxf()
  7612. if ret_dxf_val == 'fail':
  7613. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7614. return
  7615. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7616. else:
  7617. ret = make_dxf()
  7618. if ret == 'fail':
  7619. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7620. return
  7621. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7622. """
  7623. Adds a new Geometry Object to the projects and populates
  7624. it with shapes extracted from the SVG file.
  7625. :param filename: Path to the SVG file.
  7626. :param geo_type: Type of FlatCAM object that will be created from SVG
  7627. :param outname:
  7628. :return:
  7629. """
  7630. self.defaults.report_usage("import_svg()")
  7631. log.debug("App.import_svg()")
  7632. obj_type = ""
  7633. if geo_type is None or geo_type == "geometry":
  7634. obj_type = "geometry"
  7635. elif geo_type == "gerber":
  7636. obj_type = "gerber"
  7637. else:
  7638. self.inform.emit('[ERROR_NOTCL] %s' %
  7639. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7640. return
  7641. units = self.defaults['units'].upper()
  7642. def obj_init(geo_obj, app_obj):
  7643. geo_obj.import_svg(filename, obj_type, units=units)
  7644. geo_obj.multigeo = False
  7645. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7646. with self.proc_container.new(_("Importing SVG")) as proc:
  7647. # Object name
  7648. name = outname or filename.split('/')[-1].split('\\')[-1]
  7649. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7650. if ret == 'fail':
  7651. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7652. return 'fail'
  7653. # Register recent file
  7654. self.file_opened.emit("svg", filename)
  7655. # GUI feedback
  7656. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7657. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7658. """
  7659. Adds a new Geometry Object to the projects and populates
  7660. it with shapes extracted from the DXF file.
  7661. :param filename: Path to the DXF file.
  7662. :param geo_type: Type of FlatCAM object that will be created from DXF
  7663. :param outname: Name for the imported Geometry
  7664. :return:
  7665. """
  7666. self.defaults.report_usage("import_dxf()")
  7667. obj_type = ""
  7668. if geo_type is None or geo_type == "geometry":
  7669. obj_type = "geometry"
  7670. elif geo_type == "gerber":
  7671. obj_type = geo_type
  7672. else:
  7673. self.inform.emit('[ERROR_NOTCL] %s' %
  7674. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7675. return
  7676. units = self.defaults['units'].upper()
  7677. def obj_init(geo_obj, app_obj):
  7678. geo_obj.import_dxf(filename, obj_type, units=units)
  7679. geo_obj.multigeo = False
  7680. with self.proc_container.new(_("Importing DXF")):
  7681. # Object name
  7682. name = outname or filename.split('/')[-1].split('\\')[-1]
  7683. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7684. if ret == 'fail':
  7685. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7686. return 'fail'
  7687. # Register recent file
  7688. self.file_opened.emit("dxf", filename)
  7689. # GUI feedback
  7690. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7691. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7692. """
  7693. Opens a Gerber file, parses it and creates a new object for
  7694. it in the program. Thread-safe.
  7695. :param outname: Name of the resulting object. None causes the
  7696. name to be that of the file. Str.
  7697. :param filename: Gerber file filename
  7698. :type filename: str
  7699. :param plot: boolean, to plot or not the resulting object
  7700. :param from_tcl: True if run from Tcl Shell
  7701. :return: None
  7702. """
  7703. # How the object should be initialized
  7704. def obj_init(gerber_obj, app_obj):
  7705. assert isinstance(gerber_obj, GerberObject), \
  7706. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7707. # Opening the file happens here
  7708. try:
  7709. gerber_obj.parse_file(filename)
  7710. except IOError:
  7711. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7712. return "fail"
  7713. except ParseError as err:
  7714. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7715. app_obj.log.error(str(err))
  7716. return "fail"
  7717. except Exception as e:
  7718. log.debug("App.open_gerber() --> %s" % str(e))
  7719. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7720. msg += traceback.format_exc()
  7721. app_obj.inform.emit(msg)
  7722. return "fail"
  7723. if gerber_obj.is_empty():
  7724. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7725. _("Object is not Gerber file or empty. Aborting object creation."))
  7726. return "fail"
  7727. App.log.debug("open_gerber()")
  7728. with self.proc_container.new(_("Opening Gerber")):
  7729. # Object name
  7730. name = outname or filename.split('/')[-1].split('\\')[-1]
  7731. # # ## Object creation # ##
  7732. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7733. if ret_val == 'fail':
  7734. if from_tcl:
  7735. filename = self.defaults['global_tcl_path'] + '/' + name
  7736. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7737. if ret_val == 'fail':
  7738. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7739. return 'fail'
  7740. # Register recent file
  7741. self.file_opened.emit("gerber", filename)
  7742. # GUI feedback
  7743. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7744. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7745. """
  7746. Opens an Excellon file, parses it and creates a new object for
  7747. it in the program. Thread-safe.
  7748. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7749. :param filename: Excellon file filename
  7750. :type filename: str
  7751. :param plot: boolean, to plot or not the resulting object
  7752. :param from_tcl: True if run from Tcl Shell
  7753. :return: None
  7754. """
  7755. App.log.debug("open_excellon()")
  7756. # How the object should be initialized
  7757. def obj_init(excellon_obj, app_obj):
  7758. try:
  7759. ret = excellon_obj.parse_file(filename=filename)
  7760. if ret == "fail":
  7761. log.debug("Excellon parsing failed.")
  7762. self.inform.emit('[ERROR_NOTCL] %s' %
  7763. _("This is not Excellon file."))
  7764. return "fail"
  7765. except IOError:
  7766. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7767. (_("Cannot open file"), filename))
  7768. log.debug("Could not open Excellon object.")
  7769. return "fail"
  7770. except Exception:
  7771. msg = '[ERROR_NOTCL] %s' % \
  7772. _("An internal error has occurred. See shell.\n")
  7773. msg += traceback.format_exc()
  7774. app_obj.inform.emit(msg)
  7775. return "fail"
  7776. ret = excellon_obj.create_geometry()
  7777. if ret == 'fail':
  7778. log.debug("Could not create geometry for Excellon object.")
  7779. return "fail"
  7780. for tool in excellon_obj.tools:
  7781. if excellon_obj.tools[tool]['solid_geometry']:
  7782. return
  7783. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7784. return "fail"
  7785. with self.proc_container.new(_("Opening Excellon.")):
  7786. # Object name
  7787. name = outname or filename.split('/')[-1].split('\\')[-1]
  7788. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7789. if ret_val == 'fail':
  7790. if from_tcl:
  7791. filename = self.defaults['global_tcl_path'] + '/' + name
  7792. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7793. if ret_val == 'fail':
  7794. self.inform.emit('[ERROR_NOTCL] %s' %
  7795. _('Open Excellon file failed. Probable not an Excellon file.'))
  7796. return
  7797. # Register recent file
  7798. self.file_opened.emit("excellon", filename)
  7799. # GUI feedback
  7800. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7801. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7802. """
  7803. Opens a G-gcode file, parses it and creates a new object for
  7804. it in the program. Thread-safe.
  7805. :param filename: G-code file filename
  7806. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7807. :param force_parsing:
  7808. :param plot: If True plot the object on canvas
  7809. :param from_tcl: True if run from Tcl Shell
  7810. :return: None
  7811. """
  7812. App.log.debug("open_gcode()")
  7813. # How the object should be initialized
  7814. def obj_init(job_obj, app_obj_):
  7815. """
  7816. :param job_obj: the resulting object
  7817. :type app_obj_: App
  7818. """
  7819. assert isinstance(app_obj_, App), \
  7820. "Initializer expected App, got %s" % type(app_obj_)
  7821. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7822. try:
  7823. f = open(filename)
  7824. gcode = f.read()
  7825. f.close()
  7826. except IOError:
  7827. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7828. return "fail"
  7829. job_obj.gcode = gcode
  7830. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7831. if gcode_ret == "fail":
  7832. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7833. return "fail"
  7834. job_obj.create_geometry()
  7835. with self.proc_container.new(_("Opening G-Code.")):
  7836. # Object name
  7837. name = outname or filename.split('/')[-1].split('\\')[-1]
  7838. # New object creation and file processing
  7839. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7840. if ret_val == 'fail':
  7841. if from_tcl:
  7842. filename = self.defaults['global_tcl_path'] + '/' + name
  7843. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7844. if ret_val == 'fail':
  7845. self.inform.emit('[ERROR_NOTCL] %s' %
  7846. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7847. "Try to load it from File menu.\n "
  7848. "Attempting to create a FlatCAM CNCJob Object from "
  7849. "G-Code file failed during processing"))
  7850. return "fail"
  7851. # Register recent file
  7852. self.file_opened.emit("cncjob", filename)
  7853. # GUI feedback
  7854. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7855. def open_hpgl2(self, filename, outname=None):
  7856. """
  7857. Opens a HPGL2 file, parses it and creates a new object for
  7858. it in the program. Thread-safe.
  7859. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7860. :param filename: HPGL2 file filename
  7861. :return: None
  7862. """
  7863. filename = filename
  7864. # How the object should be initialized
  7865. def obj_init(geo_obj, app_obj):
  7866. assert isinstance(geo_obj, GeometryObject), \
  7867. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7868. # Opening the file happens here
  7869. obj = HPGL2(self)
  7870. try:
  7871. HPGL2.parse_file(obj, filename)
  7872. except IOError:
  7873. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7874. return "fail"
  7875. except ParseError as err:
  7876. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7877. app_obj.log.error(str(err))
  7878. return "fail"
  7879. except Exception as e:
  7880. log.debug("App.open_hpgl2() --> %s" % str(e))
  7881. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7882. msg += traceback.format_exc()
  7883. app_obj.inform.emit(msg)
  7884. return "fail"
  7885. geo_obj.multigeo = True
  7886. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7887. geo_obj.tools = deepcopy(obj.tools)
  7888. geo_obj.source_file = deepcopy(obj.source_file)
  7889. del obj
  7890. if not geo_obj.solid_geometry:
  7891. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7892. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7893. return "fail"
  7894. App.log.debug("open_hpgl2()")
  7895. with self.proc_container.new(_("Opening HPGL2")) as proc:
  7896. # Object name
  7897. name = outname or filename.split('/')[-1].split('\\')[-1]
  7898. # # ## Object creation # ##
  7899. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7900. if ret == 'fail':
  7901. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7902. return 'fail'
  7903. # Register recent file
  7904. self.file_opened.emit("geometry", filename)
  7905. # GUI feedback
  7906. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7907. def open_script(self, filename, outname=None, silent=False):
  7908. """
  7909. Opens a Script file, parses it and creates a new object for
  7910. it in the program. Thread-safe.
  7911. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7912. :param filename: Script file filename
  7913. :return: None
  7914. """
  7915. App.log.debug("open_script()")
  7916. with self.proc_container.new(_("Opening TCL Script...")):
  7917. try:
  7918. with open(filename, "r") as opened_script:
  7919. script_content = opened_script.readlines()
  7920. script_content = ''.join(script_content)
  7921. if silent is False:
  7922. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7923. except Exception as e:
  7924. log.debug("App.open_script() -> %s" % str(e))
  7925. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  7926. return
  7927. # Object name
  7928. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7929. # New object creation and file processing
  7930. self.on_filenewscript(name=script_name, text=script_content)
  7931. # Register recent file
  7932. self.file_opened.emit("script", filename)
  7933. # GUI feedback
  7934. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7935. def open_config_file(self, filename, run_from_arg=None):
  7936. """
  7937. Loads a config file from the specified file.
  7938. :param filename: Name of the file from which to load.
  7939. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7940. :return: None
  7941. """
  7942. App.log.debug("Opening config file: " + filename)
  7943. if run_from_arg:
  7944. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7945. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7946. _("Opening FlatCAM Config file.")),
  7947. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7948. color=QtGui.QColor("gray"))
  7949. # # add the tab if it was closed
  7950. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7951. # # first clear previous text in text editor (if any)
  7952. # self.ui.text_editor_tab.code_editor.clear()
  7953. #
  7954. # # Switch plot_area to CNCJob tab
  7955. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7956. # close the Code editor if already open
  7957. if self.toggle_codeeditor:
  7958. self.on_toggle_code_editor()
  7959. self.on_toggle_code_editor()
  7960. try:
  7961. if filename:
  7962. f = QtCore.QFile(filename)
  7963. if f.open(QtCore.QIODevice.ReadOnly):
  7964. stream = QtCore.QTextStream(f)
  7965. code_edited = stream.readAll()
  7966. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7967. f.close()
  7968. except IOError:
  7969. App.log.error("Failed to open config file: %s" % filename)
  7970. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7971. (_("Failed to open config file"), filename))
  7972. return
  7973. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7974. """
  7975. Loads a project from the specified file.
  7976. 1) Loads and parses file
  7977. 2) Registers the file as recently opened.
  7978. 3) Calls on_file_new()
  7979. 4) Updates options
  7980. 5) Calls new_object() with the object's from_dict() as init method.
  7981. 6) Calls plot_all() if plot=True
  7982. :param filename: Name of the file from which to load.
  7983. :param run_from_arg: True if run for arguments
  7984. :param plot: If True plot all objects in the project
  7985. :param cli: Run from command line
  7986. :param from_tcl: True if run from Tcl Sehll
  7987. :return: None
  7988. """
  7989. App.log.debug("Opening project: " + filename)
  7990. # block autosaving while a project is loaded
  7991. self.block_autosave = True
  7992. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7993. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7994. if cli is None:
  7995. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7996. if run_from_arg:
  7997. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7998. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7999. _("Opening FlatCAM Project file.")),
  8000. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8001. color=QtGui.QColor("gray"))
  8002. # Open and parse an uncompressed Project file
  8003. try:
  8004. f = open(filename, 'r')
  8005. except IOError:
  8006. if from_tcl:
  8007. name = filename.split('/')[-1].split('\\')[-1]
  8008. filename = self.defaults['global_tcl_path'] + '/' + name
  8009. try:
  8010. f = open(filename, 'r')
  8011. except IOError:
  8012. log.error("Failed to open project file: %s" % filename)
  8013. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8014. return
  8015. else:
  8016. log.error("Failed to open project file: %s" % filename)
  8017. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8018. return
  8019. try:
  8020. d = json.load(f, object_hook=dict2obj)
  8021. except Exception as e:
  8022. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8023. (filename, str(e)))
  8024. f.close()
  8025. # Open and parse a compressed Project file
  8026. try:
  8027. with lzma.open(filename) as f:
  8028. file_content = f.read().decode('utf-8')
  8029. d = json.loads(file_content, object_hook=dict2obj)
  8030. except Exception as e:
  8031. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8032. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8033. (_("Failed to open project file"), filename))
  8034. return
  8035. # Clear the current project
  8036. # # NOT THREAD SAFE # ##
  8037. if run_from_arg is True:
  8038. pass
  8039. elif cli is True:
  8040. self.delete_selection_shape()
  8041. else:
  8042. self.on_file_new()
  8043. # Project options
  8044. self.options.update(d['options'])
  8045. self.project_filename = filename
  8046. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8047. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8048. if cli is None:
  8049. self.set_screen_units(self.options["units"])
  8050. # Re create objects
  8051. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8052. for obj in d['objs']:
  8053. try:
  8054. def obj_init(obj_inst, app_inst):
  8055. obj_inst.from_dict(obj)
  8056. App.log.debug("Recreating from opened project an %s object: %s" %
  8057. (obj['kind'].capitalize(), obj['options']['name']))
  8058. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8059. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8060. if cli is None:
  8061. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8062. obj['kind'].upper(),
  8063. obj['options']['name']
  8064. )
  8065. )
  8066. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8067. except Exception as e:
  8068. print('App.open_project() --> ' + str(e))
  8069. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8070. self.should_we_save = False
  8071. self.file_opened.emit("project", filename)
  8072. # restore autosaving after a project was loaded
  8073. self.block_autosave = False
  8074. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8075. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8076. if cli is None:
  8077. self.set_ui_title(name=self.project_filename)
  8078. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8079. def plot_all(self, fit_view=True, use_thread=True):
  8080. """
  8081. Re-generates all plots from all objects.
  8082. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8083. :param use_thread: if True will use threading for plotting the objects
  8084. :return: None
  8085. """
  8086. self.log.debug("Plot_all()")
  8087. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8088. for plot_obj in self.collection.get_list():
  8089. def worker_task(obj):
  8090. with self.proc_container.new("Plotting"):
  8091. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8092. if fit_view is True:
  8093. self.object_plotted.emit(obj)
  8094. if use_thread is True:
  8095. # Send to worker
  8096. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8097. else:
  8098. worker_task(plot_obj)
  8099. def register_folder(self, filename):
  8100. """
  8101. Register the last folder used by the app to open something
  8102. :param filename: the last folder is extracted from the filename
  8103. :return: None
  8104. """
  8105. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8106. def register_save_folder(self, filename):
  8107. """
  8108. Register the last folder used by the app to save something
  8109. :param filename: the last folder is extracted from the filename
  8110. :return: None
  8111. """
  8112. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8113. # def set_progress_bar(self, percentage, text=""):
  8114. # """
  8115. # Set a progress bar to a value (percentage)
  8116. #
  8117. # :param percentage: Value set to the progressbar
  8118. # :param text: Not used
  8119. # :return: None
  8120. # """
  8121. # self.ui.progress_bar.setValue(int(percentage))
  8122. def setup_recent_items(self):
  8123. """
  8124. Setup a dictionary with the recent files accessed, organized by type
  8125. :return:
  8126. """
  8127. icons = {
  8128. "gerber": self.resource_location + "/flatcam_icon16.png",
  8129. "excellon": self.resource_location + "/drill16.png",
  8130. 'geometry': self.resource_location + "/geometry16.png",
  8131. "cncjob": self.resource_location + "/cnc16.png",
  8132. "script": self.resource_location + "/script_new24.png",
  8133. "document": self.resource_location + "/notes16_1.png",
  8134. "project": self.resource_location + "/project16.png",
  8135. "svg": self.resource_location + "/geometry16.png",
  8136. "dxf": self.resource_location + "/dxf16.png",
  8137. "pdf": self.resource_location + "/pdf32.png",
  8138. "image": self.resource_location + "/image16.png"
  8139. }
  8140. try:
  8141. image_opener = self.image_tool.import_image
  8142. except AttributeError:
  8143. image_opener = None
  8144. openers = {
  8145. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8146. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8147. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8148. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8149. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8150. "document": None,
  8151. 'project': self.open_project,
  8152. 'svg': self.import_svg,
  8153. 'dxf': self.import_dxf,
  8154. 'image': image_opener,
  8155. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8156. }
  8157. # Open recent file for files
  8158. try:
  8159. f = open(self.data_path + '/recent.json')
  8160. except IOError:
  8161. App.log.error("Failed to load recent item list.")
  8162. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8163. return
  8164. try:
  8165. self.recent = json.load(f)
  8166. except json.errors.JSONDecodeError:
  8167. App.log.error("Failed to parse recent item list.")
  8168. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8169. f.close()
  8170. return
  8171. f.close()
  8172. # Open recent file for projects
  8173. try:
  8174. fp = open(self.data_path + '/recent_projects.json')
  8175. except IOError:
  8176. App.log.error("Failed to load recent project item list.")
  8177. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8178. return
  8179. try:
  8180. self.recent_projects = json.load(fp)
  8181. except json.errors.JSONDecodeError:
  8182. App.log.error("Failed to parse recent project item list.")
  8183. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8184. fp.close()
  8185. return
  8186. fp.close()
  8187. # Closure needed to create callbacks in a loop.
  8188. # Otherwise late binding occurs.
  8189. def make_callback(func, fname):
  8190. def opener():
  8191. func(fname)
  8192. return opener
  8193. def reset_recent_files():
  8194. # Reset menu
  8195. self.ui.recent.clear()
  8196. self.recent = []
  8197. try:
  8198. ff = open(self.data_path + '/recent.json', 'w')
  8199. except IOError:
  8200. App.log.error("Failed to open recent items file for writing.")
  8201. return
  8202. json.dump(self.recent, ff)
  8203. def reset_recent_projects():
  8204. # Reset menu
  8205. self.ui.recent_projects.clear()
  8206. self.recent_projects = []
  8207. try:
  8208. frp = open(self.data_path + '/recent_projects.json', 'w')
  8209. except IOError:
  8210. App.log.error("Failed to open recent projects items file for writing.")
  8211. return
  8212. json.dump(self.recent, frp)
  8213. # Reset menu
  8214. self.ui.recent.clear()
  8215. self.ui.recent_projects.clear()
  8216. # Create menu items for projects
  8217. for recent in self.recent_projects:
  8218. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8219. if recent['kind'] == 'project':
  8220. try:
  8221. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8222. # Attach callback
  8223. o = make_callback(openers[recent["kind"]], recent['filename'])
  8224. action.triggered.connect(o)
  8225. self.ui.recent_projects.addAction(action)
  8226. except KeyError:
  8227. App.log.error("Unsupported file type: %s" % recent["kind"])
  8228. # Last action in Recent Files menu is one that Clear the content
  8229. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8230. (_("Clear Recent projects")), self)
  8231. clear_action_proj.triggered.connect(reset_recent_projects)
  8232. self.ui.recent_projects.addSeparator()
  8233. self.ui.recent_projects.addAction(clear_action_proj)
  8234. # Create menu items for files
  8235. for recent in self.recent:
  8236. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8237. if recent['kind'] != 'project':
  8238. try:
  8239. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8240. # Attach callback
  8241. o = make_callback(openers[recent["kind"]], recent['filename'])
  8242. action.triggered.connect(o)
  8243. self.ui.recent.addAction(action)
  8244. except KeyError:
  8245. App.log.error("Unsupported file type: %s" % recent["kind"])
  8246. # Last action in Recent Files menu is one that Clear the content
  8247. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8248. (_("Clear Recent files")), self)
  8249. clear_action.triggered.connect(reset_recent_files)
  8250. self.ui.recent.addSeparator()
  8251. self.ui.recent.addAction(clear_action)
  8252. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8253. # self.ui.menufilerecent.set_submenu(recent_menu)
  8254. # recent_menu.show_all()
  8255. # self.ui.recent.show()
  8256. self.log.debug("Recent items list has been populated.")
  8257. def setup_component_editor(self):
  8258. """
  8259. Default text for the Selected tab when is not taken by the Object UI.
  8260. :return:
  8261. """
  8262. # label = QtWidgets.QLabel("Choose an item from Project")
  8263. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8264. sel_title = QtWidgets.QTextEdit(
  8265. _('<b>Shortcut Key List</b>'))
  8266. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8267. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8268. f_settings = QSettings("Open Source", "FlatCAM")
  8269. if f_settings.contains("notebook_font_size"):
  8270. fsize = f_settings.value('notebook_font_size', type=int)
  8271. else:
  8272. fsize = 12
  8273. tsize = fsize + int(fsize / 2)
  8274. # selected_text = (_('''
  8275. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8276. # </p>
  8277. #
  8278. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8279. # The normal flow when working in FlatCAM is the following:</span></p>
  8280. #
  8281. # <ol>
  8282. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8283. # file into
  8284. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8285. # even dragging and dropping the files on the GUI.<br />
  8286. # <br />
  8287. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8288. # drop of the
  8289. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8290. # &nbsp;</li>
  8291. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8292. # and then
  8293. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8294. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8295. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8296. # <br />
  8297. # If the selection of the object is done on the canvas by single click instead, and the
  8298. # <strong>SELECTED TAB</strong>
  8299. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8300. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8301. # it even if it was out of focus.<br />
  8302. # <br />
  8303. # You can change the parameters in this screen and the flow direction is like this:<br />
  8304. # <br />
  8305. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8306. # <strong> Geometry Object
  8307. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8308. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8309. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8310. # </ol>
  8311. #
  8312. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8313. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8314. # <strong>F3</strong>.</span></p>
  8315. #
  8316. # ''').format(fsize=fsize, tsize=tsize))
  8317. selected_text = '''
  8318. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8319. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8320. {s1}</span></p>
  8321. <ol>
  8322. <li><span style="font-size:{fsize}px">{s2}<br />
  8323. <br />
  8324. {s3}</span><br />
  8325. &nbsp;</li>
  8326. <li><span style="font-size:{fsize}px">{s4}<br />
  8327. &nbsp;</li>
  8328. <br />
  8329. <li><span style="font-size:{fsize}px">{s5}<br />
  8330. &nbsp;</li>
  8331. <br />
  8332. <li><span style="font-size:{fsize}px">{s6}<br />
  8333. <br />
  8334. {s7}</span></li>
  8335. </ol>
  8336. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8337. '''.format(
  8338. title=_("Selected Tab - Choose an Item from Project Tab"),
  8339. subtitle=_("Details"),
  8340. s1=_("The normal flow when working in FlatCAM is the following:"),
  8341. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8342. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8343. "files on the GUI."),
  8344. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8345. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8346. "actions offered within the app."),
  8347. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8348. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8349. "SELECTED TAB will be updated with the object properties according to its kind: "
  8350. "Gerber, Excellon, Geometry or CNCJob object."),
  8351. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8352. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8353. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8354. "the SELECTED TAB and populate it even if it was out of focus."),
  8355. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8356. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8357. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8358. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8359. "(again, done in SELECTED TAB) --> Save GCode."),
  8360. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8361. "or through its own key shortcut: <b>F3</b>."),
  8362. tsize=tsize,
  8363. fsize=fsize
  8364. )
  8365. sel_title.setText(selected_text)
  8366. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8367. self.ui.selected_scroll_area.setWidget(sel_title)
  8368. def setup_obj_classes(self):
  8369. """
  8370. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8371. class.
  8372. :return: None
  8373. """
  8374. FlatCAMObj.app = self
  8375. ObjectCollection.app = self
  8376. Gerber.app = self
  8377. Excellon.app = self
  8378. Geometry.app = self
  8379. CNCjob.app = self
  8380. FCProcess.app = self
  8381. FCProcessContainer.app = self
  8382. OptionsGroupUI.app = self
  8383. def version_check(self):
  8384. """
  8385. Checks for the latest version of the program. Alerts the
  8386. user if theirs is outdated. This method is meant to be run
  8387. in a separate thread.
  8388. :return: None
  8389. """
  8390. self.log.debug("version_check()")
  8391. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8392. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8393. App.version_url,
  8394. str(self.defaults['global_serial']),
  8395. str(self.version),
  8396. str(self.os),
  8397. urllib.parse.urlencode(self.defaults["global_stats"])
  8398. )
  8399. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8400. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8401. # urllib.parse.urlencode(self.defaults["global_stats"])
  8402. else:
  8403. # no_stats dict; just so it won't break things on website
  8404. no_ststs_dict = {}
  8405. no_ststs_dict["global_ststs"] = {}
  8406. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) +\
  8407. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8408. App.log.debug("Checking for updates @ %s" % full_url)
  8409. # ## Get the data
  8410. try:
  8411. f = urllib.request.urlopen(full_url)
  8412. except Exception:
  8413. # App.log.warning("Failed checking for latest version. Could not connect.")
  8414. self.log.warning("Failed checking for latest version. Could not connect.")
  8415. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8416. return
  8417. try:
  8418. data = json.load(f)
  8419. except Exception as e:
  8420. App.log.error("Could not parse information about latest version.")
  8421. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8422. App.log.debug("json.load(): %s" % str(e))
  8423. f.close()
  8424. return
  8425. f.close()
  8426. # ## Latest version?
  8427. if self.version >= data["version"]:
  8428. App.log.debug("FlatCAM is up to date!")
  8429. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8430. return
  8431. App.log.debug("Newer version available.")
  8432. self.message.emit(
  8433. _("Newer Version Available"),
  8434. '%s<br><br>><b>%s</b><br>%s' % (
  8435. _("There is a newer version of FlatCAM available for download:"),
  8436. str(data["name"]),
  8437. str(data["message"])
  8438. ),
  8439. _("info")
  8440. )
  8441. def on_plotcanvas_setup(self, container=None):
  8442. """
  8443. This is doing the setup for the plot area (canvas).
  8444. :param container: QT Widget where to install the canvas
  8445. :return: None
  8446. """
  8447. if container:
  8448. plot_container = container
  8449. else:
  8450. plot_container = self.ui.right_layout
  8451. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8452. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8453. self.is_legacy = True
  8454. self.defaults["global_graphic_engine"] = "2D"
  8455. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8456. else:
  8457. try:
  8458. self.plotcanvas = PlotCanvas(plot_container, self)
  8459. except Exception as er:
  8460. msg_txt = traceback.format_exc()
  8461. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8462. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8463. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8464. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8465. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8466. msg += msg_txt
  8467. self.inform.emit(msg)
  8468. return 'fail'
  8469. # So it can receive key presses
  8470. self.plotcanvas.native.setFocus()
  8471. if self.is_legacy is False:
  8472. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8473. # Set the mouse button for panning
  8474. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8475. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8476. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8477. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8478. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8479. # Keys over plot enabled
  8480. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8481. if self.defaults['global_cursor_type'] == 'small':
  8482. self.app_cursor = self.plotcanvas.new_cursor()
  8483. else:
  8484. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8485. if self.ui.grid_snap_btn.isChecked():
  8486. self.app_cursor.enabled = True
  8487. else:
  8488. self.app_cursor.enabled = False
  8489. if self.is_legacy is False:
  8490. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8491. else:
  8492. # will use the default Matplotlib axes
  8493. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8494. def on_zoom_fit(self, event):
  8495. """
  8496. Callback for zoom-fit request. This can be either from the corresponding
  8497. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8498. with axes limits from the geometry bounds of all objects.
  8499. :param event: Ignored.
  8500. :return: None
  8501. """
  8502. if self.is_legacy is False:
  8503. self.plotcanvas.fit_view()
  8504. else:
  8505. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8506. width = xmax - xmin
  8507. height = ymax - ymin
  8508. xmin -= 0.05 * width
  8509. xmax += 0.05 * width
  8510. ymin -= 0.05 * height
  8511. ymax += 0.05 * height
  8512. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8513. def on_zoom_in(self):
  8514. """
  8515. Callback for zoom-in request.
  8516. :return:
  8517. """
  8518. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8519. def on_zoom_out(self):
  8520. """
  8521. Callback for zoom-out request.
  8522. :return:
  8523. """
  8524. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8525. def disable_all_plots(self):
  8526. self.defaults.report_usage("disable_all_plots()")
  8527. self.disable_plots(self.collection.get_list())
  8528. self.inform.emit('[success] %s' %
  8529. _("All plots disabled."))
  8530. def disable_other_plots(self):
  8531. self.defaults.report_usage("disable_other_plots()")
  8532. self.disable_plots(self.collection.get_non_selected())
  8533. self.inform.emit('[success] %s' %
  8534. _("All non selected plots disabled."))
  8535. def enable_all_plots(self):
  8536. self.defaults.report_usage("enable_all_plots()")
  8537. self.enable_plots(self.collection.get_list())
  8538. self.inform.emit('[success] %s' %
  8539. _("All plots enabled."))
  8540. def on_enable_sel_plots(self):
  8541. log.debug("App.on_enable_sel_plot()")
  8542. object_list = self.collection.get_selected()
  8543. self.enable_plots(objects=object_list)
  8544. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8545. def on_disable_sel_plots(self):
  8546. log.debug("App.on_disable_sel_plot()")
  8547. # self.inform.emit(_("Disabling plots ..."))
  8548. object_list = self.collection.get_selected()
  8549. self.disable_plots(objects=object_list)
  8550. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8551. def enable_plots(self, objects):
  8552. """
  8553. Enable plots
  8554. :param objects: list of Objects to be enabled
  8555. :return:
  8556. """
  8557. log.debug("Enabling plots ...")
  8558. # self.inform.emit(_("Working ..."))
  8559. for obj in objects:
  8560. if obj.options['plot'] is False:
  8561. obj.options.set_change_callback(lambda x: None)
  8562. obj.options['plot'] = True
  8563. try:
  8564. # only the Gerber obj has on_plot_cb_click() method
  8565. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8566. # disable this cb while disconnected,
  8567. # in case the operation takes time the user is not allowed to change it
  8568. obj.ui.plot_cb.setDisabled(True)
  8569. except AttributeError:
  8570. pass
  8571. obj.set_form_item("plot")
  8572. try:
  8573. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8574. obj.ui.plot_cb.setDisabled(False)
  8575. except AttributeError:
  8576. pass
  8577. obj.options.set_change_callback(obj.on_options_change)
  8578. def worker_task(objs):
  8579. with self.proc_container.new(_("Enabling plots ...")):
  8580. for plot_obj in objs:
  8581. # obj.options['plot'] = True
  8582. if isinstance(plot_obj, CNCJobObject):
  8583. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8584. else:
  8585. plot_obj.plot(visible=True)
  8586. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8587. # self.plots_updated.emit()
  8588. def disable_plots(self, objects):
  8589. """
  8590. Disables plots
  8591. :param objects: list of Objects to be disabled
  8592. :return:
  8593. """
  8594. # if no objects selected then do nothing
  8595. if not self.collection.get_selected():
  8596. return
  8597. log.debug("Disabling plots ...")
  8598. # self.inform.emit(_("Working ..."))
  8599. for obj in objects:
  8600. if obj.options['plot'] is True:
  8601. obj.options.set_change_callback(lambda x: None)
  8602. obj.options['plot'] = False
  8603. try:
  8604. # only the Gerber obj has on_plot_cb_click() method
  8605. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8606. obj.ui.plot_cb.setDisabled(True)
  8607. except AttributeError:
  8608. pass
  8609. obj.set_form_item("plot")
  8610. try:
  8611. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8612. obj.ui.plot_cb.setDisabled(False)
  8613. except AttributeError:
  8614. pass
  8615. obj.options.set_change_callback(obj.on_options_change)
  8616. try:
  8617. self.delete_selection_shape()
  8618. except Exception as e:
  8619. log.debug("App.disable_plots() --> %s" % str(e))
  8620. # self.plots_updated.emit()
  8621. def worker_task(objs):
  8622. with self.proc_container.new(_("Disabling plots ...")):
  8623. for plot_obj in objs:
  8624. # obj.options['plot'] = True
  8625. if isinstance(plot_obj, CNCJobObject):
  8626. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8627. else:
  8628. plot_obj.plot(visible=False)
  8629. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8630. def toggle_plots(self, objects):
  8631. """
  8632. Toggle plots visibility
  8633. :param objects: list of Objects for which to be toggled the visibility
  8634. :return: None
  8635. """
  8636. # if no objects selected then do nothing
  8637. if not self.collection.get_selected():
  8638. return
  8639. log.debug("Toggling plots ...")
  8640. self.inform.emit(_("Working ..."))
  8641. for obj in objects:
  8642. if obj.options['plot'] is False:
  8643. obj.options['plot'] = True
  8644. else:
  8645. obj.options['plot'] = False
  8646. self.plots_updated.emit()
  8647. def clear_plots(self):
  8648. """
  8649. Clear the plots
  8650. :return: None
  8651. """
  8652. objects = self.collection.get_list()
  8653. for obj in objects:
  8654. obj.clear(obj == objects[-1])
  8655. # Clear pool to free memory
  8656. self.clear_pool()
  8657. def on_set_color_action_triggered(self):
  8658. """
  8659. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8660. :return:
  8661. """
  8662. new_color = self.defaults['gerber_plot_fill']
  8663. clicked_action = self.sender()
  8664. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8665. act_name = clicked_action.text()
  8666. sel_obj_list = self.collection.get_selected()
  8667. if not sel_obj_list:
  8668. return
  8669. # a default value, I just chose this one
  8670. alpha_level = 'BF'
  8671. for sel_obj in sel_obj_list:
  8672. if sel_obj.kind == 'excellon':
  8673. alpha_level = str(hex(
  8674. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8675. elif sel_obj.kind == 'gerber':
  8676. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8677. elif sel_obj.kind == 'geometry':
  8678. alpha_level = 'FF'
  8679. else:
  8680. log.debug(
  8681. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8682. continue
  8683. sel_obj.alpha_level = alpha_level
  8684. if act_name == _('Red'):
  8685. new_color = '#FF0000' + alpha_level
  8686. if act_name == _('Blue'):
  8687. new_color = '#0000FF' + alpha_level
  8688. if act_name == _('Yellow'):
  8689. new_color = '#FFDF00' + alpha_level
  8690. if act_name == _('Green'):
  8691. new_color = '#00FF00' + alpha_level
  8692. if act_name == _('Purple'):
  8693. new_color = '#FF00FF' + alpha_level
  8694. if act_name == _('Brown'):
  8695. new_color = '#A52A2A' + alpha_level
  8696. if act_name == _('White'):
  8697. new_color = '#FFFFFF' + alpha_level
  8698. if act_name == _('Black'):
  8699. new_color = '#000000' + alpha_level
  8700. if act_name == _('Custom'):
  8701. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8702. c_dialog = QtWidgets.QColorDialog()
  8703. plot_fill_color = c_dialog.getColor(initial=new_color)
  8704. if plot_fill_color.isValid() is False:
  8705. return
  8706. new_color = str(plot_fill_color.name()) + alpha_level
  8707. if act_name == _("Default"):
  8708. for sel_obj in sel_obj_list:
  8709. if sel_obj.kind == 'excellon':
  8710. new_color = self.defaults['excellon_plot_fill']
  8711. new_line_color = self.defaults['excellon_plot_line']
  8712. elif sel_obj.kind == 'gerber':
  8713. new_color = self.defaults['gerber_plot_fill']
  8714. new_line_color = self.defaults['gerber_plot_line']
  8715. elif sel_obj.kind == 'geometry':
  8716. new_color = self.defaults['geometry_plot_line']
  8717. new_line_color = self.defaults['geometry_plot_line']
  8718. else:
  8719. log.debug(
  8720. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8721. continue
  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. return
  8728. if act_name == _("Opacity"):
  8729. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8730. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8731. if ok_button:
  8732. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8733. for sel_obj in sel_obj_list:
  8734. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8735. sel_obj.shapes.redraw(
  8736. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8737. )
  8738. return
  8739. new_line_color = color_variant(new_color[:7], 0.7)
  8740. if act_name == _("White"):
  8741. new_line_color = color_variant("#dedede", 0.7)
  8742. for sel_obj in sel_obj_list:
  8743. sel_obj.fill_color = new_color
  8744. sel_obj.outline_color = new_line_color
  8745. sel_obj.shapes.redraw(
  8746. update_colors=(new_color, new_line_color)
  8747. )
  8748. def on_grid_snap_triggered(self, state):
  8749. """
  8750. :param state: A parameter with the state of the grid, boolean
  8751. :return:
  8752. """
  8753. if state:
  8754. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  8755. else:
  8756. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  8757. self.ui.snap_infobar_label.clicked_state = state
  8758. def on_grid_icon_snap_clicked(self):
  8759. """
  8760. Slot called by clicking a GUI element, in this case a FCLabel
  8761. :return:
  8762. """
  8763. if isinstance(self.sender(), FCLabel):
  8764. self.ui.grid_snap_btn.trigger()
  8765. def generate_cnc_job(self, objects):
  8766. """
  8767. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8768. :param objects: Selected objects in the Project Tab
  8769. :return:
  8770. """
  8771. self.defaults.report_usage("generate_cnc_job()")
  8772. # for obj in objects:
  8773. # obj.generatecncjob()
  8774. for obj in objects:
  8775. obj.on_generatecnc_button_click()
  8776. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8777. """
  8778. Saves the current project to the specified file.
  8779. :param filename: Name of the file in which to save.
  8780. :type filename: str
  8781. :param quit_action: if the project saving will be followed by an app quit; boolean
  8782. :param silent: if True will not display status messages
  8783. :param from_tcl True is run from Tcl Shell
  8784. :return: None
  8785. """
  8786. self.log.debug("save_project()")
  8787. self.save_in_progress = True
  8788. with self.proc_container.new(_("Saving FlatCAM Project")):
  8789. # Capture the latest changes
  8790. # Current object
  8791. try:
  8792. current_object = self.collection.get_active()
  8793. if current_object:
  8794. current_object.read_form()
  8795. except Exception as e:
  8796. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8797. pass
  8798. # Serialize the whole project
  8799. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8800. "options": self.options,
  8801. "version": self.version}
  8802. if self.defaults["global_save_compressed"] is True:
  8803. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8804. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8805. # # Write
  8806. f.write(g)
  8807. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8808. else:
  8809. # Open file
  8810. try:
  8811. f = open(filename, 'w')
  8812. except IOError:
  8813. App.log.error("Failed to open file for saving: %s", filename)
  8814. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8815. return
  8816. # Write
  8817. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8818. f.close()
  8819. # verification of the saved project
  8820. # Open and parse
  8821. try:
  8822. saved_f = open(filename, 'r')
  8823. except IOError:
  8824. if silent is False:
  8825. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8826. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8827. return
  8828. try:
  8829. saved_d = json.load(saved_f, object_hook=dict2obj)
  8830. except Exception:
  8831. if silent is False:
  8832. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8833. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8834. f.close()
  8835. return
  8836. saved_f.close()
  8837. if silent is False:
  8838. if 'version' in saved_d:
  8839. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8840. else:
  8841. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8842. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8843. tb_settings = QSettings("Open Source", "FlatCAM")
  8844. lock_state = self.ui.lock_action.isChecked()
  8845. tb_settings.setValue('toolbar_lock', lock_state)
  8846. # This will write the setting to the platform specific storage.
  8847. del tb_settings
  8848. # if quit:
  8849. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8850. # t.start()
  8851. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8852. def start_delayed_quit(self, delay, filename, should_quit=None):
  8853. """
  8854. :param delay: period of checking if project file size is more than zero; in seconds
  8855. :param filename: the name of the project file to be checked periodically for size more than zero
  8856. :param should_quit: if the task finished will be followed by an app quit; boolean
  8857. :return:
  8858. """
  8859. to_quit = should_quit
  8860. self.save_timer = QtCore.QTimer()
  8861. self.save_timer.setInterval(delay)
  8862. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8863. self.save_timer.start()
  8864. def check_project_file_size(self, filename, should_quit=None):
  8865. """
  8866. :param filename: the name of the project file to be checked periodically for size more than zero
  8867. :param should_quit: will quit the app if True; boolean
  8868. :return:
  8869. """
  8870. try:
  8871. if os.stat(filename).st_size > 0:
  8872. self.save_in_progress = False
  8873. self.save_timer.stop()
  8874. if should_quit:
  8875. self.app_quit.emit()
  8876. except Exception:
  8877. traceback.print_exc()
  8878. def save_project_auto(self):
  8879. """
  8880. Called periodically to save the project.
  8881. 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
  8882. # progress.
  8883. :return:
  8884. """
  8885. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8886. self.on_file_saveproject()
  8887. def save_project_auto_update(self):
  8888. """
  8889. Update the auto save time interval value.
  8890. :return:
  8891. """
  8892. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8893. try:
  8894. if self.autosave_timer.isActive():
  8895. self.autosave_timer.stop()
  8896. except Exception:
  8897. pass
  8898. if self.defaults['global_autosave'] is True:
  8899. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8900. self.autosave_timer.start()
  8901. def on_options_app2project(self):
  8902. """
  8903. Callback for Options->Transfer Options->App=>Project. Copies options
  8904. from application defaults to project defaults.
  8905. :return: None
  8906. """
  8907. self.defaults.report_usage("on_options_app2project")
  8908. self.preferencesUiManager.defaults_read_form()
  8909. self.options.update(self.defaults)
  8910. def toggle_shell(self):
  8911. """
  8912. Toggle shell: if is visible close it, if it is closed then open it
  8913. :return: None
  8914. """
  8915. self.defaults.report_usage("toggle_shell()")
  8916. if self.ui.shell_dock.isVisible():
  8917. self.ui.shell_dock.hide()
  8918. self.plotcanvas.native.setFocus()
  8919. else:
  8920. self.ui.shell_dock.show()
  8921. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8922. # self.shell._edit.setFocus()
  8923. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8924. # HACK - simulate a mouse click - alternative
  8925. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8926. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8927. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8928. # no_km)
  8929. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8930. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8931. # no_km)
  8932. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8933. def on_toggle_shell_from_settings(self, state):
  8934. """
  8935. Toggle shell: if is visible close it, if it is closed then open it
  8936. :return: None
  8937. """
  8938. self.defaults.report_usage("on_toggle_shell_from_settings()")
  8939. if state is True:
  8940. if not self.ui.shell_dock.isVisible():
  8941. self.ui.shell_dock.show()
  8942. else:
  8943. if self.ui.shell_dock.isVisible():
  8944. self.ui.shell_dock.hide()
  8945. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8946. """
  8947. Shows a message on the FlatCAM Shell
  8948. :param msg: Message to display.
  8949. :param show: Opens the shell.
  8950. :param error: Shows the message as an error.
  8951. :param warning: Shows the message as an warning.
  8952. :param success: Shows the message as an success.
  8953. :param selected: Indicate that something was selected on canvas
  8954. :return: None
  8955. """
  8956. if show:
  8957. self.ui.shell_dock.show()
  8958. try:
  8959. if error:
  8960. self.shell.append_error(msg + "\n")
  8961. elif warning:
  8962. self.shell.append_warning(msg + "\n")
  8963. elif success:
  8964. self.shell.append_success(msg + "\n")
  8965. elif selected:
  8966. self.shell.append_selected(msg + "\n")
  8967. else:
  8968. self.shell.append_output(msg + "\n")
  8969. except AttributeError:
  8970. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8971. class ArgsThread(QtCore.QObject):
  8972. open_signal = pyqtSignal(list)
  8973. start = pyqtSignal()
  8974. if sys.platform == 'win32':
  8975. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8976. else:
  8977. address = ('/tmp/testipc', 'AF_UNIX')
  8978. def __init__(self):
  8979. super(ArgsThread, self).__init__()
  8980. self.listener = None
  8981. self.thread_exit = False
  8982. self.start.connect(self.run)
  8983. def my_loop(self, address):
  8984. try:
  8985. self.listener = Listener(*address)
  8986. while self.thread_exit is False:
  8987. conn = self.listener.accept()
  8988. self.serve(conn)
  8989. except socket.error:
  8990. try:
  8991. conn = Client(*address)
  8992. conn.send(sys.argv)
  8993. conn.send('close')
  8994. # close the current instance only if there are args
  8995. if len(sys.argv) > 1:
  8996. try:
  8997. self.listener.close()
  8998. except Exception:
  8999. pass
  9000. sys.exit()
  9001. except ConnectionRefusedError:
  9002. if sys.platform == 'win32':
  9003. pass
  9004. else:
  9005. os.system('rm /tmp/testipc')
  9006. self.listener = Listener(*address)
  9007. while True:
  9008. conn = self.listener.accept()
  9009. self.serve(conn)
  9010. def serve(self, conn):
  9011. while self.thread_exit is False:
  9012. msg = conn.recv()
  9013. if msg == 'close':
  9014. break
  9015. self.open_signal.emit(msg)
  9016. conn.close()
  9017. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9018. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9019. @pyqtSlot()
  9020. def run(self):
  9021. self.my_loop(self.address)
  9022. # end of file