FlatCAMApp.py 488 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 PyQt5.QtCore import pyqtSlot, Qt
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Diverse
  37. from FlatCAMCommon import LoudDict, color_variant
  38. from FlatCAMBookmark import BookmarkManager
  39. from FlatCAMDB import ToolsDB2
  40. from vispy.gloo.util import _screenshot
  41. from vispy.io import write_png
  42. # FlatCAM Objects
  43. from defaults import FlatCAMDefaults
  44. from flatcamGUI.preferences.OptionsGroupUI import OptionsGroupUI
  45. from flatcamGUI.preferences.PreferencesUIManager import PreferencesUIManager
  46. from flatcamObjects.ObjectCollection import *
  47. from flatcamObjects.FlatCAMObj import FlatCAMObj
  48. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  49. from flatcamObjects.FlatCAMDocument import DocumentObject
  50. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  51. from flatcamObjects.FlatCAMGeometry import GeometryObject
  52. from flatcamObjects.FlatCAMGerber import GerberObject
  53. from flatcamObjects.FlatCAMScript import ScriptObject
  54. # FlatCAM Parsing files
  55. from flatcamParsers.ParseExcellon import Excellon
  56. from flatcamParsers.ParseGerber import Gerber
  57. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  58. # FlatCAM GUI
  59. from flatcamGUI.PlotCanvas import *
  60. from flatcamGUI.PlotCanvasLegacy import *
  61. from flatcamGUI.FlatCAMGUI import *
  62. from flatcamGUI.GUIElements import FCFileSaveDialog
  63. # FlatCAM Pre-processors
  64. from FlatCAMPostProc import load_preprocessors
  65. # FlatCAM Editors
  66. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  67. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  68. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  69. from flatcamEditors.FlatCAMTextEditor import TextEditor
  70. from flatcamParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from FlatCAMProcess import *
  73. from FlatCAMWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from flatcamTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import FlatCAMTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = 8.993
  138. version_date = "2020/08/01"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by:
  169. # * App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. plots_updated = QtCore.pyqtSignal()
  188. # Emitted by new_object() and passes the new object as argument, plot flag.
  189. # on_object_created() adds the object to the collection, plots on appropriate flag
  190. # and emits new_object_available.
  191. object_created = QtCore.pyqtSignal(object, bool, bool)
  192. # Emitted when a object has been changed (like scaled, mirrored)
  193. object_changed = QtCore.pyqtSignal(object)
  194. # Emitted after object has been plotted.
  195. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  196. object_plotted = QtCore.pyqtSignal(object)
  197. # Emitted when a new object has been added or deleted from/to the collection
  198. object_status_changed = QtCore.pyqtSignal(object, str, str)
  199. message = QtCore.pyqtSignal(str, str, str)
  200. # Emmited when shell command is finished(one command only)
  201. shell_command_finished = QtCore.pyqtSignal(object)
  202. # Emitted when multiprocess pool has been recreated
  203. pool_recreated = QtCore.pyqtSignal(object)
  204. # Emitted when an unhandled exception happens
  205. # in the worker task.
  206. thread_exception = QtCore.pyqtSignal(object)
  207. # used to signal that there are arguments for the app
  208. args_at_startup = QtCore.pyqtSignal(list)
  209. # a reusable signal to replot a list of objects
  210. # should be disconnected after use so it can be reused
  211. replot_signal = pyqtSignal(list)
  212. # signal emitted when jumping
  213. jump_signal = pyqtSignal(tuple)
  214. # signal emitted when jumping
  215. locate_signal = pyqtSignal(tuple, str)
  216. # close app signal
  217. close_app_signal = pyqtSignal()
  218. # will perform the cleanup operation after a Graceful Exit
  219. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  220. # graphic residues behind
  221. cleanup = pyqtSignal()
  222. def __init__(self, user_defaults=True):
  223. """
  224. Starts the application.
  225. :return: app
  226. :rtype: App
  227. """
  228. App.log.info("FlatCAM Starting...")
  229. self.main_thread = QtWidgets.QApplication.instance().thread()
  230. # ############################################################################################################
  231. # ################# Setup the listening thread for another instance launching with args ######################
  232. # ############################################################################################################
  233. if sys.platform == 'win32' or sys.platform == 'linux':
  234. # make sure the thread is stored by using a self. otherwise it's garbage collected
  235. self.th = QtCore.QThread()
  236. self.th.start(priority=QtCore.QThread.LowestPriority)
  237. self.new_launch = ArgsThread()
  238. self.new_launch.open_signal[list].connect(self.on_startup_args)
  239. self.new_launch.moveToThread(self.th)
  240. self.new_launch.start.emit()
  241. # ############################################################################################################
  242. # # ######################################## OS-specific #####################################################
  243. # ############################################################################################################
  244. portable = False
  245. # Folder for user settings.
  246. if sys.platform == 'win32':
  247. if platform.architecture()[0] == '32bit':
  248. App.log.debug("Win32!")
  249. else:
  250. App.log.debug("Win64!")
  251. # #######################################################################################################
  252. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  253. # #######################################################################################################
  254. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  255. try:
  256. with open(config_file, 'r'):
  257. pass
  258. except FileNotFoundError:
  259. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  260. try:
  261. with open(config_file, 'r') as f:
  262. try:
  263. for line in f:
  264. param = str(line).replace('\n', '').rpartition('=')
  265. if param[0] == 'portable':
  266. try:
  267. portable = eval(param[2])
  268. except NameError:
  269. portable = False
  270. if param[0] == 'headless':
  271. if param[2].lower() == 'true':
  272. self.cmd_line_headless = 1
  273. else:
  274. self.cmd_line_headless = None
  275. except Exception as e:
  276. log.debug('App.__init__() -->%s' % str(e))
  277. return
  278. except FileNotFoundError as e:
  279. log.debug(str(e))
  280. pass
  281. if portable is False:
  282. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  283. else:
  284. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  285. self.os = 'windows'
  286. else: # Linux/Unix/MacOS
  287. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  288. self.os = 'unix'
  289. # ############################################################################################################
  290. # ################################# Setup folders and files ##################################################
  291. # ############################################################################################################
  292. if not os.path.exists(self.data_path):
  293. os.makedirs(self.data_path)
  294. App.log.debug('Created data folder: ' + self.data_path)
  295. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  296. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  297. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  298. if not os.path.exists(self.preprocessorpaths):
  299. os.makedirs(self.preprocessorpaths)
  300. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  301. # create geo_tools_db.FlatDB file if there is none
  302. try:
  303. f = open(self.data_path + '/geo_tools_db.FlatDB')
  304. f.close()
  305. except IOError:
  306. App.log.debug('Creating empty geo_tool_db.FlatDB')
  307. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  308. json.dump({}, f)
  309. f.close()
  310. # create current_defaults.FlatConfig file if there is none
  311. try:
  312. f = open(self.data_path + '/current_defaults.FlatConfig')
  313. f.close()
  314. except IOError:
  315. App.log.debug('Creating empty current_defaults.FlatConfig')
  316. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  317. json.dump({}, f)
  318. f.close()
  319. # Write factory_defaults.FlatConfig file to disk
  320. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  321. # create a recent files json file if there is none
  322. try:
  323. f = open(self.data_path + '/recent.json')
  324. f.close()
  325. except IOError:
  326. App.log.debug('Creating empty recent.json')
  327. f = open(self.data_path + '/recent.json', 'w')
  328. json.dump([], f)
  329. f.close()
  330. # create a recent projects json file if there is none
  331. try:
  332. fp = open(self.data_path + '/recent_projects.json')
  333. fp.close()
  334. except IOError:
  335. App.log.debug('Creating empty recent_projects.json')
  336. fp = open(self.data_path + '/recent_projects.json', 'w')
  337. json.dump([], fp)
  338. fp.close()
  339. # Application directory. CHDIR to it. Otherwise, trying to load
  340. # GUI icons will fail as their path is relative.
  341. # This will fail under cx_freeze ...
  342. self.app_home = os.path.dirname(os.path.realpath(__file__))
  343. App.log.debug("Application path is " + self.app_home)
  344. App.log.debug("Started in " + os.getcwd())
  345. # cx_freeze workaround
  346. if os.path.isfile(self.app_home):
  347. self.app_home = os.path.dirname(self.app_home)
  348. os.chdir(self.app_home)
  349. # ############################################################################################################
  350. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  351. # ############################################################################################################
  352. self.defaults = FlatCAMDefaults()
  353. self.defaults["root_folder_path"] = self.app_home
  354. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  355. if user_defaults:
  356. self.defaults.load(filename=current_defaults_path)
  357. if self.defaults['units'] == 'MM':
  358. self.decimals = int(self.defaults['decimals_metric'])
  359. else:
  360. self.decimals = int(self.defaults['decimals_inch'])
  361. if self.defaults["global_gray_icons"] is False:
  362. self.resource_location = 'assets/resources'
  363. else:
  364. self.resource_location = 'assets/resources/dark_resources'
  365. self.current_units = self.defaults['units']
  366. # ###########################################################################################################
  367. # #################################### SETUP OBJECT CLASSES #################################################
  368. # ###########################################################################################################
  369. self.setup_obj_classes()
  370. # ###########################################################################################################
  371. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  372. # ###########################################################################################################
  373. self.pool = Pool()
  374. # ###########################################################################################################
  375. # ###################################### Setting the Splash Screen ##########################################
  376. # ###########################################################################################################
  377. splash_settings = QSettings("Open Source", "FlatCAM")
  378. if splash_settings.contains("splash_screen"):
  379. show_splash = splash_settings.value("splash_screen")
  380. else:
  381. splash_settings.setValue('splash_screen', 1)
  382. # This will write the setting to the platform specific storage.
  383. del splash_settings
  384. show_splash = 1
  385. if show_splash and self.cmd_line_headless != 1:
  386. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  387. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  388. # self.splash.setMask(splash_pix.mask())
  389. # move splashscreen to the current monitor
  390. desktop = QtWidgets.QApplication.desktop()
  391. screen = desktop.screenNumber(QtGui.QCursor.pos())
  392. current_screen_center = desktop.availableGeometry(screen).center()
  393. self.splash.move(current_screen_center - self.splash.rect().center())
  394. self.splash.show()
  395. self.splash.showMessage(_("FlatCAM is initializing ..."),
  396. alignment=Qt.AlignBottom | Qt.AlignLeft,
  397. color=QtGui.QColor("gray"))
  398. else:
  399. show_splash = 0
  400. # ###########################################################################################################
  401. # ######################################### Initialize GUI ##################################################
  402. # ###########################################################################################################
  403. # FlatCAM colors used in plotting
  404. self.FC_light_green = '#BBF268BF'
  405. self.FC_dark_green = '#006E20BF'
  406. self.FC_light_blue = '#a5a5ffbf'
  407. self.FC_dark_blue = '#0000ffbf'
  408. QtCore.QObject.__init__(self)
  409. self.ui = FlatCAMGUI(self)
  410. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  411. if theme_settings.contains("theme"):
  412. theme = theme_settings.value('theme', type=str)
  413. else:
  414. theme = 'white'
  415. if self.defaults["global_cursor_color_enabled"]:
  416. self.cursor_color_3D = self.defaults["global_cursor_color"]
  417. else:
  418. if theme == 'white':
  419. self.cursor_color_3D = 'black'
  420. else:
  421. self.cursor_color_3D = 'gray'
  422. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  423. self.ui.final_save.connect(self.final_save)
  424. # restore the toolbar view
  425. self.restore_toolbar_view()
  426. # restore the GUI geometry
  427. self.restore_main_win_geom()
  428. # set FlatCAM units in the Status bar
  429. self.set_screen_units(self.defaults['units'])
  430. # ###########################################################################################################
  431. # ########################################### AUTOSAVE SETUP ################################################
  432. # ###########################################################################################################
  433. self.block_autosave = False
  434. self.autosave_timer = QtCore.QTimer(self)
  435. self.save_project_auto_update()
  436. self.autosave_timer.timeout.connect(self.save_project_auto)
  437. # ###########################################################################################################
  438. # #################################### LOAD PREPROCESSORS ###################################################
  439. # ###########################################################################################################
  440. # ----------------------------------------- WARNING --------------------------------------------------------
  441. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  442. # That's because the number of preprocessors can vary and here the comboboxes are populated
  443. # -----------------------------------------------------------------------------------------------------------
  444. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  445. # the preprocessor file
  446. self.preprocessors = load_preprocessors(self)
  447. # make sure that always the 'default' preprocessor is the first item in the dictionary
  448. if 'default' in self.preprocessors.keys():
  449. new_ppp_dict = {}
  450. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  451. default_pp = self.preprocessors.pop('default')
  452. new_ppp_dict['default'] = default_pp
  453. # then add the rest of the keys
  454. for name, val_class in self.preprocessors.items():
  455. new_ppp_dict[name] = val_class
  456. # and now put back the ordered dict with 'default' key first
  457. self.preprocessors = new_ppp_dict
  458. for name in list(self.preprocessors.keys()):
  459. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  460. if name.partition('_')[0] == 'Paste':
  461. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  462. continue
  463. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  464. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  465. if name == 'hpgl':
  466. continue
  467. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  468. # ###########################################################################################################
  469. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  470. # ###########################################################################################################
  471. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  472. inform=self.inform)
  473. self.preferencesUiManager.defaults_write_form()
  474. # When the self.defaults dictionary changes will update the Preferences GUI forms
  475. self.defaults.set_change_callback(self.on_defaults_dict_change)
  476. # ###########################################################################################################
  477. # ##################################### FIRST RUN SECTION ###################################################
  478. # ################################ It's done only once after install #####################################
  479. # ###########################################################################################################
  480. if self.defaults["first_run"] is True:
  481. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  482. initial_lay = 'minimal'
  483. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  484. # Set the combobox in Preferences to the current layout
  485. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  486. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  487. # after the first run, this object should be False
  488. self.defaults["first_run"] = False
  489. self.preferencesUiManager.save_defaults(silent=True)
  490. # ###########################################################################################################
  491. # ############################################ Data #########################################################
  492. # ###########################################################################################################
  493. self.recent = []
  494. self.recent_projects = []
  495. self.clipboard = QtWidgets.QApplication.clipboard()
  496. self.project_filename = None
  497. self.toggle_units_ignore = False
  498. # ###########################################################################################################
  499. # ########################################## LOAD LANGUAGES ################################################
  500. # ###########################################################################################################
  501. self.languages = fcTranslate.load_languages()
  502. for name in sorted(self.languages.values()):
  503. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  504. # ###########################################################################################################
  505. # ####################################### APPLY APP LANGUAGE ################################################
  506. # ###########################################################################################################
  507. ret_val = fcTranslate.apply_language('strings')
  508. if ret_val == "no language":
  509. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  510. log.debug("Could not find the Language files. The App strings are missing.")
  511. else:
  512. # make the current language the current selection on the language combobox
  513. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  514. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  515. # ###########################################################################################################
  516. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  517. # ###########################################################################################################
  518. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  519. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  520. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  521. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  522. self.defaults.propagate_defaults()
  523. # ###########################################################################################################
  524. # ######################################## UPDATE THE OPTIONS ###############################################
  525. # ###########################################################################################################
  526. self.options = LoudDict()
  527. # -----------------------------------------------------------------------------------------------------------
  528. # Update the self.options from the self.defaults
  529. # The self.defaults holds the application defaults while the self.options holds the object defaults
  530. # -----------------------------------------------------------------------------------------------------------
  531. # Copy app defaults to project options
  532. for def_key, def_val in self.defaults.items():
  533. self.options[def_key] = deepcopy(def_val)
  534. self.preferencesUiManager.show_preferences_gui()
  535. # ### End of Data ####
  536. # ###########################################################################################################
  537. # #################################### SETUP OBJECT COLLECTION ##############################################
  538. # ###########################################################################################################
  539. self.collection = ObjectCollection(self)
  540. self.ui.project_tab_layout.addWidget(self.collection.view)
  541. # ### Adjust tabs width ## ##
  542. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  543. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  544. self.collection.view.setMinimumWidth(290)
  545. self.log.debug("Finished creating Object Collection.")
  546. # ###########################################################################################################
  547. # ######################################## SETUP Plot Area ##################################################
  548. # ###########################################################################################################
  549. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  550. if self.defaults["global_graphic_engine"] == '3D':
  551. self.is_legacy = False
  552. else:
  553. self.is_legacy = True
  554. # Event signals disconnect id holders
  555. self.mp = None
  556. self.mm = None
  557. self.mr = None
  558. self.mdc = None
  559. self.mp_zc = None
  560. self.kp = None
  561. # Matplotlib axis
  562. self.axes = None
  563. if show_splash:
  564. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  565. "Canvas initialization started."),
  566. alignment=Qt.AlignBottom | Qt.AlignLeft,
  567. color=QtGui.QColor("gray"))
  568. start_plot_time = time.time() # debug
  569. self.plotcanvas = None
  570. self.app_cursor = None
  571. self.hover_shapes = None
  572. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  573. # setup the PlotCanvas
  574. self.on_plotcanvas_setup()
  575. end_plot_time = time.time()
  576. self.used_time = end_plot_time - start_plot_time
  577. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  578. if show_splash:
  579. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  580. "Canvas initialization started.\n"
  581. "Canvas initialization finished in"), '%.2f' % self.used_time),
  582. alignment=Qt.AlignBottom | Qt.AlignLeft,
  583. color=QtGui.QColor("gray"))
  584. self.ui.splitter.setStretchFactor(1, 2)
  585. # ###########################################################################################################
  586. # ############################################### SYS TRAY ##################################################
  587. # ###########################################################################################################
  588. if self.defaults["global_systray_icon"]:
  589. self.parent_w = QtWidgets.QWidget()
  590. if self.cmd_line_headless == 1:
  591. self.trayIcon = FlatCAMSystemTray(app=self,
  592. icon=QtGui.QIcon(self.resource_location +
  593. '/flatcam_icon32_green.png'),
  594. headless=True,
  595. parent=self.parent_w)
  596. else:
  597. self.trayIcon = FlatCAMSystemTray(app=self,
  598. icon=QtGui.QIcon(self.resource_location +
  599. '/flatcam_icon32_green.png'),
  600. parent=self.parent_w)
  601. # ###########################################################################################################
  602. # ############################################### Worker SETUP ##############################################
  603. # ###########################################################################################################
  604. if self.defaults["global_worker_number"]:
  605. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  606. else:
  607. self.workers = WorkerStack(workers_number=2)
  608. self.worker_task.connect(self.workers.add_task)
  609. self.log.debug("Finished creating Workers crew.")
  610. # ###########################################################################################################
  611. # ############################################# Activity Monitor ###########################################
  612. # ###########################################################################################################
  613. self.activity_view = FlatCAMActivityView(app=self)
  614. self.ui.infobar.addWidget(self.activity_view)
  615. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  616. # ###########################################################################################################
  617. # ############################################# Signal handling #############################################
  618. # ###########################################################################################################
  619. # ########################################## Custom signals ################################################
  620. # signal for displaying messages in status bar
  621. self.inform.connect(self.info)
  622. # signal to be called when the app is quiting
  623. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  624. self.message.connect(self.message_dialog)
  625. # self.progress.connect(self.set_progress_bar)
  626. # signals that are emitted when object state changes
  627. self.object_created.connect(self.on_object_created)
  628. self.object_changed.connect(self.on_object_changed)
  629. self.object_plotted.connect(self.on_object_plotted)
  630. self.plots_updated.connect(self.on_plots_updated)
  631. # signals emitted when file state change
  632. self.file_opened.connect(self.register_recent)
  633. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  634. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  635. # ########################################## Standard signals ###############################################
  636. # ### Menu
  637. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  638. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  639. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  640. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  641. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  642. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  643. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  644. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  645. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  646. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  647. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  648. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  649. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  650. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  651. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  652. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  653. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  654. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  655. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  656. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  657. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  658. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  659. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  660. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  661. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  662. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  663. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  664. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  665. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  666. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  667. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  668. self.ui.menufile_exit.triggered.connect(self.final_save)
  669. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  670. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  671. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  672. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  673. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  674. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  675. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  676. self.ui.menueditdelete.triggered.connect(self.on_delete)
  677. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  678. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  679. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  680. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  681. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  682. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  683. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  684. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  685. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  686. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  687. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  688. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  689. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  690. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  691. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  692. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  693. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  694. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  695. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  696. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  697. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  698. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  699. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  700. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  701. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  702. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  703. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  704. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  705. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  706. self.ui.menuview_replot.triggered.connect(self.plot_all)
  707. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  708. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  709. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  710. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  711. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  712. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  713. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  714. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  715. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  716. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  717. self.ui.menuhelp_about.triggered.connect(self.on_about)
  718. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  719. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  720. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  721. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  722. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  723. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  724. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  725. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  726. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  727. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  728. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  729. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  730. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  731. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  732. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  733. # ToolBar signals
  734. self.connect_toolbar_signals()
  735. # Notebook and Plot Tab Area signals
  736. # make the right click on the notebook tab and plot tab area tab raise a menu
  737. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  738. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  739. self.on_tab_setup_context_menu()
  740. # activate initial state
  741. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  742. # Context Menu
  743. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  744. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  745. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  746. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  747. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  748. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  749. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  750. self.ui.clearplot.triggered.connect(self.clear_plots)
  751. self.ui.replot.triggered.connect(self.plot_all)
  752. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  753. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  754. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  755. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  756. self.ui.popmenu_move.triggered.connect(self.obj_move)
  757. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  758. # Project Context Menu -> Color Setting
  759. for act in self.ui.menuprojectcolor.actions():
  760. act.triggered.connect(self.on_set_color_action_triggered)
  761. # ###########################################################################################################
  762. # #################################### GUI PREFERENCES SIGNALS ##############################################
  763. # ###########################################################################################################
  764. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  765. lambda: self.on_toggle_units(no_pref=False))
  766. # ##################################### Workspace Setting Signals ###########################################
  767. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  768. self.on_workspace_modified)
  769. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  770. self.on_workspace_modified
  771. )
  772. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  773. # ###########################################################################################################
  774. # ######################################## GUI SETTINGS SIGNALS #############################################
  775. # ###########################################################################################################
  776. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  777. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  778. # ######################################## Tools related signals ############################################
  779. # Film Tool
  780. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  781. self.on_film_color_entry)
  782. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  783. self.on_film_color_button)
  784. # QRCode Tool
  785. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  786. self.on_qrcode_fill_color_entry)
  787. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  788. self.on_qrcode_fill_color_button)
  789. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  790. self.on_qrcode_back_color_entry)
  791. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  792. self.on_qrcode_back_color_button)
  793. # portability changed signal
  794. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  795. # Object list
  796. self.collection.view.activated.connect(self.on_row_activated)
  797. self.collection.item_selected.connect(self.on_row_selected)
  798. self.object_status_changed.connect(self.on_collection_updated)
  799. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  800. # Export Excellon parameters.
  801. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  802. self.on_update_exc_export
  803. )
  804. # call it once to make sure it is updated at startup
  805. self.on_update_exc_export(state=self.defaults["excellon_update"])
  806. # when there are arguments at application startup this get launched
  807. self.args_at_startup[list].connect(self.on_startup_args)
  808. # ###########################################################################################################
  809. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  810. # ###########################################################################################################
  811. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  812. lambda: self.restore_extensions(ext_type='excellon'))
  813. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  814. lambda: self.restore_extensions(ext_type='gcode'))
  815. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  816. lambda: self.restore_extensions(ext_type='gerber'))
  817. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  818. lambda: self.delete_all_extensions(ext_type='excellon'))
  819. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  820. lambda: self.delete_all_extensions(ext_type='gcode'))
  821. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  822. lambda: self.delete_all_extensions(ext_type='gerber'))
  823. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  824. lambda: self.add_extension(ext_type='excellon'))
  825. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  826. lambda: self.add_extension(ext_type='gcode'))
  827. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  828. lambda: self.add_extension(ext_type='gerber'))
  829. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  830. lambda: self.del_extension(ext_type='excellon'))
  831. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  832. lambda: self.del_extension(ext_type='gcode'))
  833. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  834. lambda: self.del_extension(ext_type='gerber'))
  835. # connect the 'Apply' buttons from the Preferences/File Associations
  836. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  837. lambda: self.on_register_files(obj_type='excellon'))
  838. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  839. lambda: self.on_register_files(obj_type='gcode'))
  840. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  841. lambda: self.on_register_files(obj_type='gerber'))
  842. # ###########################################################################################################
  843. # ########################################### KEYWORDS SIGNALS ##############################################
  844. # ###########################################################################################################
  845. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  846. lambda: self.restore_extensions(ext_type='keyword'))
  847. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  848. lambda: self.delete_all_extensions(ext_type='keyword'))
  849. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  850. lambda: self.add_extension(ext_type='keyword'))
  851. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  852. lambda: self.del_extension(ext_type='keyword'))
  853. # connect the abort_all_tasks related slots to the related signals
  854. self.proc_container.idle_flag.connect(self.app_is_idle)
  855. # signal emitted when a tab is closed in the Plot Area
  856. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  857. # signal to close the application
  858. self.close_app_signal.connect(self.kill_app)
  859. # ################################# FINISHED CONNECTING SIGNALS #############################################
  860. # ###########################################################################################################
  861. # ###########################################################################################################
  862. # ###########################################################################################################
  863. self.log.debug("Finished connecting Signals.")
  864. # ###########################################################################################################
  865. # ########################################## Other setups ###################################################
  866. # ###########################################################################################################
  867. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  868. # depending on from where those tools are called different actions can be done
  869. self.call_source = 'app'
  870. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  871. self.tool_tab_locked = False
  872. # decide if to show or hide the Notebook side of the screen at startup
  873. if self.defaults["global_project_at_startup"] is True:
  874. self.ui.splitter.setSizes([1, 1])
  875. else:
  876. self.ui.splitter.setSizes([0, 1])
  877. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  878. self.setup_component_editor()
  879. # ###########################################################################################################
  880. # ####################################### Auto-complete KEYWORDS ############################################
  881. # ###########################################################################################################
  882. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  883. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  884. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  885. 'export_exc',
  886. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  887. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  888. 'interiors', 'isolate', 'join_excellon',
  889. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  890. 'mirror', 'ncc',
  891. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  892. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  893. 'options', 'origin',
  894. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  895. 'save', 'save_project',
  896. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  897. 'skew', 'subtract_poly', 'subtract_rectangle',
  898. 'version', 'write_gcode'
  899. ]
  900. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  901. 'Paste_1',
  902. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  903. 'Toolchange_manual', 'True', 'Users',
  904. 'all', 'auto', 'axis',
  905. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  906. 'contour', 'default',
  907. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  908. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  909. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  910. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  911. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  912. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  913. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  914. 'spacing_columns',
  915. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  916. 'toolchange_xy', 'toolchangez', 'travelz',
  917. 'tooldia', 'use_threads', 'value',
  918. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  919. ]
  920. self.tcl_keywords = [
  921. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  922. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  923. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  924. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  925. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  926. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  927. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  928. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  929. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  930. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  931. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  932. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  933. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  934. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  935. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  936. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  937. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  938. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  939. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  940. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  941. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  942. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  943. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  944. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  945. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  946. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  947. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  948. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  949. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  950. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  951. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  952. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  953. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  954. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  955. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  956. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  957. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  958. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  959. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  960. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  961. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  962. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  963. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  964. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  965. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  966. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  967. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  968. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  969. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  970. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  971. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  972. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  973. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  974. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  975. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  976. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  977. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  978. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  979. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  980. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  981. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  982. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  983. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  984. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  985. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  986. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  987. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  988. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  989. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  990. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  991. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  992. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  993. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  994. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  995. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  996. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  997. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  998. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  999. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1000. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1001. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1002. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1003. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1004. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1005. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1006. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1007. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1008. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1009. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1010. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1011. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1012. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1013. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1014. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1015. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1016. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1017. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1018. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1019. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1020. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1021. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1022. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1023. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1024. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1025. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1026. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1027. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1028. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1029. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1030. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1031. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1032. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1033. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1034. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1035. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1036. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1037. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1038. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1039. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1040. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1041. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1042. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1043. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1044. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1045. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1046. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1047. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1048. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1049. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1050. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1051. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1052. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1053. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1054. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1055. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1056. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1057. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1058. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1059. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1060. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1061. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1062. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1063. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1064. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1065. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1066. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1067. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1068. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1069. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1070. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1071. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1072. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1073. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1074. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1075. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1076. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1077. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1078. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1079. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1080. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1081. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1082. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1083. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1084. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1085. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1086. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1087. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1088. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1089. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1090. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1091. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1092. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1093. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1094. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1095. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1096. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1097. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1098. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1099. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1100. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1101. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1102. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1103. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1104. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1105. ]
  1106. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1107. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1108. # ###########################################################################################################
  1109. # ############################################## Shell SETUP ################################################
  1110. # ###########################################################################################################
  1111. self.shell = FCShell(app=self, version=self.version)
  1112. self.ui.shell_dock.setWidget(self.shell)
  1113. self.log.debug("TCL Shell has been initialized.")
  1114. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1115. if self.defaults["global_shell_at_startup"]:
  1116. self.ui.shell_dock.show()
  1117. else:
  1118. self.ui.shell_dock.hide()
  1119. # ###########################################################################################################
  1120. # ########################################## Tools and Plugins ##############################################
  1121. # ###########################################################################################################
  1122. self.dblsidedtool = None
  1123. self.distance_tool = None
  1124. self.distance_min_tool = None
  1125. self.panelize_tool = None
  1126. self.film_tool = None
  1127. self.paste_tool = None
  1128. self.calculator_tool = None
  1129. self.rules_tool = None
  1130. self.sub_tool = None
  1131. self.move_tool = None
  1132. self.cutout_tool = None
  1133. self.ncclear_tool = None
  1134. self.optimal_tool = None
  1135. self.paint_tool = None
  1136. self.transform_tool = None
  1137. self.properties_tool = None
  1138. self.pdf_tool = None
  1139. self.image_tool = None
  1140. self.pcb_wizard_tool = None
  1141. self.cal_exc_tool = None
  1142. self.qrcode_tool = None
  1143. self.copper_thieving_tool = None
  1144. self.fiducial_tool = None
  1145. self.edrills_tool = None
  1146. self.align_objects_tool = None
  1147. self.punch_tool = None
  1148. self.invert_tool = None
  1149. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1150. try:
  1151. self.install_tools()
  1152. except AttributeError as e:
  1153. log.debug("App.__init__() install tools() --> %s" % str(e))
  1154. # ###########################################################################################################
  1155. # ############################################ SETUP RECENT ITEMS ###########################################
  1156. # ###########################################################################################################
  1157. self.setup_recent_items()
  1158. # ###########################################################################################################
  1159. # ######################################### BookMarks Manager ###############################################
  1160. # ###########################################################################################################
  1161. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1162. self.install_bookmarks()
  1163. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1164. # ###########################################################################################################
  1165. # ########################################### Tools Database ################################################
  1166. # ###########################################################################################################
  1167. self.tools_db_tab = None
  1168. # ### System Font Parsing ###
  1169. # self.f_parse = ParseFont(self)
  1170. # self.parse_system_fonts()
  1171. # ###########################################################################################################
  1172. # ######################################### Check for updates ###############################################
  1173. # ###########################################################################################################
  1174. # Separate thread (Not worker)
  1175. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1176. if (self.beta is False or self.beta is None) and \
  1177. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1178. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1179. # self.thr2 = QtCore.QThread()
  1180. self.worker_task.emit({'fcn': self.version_check,
  1181. 'params': []})
  1182. # self.thr2.start(QtCore.QThread.LowPriority)
  1183. # ###########################################################################################################
  1184. # ##################################### Register files with FlatCAM; #######################################
  1185. # ################################### It works only for Windows for now ####################################
  1186. # ###########################################################################################################
  1187. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1188. self.on_register_files()
  1189. # ###########################################################################################################
  1190. # ######################################## Variables for global usage #######################################
  1191. # ###########################################################################################################
  1192. # hold the App units
  1193. self.units = 'MM'
  1194. # coordinates for relative position display
  1195. self.rel_point1 = (0, 0)
  1196. self.rel_point2 = (0, 0)
  1197. # variable to store coordinates
  1198. self.pos = (0, 0)
  1199. self.pos_canvas = (0, 0)
  1200. self.pos_jump = (0, 0)
  1201. # variable to store mouse coordinates
  1202. self.mouse = [0, 0]
  1203. # variable to store the delta positions on cavnas
  1204. self.dx = 0
  1205. self.dy = 0
  1206. # decide if we have a double click or single click
  1207. self.doubleclick = False
  1208. # store here the is_dragging value
  1209. self.event_is_dragging = False
  1210. # variable to store if a command is active (then the var is not None) and which one it is
  1211. self.command_active = None
  1212. # variable to store the status of moving selection action
  1213. # None value means that it's not an selection action
  1214. # True value = a selection from left to right
  1215. # False value = a selection from right to left
  1216. self.selection_type = None
  1217. # List to store the objects that are currently loaded in FlatCAM
  1218. # This list is updated on each object creation or object delete
  1219. self.all_objects_list = []
  1220. self.objects_under_the_click_list = []
  1221. # List to store the objects that are selected
  1222. self.sel_objects_list = []
  1223. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1224. self.key_modifiers = None
  1225. # Variable to hold the status of the axis
  1226. self.toggle_axis = True
  1227. # Variable to hold the status of the grid lines
  1228. self.toggle_grid_lines = True
  1229. # Variable to store the status of the fullscreen event
  1230. self.toggle_fscreen = False
  1231. # Variable to store the status of the code editor
  1232. self.toggle_codeeditor = False
  1233. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1234. self.click_noproject = False
  1235. self.cursor = None
  1236. # Variable to store the GCODE that was edited
  1237. self.gcode_edited = ""
  1238. self.text_editor_tab = None
  1239. # reference for the self.ui.code_editor
  1240. self.reference_code_editor = None
  1241. self.script_code = ''
  1242. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1243. self.tools_db_changed_flag = False
  1244. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1245. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1246. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1247. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1248. 'tsm']
  1249. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1250. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1251. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1252. 'sbp', 'tap', 'xpi']
  1253. self.svg_list = ['svg']
  1254. self.dxf_list = ['dxf']
  1255. self.pdf_list = ['pdf']
  1256. self.prj_list = ['flatprj']
  1257. self.conf_list = ['flatconfig']
  1258. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1259. # flag for polygons not cleared
  1260. self.poly_not_cleared = False
  1261. # VisPy visuals
  1262. self.isHovering = False
  1263. self.notHovering = True
  1264. # Window geometry
  1265. self.x_pos = None
  1266. self.y_pos = None
  1267. self.width = None
  1268. self.height = None
  1269. # when True, the app has to return from any thread
  1270. self.abort_flag = False
  1271. # set the value used in the Windows Title
  1272. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1273. # this holds a widget that is installed in the Plot Area when View Source option is used
  1274. self.source_editor_tab = None
  1275. self.pagesize = {}
  1276. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1277. # VisPy visuals
  1278. if self.is_legacy is False:
  1279. try:
  1280. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1281. except AttributeError:
  1282. self.tool_shapes = None
  1283. else:
  1284. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1285. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1286. # used in the delayed shutdown self.start_delayed_quit() method
  1287. self.save_timer = None
  1288. # ###########################################################################################################
  1289. # ################################## ADDING FlatCAM EDITORS section #########################################
  1290. # ###########################################################################################################
  1291. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1292. # at the first launch of the App , the editors will not be functional.
  1293. try:
  1294. self.geo_editor = FlatCAMGeoEditor(self)
  1295. except AttributeError:
  1296. pass
  1297. try:
  1298. self.exc_editor = FlatCAMExcEditor(self)
  1299. except AttributeError:
  1300. pass
  1301. try:
  1302. self.grb_editor = FlatCAMGrbEditor(self)
  1303. except AttributeError:
  1304. pass
  1305. self.log.debug("Finished adding FlatCAM Editor's.")
  1306. self.set_ui_title(name=_("New Project - Not saved"))
  1307. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1308. current_platform = platform.architecture()[0]
  1309. if current_platform != '64bit':
  1310. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1311. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1312. # ###########################################################################################################
  1313. # ##################################### Finished the CONSTRUCTOR ############################################
  1314. # ###########################################################################################################
  1315. App.log.debug("END of constructor. Releasing control.")
  1316. # ###########################################################################################################
  1317. # ########################################## SHOW GUI #######################################################
  1318. # ###########################################################################################################
  1319. # if the app is not started as headless, show it
  1320. if self.cmd_line_headless != 1:
  1321. if show_splash:
  1322. # finish the splash
  1323. self.splash.finish(self.ui)
  1324. mgui_settings = QSettings("Open Source", "FlatCAM")
  1325. if mgui_settings.contains("maximized_gui"):
  1326. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1327. if maximized_ui is True:
  1328. self.ui.showMaximized()
  1329. else:
  1330. self.ui.show()
  1331. else:
  1332. self.ui.show()
  1333. if self.defaults["global_systray_icon"]:
  1334. self.trayIcon.show()
  1335. else:
  1336. log.warning("******************* RUNNING HEADLESS *******************")
  1337. # ###########################################################################################################
  1338. # ######################################## START-UP ARGUMENTS ###############################################
  1339. # ###########################################################################################################
  1340. # test if the program was started with a script as parameter
  1341. if self.cmd_line_shellvar:
  1342. try:
  1343. cnt = 0
  1344. command_tcl = 0
  1345. for i in self.cmd_line_shellvar.split(','):
  1346. if i is not None:
  1347. # noinspection PyBroadException
  1348. try:
  1349. command_tcl = eval(i)
  1350. except Exception:
  1351. command_tcl = i
  1352. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1353. cnt += 1
  1354. # if there are Windows paths then replace the path separator with a Unix like one
  1355. if sys.platform == 'win32':
  1356. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1357. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1358. except Exception as ext:
  1359. print("ERROR: ", ext)
  1360. sys.exit(2)
  1361. if self.cmd_line_shellfile:
  1362. if self.cmd_line_headless != 1:
  1363. if self.ui.shell_dock.isHidden():
  1364. self.ui.shell_dock.show()
  1365. try:
  1366. with open(self.cmd_line_shellfile, "r") as myfile:
  1367. # if show_splash:
  1368. # self.splash.showMessage('%s: %ssec\n%s' % (
  1369. # _("Canvas initialization started.\n"
  1370. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1371. # _("Executing Tcl Script ...")),
  1372. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1373. # color=QtGui.QColor("gray"))
  1374. cmd_line_shellfile_text = myfile.read()
  1375. if self.cmd_line_headless != 1:
  1376. self.shell.exec_command(cmd_line_shellfile_text)
  1377. else:
  1378. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1379. except Exception as ext:
  1380. print("ERROR: ", ext)
  1381. sys.exit(2)
  1382. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1383. # the path/file_name must be enclosed in quotes if it contain spaces
  1384. if App.args:
  1385. self.args_at_startup.emit(App.args)
  1386. if self.defaults.old_defaults_found is True:
  1387. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1388. "Please reboot the application to update."))
  1389. self.defaults.old_defaults_found = False
  1390. # ######################################### INIT FINISHED #######################################################
  1391. # #################################################################################################################
  1392. # #################################################################################################################
  1393. # #################################################################################################################
  1394. # #################################################################################################################
  1395. # #################################################################################################################
  1396. @staticmethod
  1397. def copy_and_overwrite(from_path, to_path):
  1398. """
  1399. From here:
  1400. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1401. :param from_path: source path
  1402. :param to_path: destination path
  1403. :return: None
  1404. """
  1405. if os.path.exists(to_path):
  1406. shutil.rmtree(to_path)
  1407. try:
  1408. shutil.copytree(from_path, to_path)
  1409. except FileNotFoundError:
  1410. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1411. shutil.copytree(from_new_path, to_path)
  1412. def on_startup_args(self, args, silent=False):
  1413. """
  1414. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1415. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1416. :param args: a list containing the application args at startup
  1417. :return: None
  1418. """
  1419. if args is not None:
  1420. args_to_process = args
  1421. else:
  1422. args_to_process = App.args
  1423. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1424. for argument in args_to_process:
  1425. if '.FlatPrj'.lower() in argument.lower():
  1426. try:
  1427. project_name = str(argument)
  1428. if project_name == "":
  1429. if silent is False:
  1430. self.inform.emit(_("Cancelled."))
  1431. else:
  1432. # self.open_project(project_name)
  1433. run_from_arg = True
  1434. # self.worker_task.emit({'fcn': self.open_project,
  1435. # 'params': [project_name, run_from_arg]})
  1436. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1437. except Exception as e:
  1438. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1439. elif '.FlatConfig'.lower() in argument.lower():
  1440. try:
  1441. file_name = str(argument)
  1442. if file_name == "":
  1443. if silent is False:
  1444. self.inform.emit(_("Open Config file failed."))
  1445. else:
  1446. run_from_arg = True
  1447. # self.worker_task.emit({'fcn': self.open_config_file,
  1448. # 'params': [file_name, run_from_arg]})
  1449. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1450. except Exception as e:
  1451. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1452. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1453. try:
  1454. file_name = str(argument)
  1455. if file_name == "":
  1456. if silent is False:
  1457. self.inform.emit(_("Open Script file failed."))
  1458. else:
  1459. if silent is False:
  1460. self.on_fileopenscript(name=file_name)
  1461. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1462. self.on_filerunscript(name=file_name)
  1463. except Exception as e:
  1464. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1465. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1466. log.debug("App.on_startup_args() --> Quit event.")
  1467. sys.exit()
  1468. elif 'save'.lower() in argument.lower():
  1469. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1470. self.preferencesUiManager.save_defaults()
  1471. else:
  1472. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1473. proc_arg = argument.lower()
  1474. for ext in exc_list:
  1475. proc_ext = ext.replace(' ', '')
  1476. proc_ext = '.%s' % proc_ext
  1477. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1478. file_name = str(argument)
  1479. if file_name == "":
  1480. if silent is False:
  1481. self.inform.emit(_("Open Excellon file failed."))
  1482. else:
  1483. self.on_fileopenexcellon(name=file_name, signal=None)
  1484. return
  1485. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1486. for ext in gco_list:
  1487. proc_ext = ext.replace(' ', '')
  1488. proc_ext = '.%s' % proc_ext
  1489. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1490. file_name = str(argument)
  1491. if file_name == "":
  1492. if silent is False:
  1493. self.inform.emit(_("Open GCode file failed."))
  1494. else:
  1495. self.on_fileopengcode(name=file_name, signal=None)
  1496. return
  1497. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1498. for ext in grb_list:
  1499. proc_ext = ext.replace(' ', '')
  1500. proc_ext = '.%s' % proc_ext
  1501. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1502. file_name = str(argument)
  1503. if file_name == "":
  1504. if silent is False:
  1505. self.inform.emit(_("Open Gerber file failed."))
  1506. else:
  1507. self.on_fileopengerber(name=file_name, signal=None)
  1508. return
  1509. # if it reached here without already returning then the app was registered with a file that it does not
  1510. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1511. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1512. # for arg in args_to_process:
  1513. # if 'FlatCAM.exe' in arg:
  1514. # continue
  1515. # else:
  1516. # sys.exit(2)
  1517. def set_ui_title(self, name):
  1518. """
  1519. Sets the title of the main window.
  1520. :param name: String that store the project path and project name
  1521. :return: None
  1522. """
  1523. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1524. (self.version,
  1525. ('BETA' if self.beta else ''),
  1526. platform.architecture()[0],
  1527. self.engine,
  1528. name)
  1529. )
  1530. def on_app_restart(self):
  1531. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1532. # be left in the SySTray
  1533. try:
  1534. self.trayIcon.hide()
  1535. except Exception:
  1536. pass
  1537. fcTranslate.restart_program(app=self)
  1538. def clear_pool(self):
  1539. """
  1540. Clear the multiprocessing pool and calls garbage collector.
  1541. :return: None
  1542. """
  1543. self.pool.close()
  1544. self.pool = Pool()
  1545. self.pool_recreated.emit(self.pool)
  1546. gc.collect()
  1547. def install_tools(self):
  1548. """
  1549. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1550. Instantiation of the Tools classes.
  1551. The order that the tools are installed is important as they can depend on each other install position.
  1552. :return: None
  1553. """
  1554. self.distance_tool = Distance(self)
  1555. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1556. before=self.ui.menueditorigin,
  1557. separator=False)
  1558. self.distance_min_tool = DistanceMin(self)
  1559. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1560. pos=self.ui.menuedit,
  1561. before=self.ui.menueditorigin,
  1562. separator=True)
  1563. self.dblsidedtool = DblSidedTool(self)
  1564. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1565. self.cal_exc_tool = ToolCalibration(self)
  1566. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1567. before=self.dblsidedtool.menuAction,
  1568. separator=False)
  1569. self.align_objects_tool = AlignObjects(self)
  1570. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1571. self.edrills_tool = ToolExtractDrills(self)
  1572. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1573. self.panelize_tool = Panelize(self)
  1574. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1575. self.film_tool = Film(self)
  1576. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1577. self.paste_tool = SolderPaste(self)
  1578. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1579. self.calculator_tool = ToolCalculator(self)
  1580. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1581. self.sub_tool = ToolSub(self)
  1582. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1583. pos=self.ui.menutool, separator=True)
  1584. self.rules_tool = RulesCheck(self)
  1585. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1586. pos=self.ui.menutool, separator=False)
  1587. self.optimal_tool = ToolOptimal(self)
  1588. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1589. pos=self.ui.menutool, separator=True)
  1590. self.move_tool = ToolMove(self)
  1591. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1592. before=self.ui.menueditorigin, separator=True)
  1593. self.cutout_tool = CutOut(self)
  1594. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1595. before=self.sub_tool.menuAction)
  1596. self.ncclear_tool = NonCopperClear(self)
  1597. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1598. before=self.sub_tool.menuAction, separator=True)
  1599. self.paint_tool = ToolPaint(self)
  1600. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1601. before=self.sub_tool.menuAction, separator=True)
  1602. self.copper_thieving_tool = ToolCopperThieving(self)
  1603. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1604. pos=self.ui.menutool)
  1605. self.fiducial_tool = ToolFiducials(self)
  1606. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1607. pos=self.ui.menutool)
  1608. self.qrcode_tool = QRCode(self)
  1609. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1610. pos=self.ui.menutool)
  1611. self.punch_tool = ToolPunchGerber(self)
  1612. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1613. self.invert_tool = ToolInvertGerber(self)
  1614. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1615. self.transform_tool = ToolTransform(self)
  1616. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1617. pos=self.ui.menuoptions, separator=True)
  1618. self.properties_tool = Properties(self)
  1619. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1620. pos=self.ui.menuoptions)
  1621. self.pdf_tool = ToolPDF(self)
  1622. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1623. pos=self.ui.menufileimport,
  1624. separator=True)
  1625. self.image_tool = ToolImage(self)
  1626. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1627. pos=self.ui.menufileimport,
  1628. separator=True)
  1629. self.pcb_wizard_tool = PcbWizard(self)
  1630. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1631. pos=self.ui.menufileimport)
  1632. self.log.debug("Tools are installed.")
  1633. def remove_tools(self):
  1634. """
  1635. Will remove all the actions in the Tool menu.
  1636. :return: None
  1637. """
  1638. for act in self.ui.menutool.actions():
  1639. self.ui.menutool.removeAction(act)
  1640. def init_tools(self):
  1641. """
  1642. Initialize the Tool tab in the notebook side of the central widget.
  1643. Remove the actions in the Tools menu.
  1644. Instantiate again the FlatCAM tools (plugins).
  1645. All this is required when changing the layout: standard, compact etc.
  1646. :return: None
  1647. """
  1648. log.debug("init_tools()")
  1649. # delete the data currently in the Tools Tab and the Tab itself
  1650. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1651. if widget is not None:
  1652. widget.deleteLater()
  1653. self.ui.notebook.removeTab(2)
  1654. # rebuild the Tools Tab
  1655. self.ui.tool_tab = QtWidgets.QWidget()
  1656. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1657. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1658. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1659. self.ui.tool_scroll_area = VerticalScrollArea()
  1660. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1661. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1662. # first remove all of them
  1663. self.remove_tools()
  1664. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1665. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1666. '&Command Line\tS')
  1667. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1668. # third install all of them
  1669. try:
  1670. self.install_tools()
  1671. except AttributeError:
  1672. pass
  1673. self.log.debug("Tools are initialized.")
  1674. # def parse_system_fonts(self):
  1675. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1676. # 'params': []})
  1677. def connect_toolbar_signals(self):
  1678. """
  1679. Reconnect the signals to the actions in the toolbar.
  1680. This has to be done each time after the FlatCAM tools are removed/installed.
  1681. :return: None
  1682. """
  1683. # Toolbar
  1684. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1685. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1686. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1687. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1688. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1689. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1690. self.ui.replot_btn.triggered.connect(self.plot_all)
  1691. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1692. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1693. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1694. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1695. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1696. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1697. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1698. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1699. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1700. self.ui.delete_btn.triggered.connect(self.on_delete)
  1701. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1702. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1703. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1704. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1705. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1706. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1707. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1708. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1709. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1710. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1711. # Tools Toolbar Signals
  1712. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1713. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1714. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1715. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1716. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1717. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1718. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1719. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1720. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1721. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1722. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1723. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1724. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1725. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1726. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1727. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1728. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1729. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1730. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1731. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1732. def object2editor(self):
  1733. """
  1734. Send the current Geometry or Excellon object (if any) into the it's editor.
  1735. :return: None
  1736. """
  1737. self.defaults.report_usage("object2editor()")
  1738. # disable the objects menu as it may interfere with the Editors
  1739. self.ui.menuobjects.setDisabled(True)
  1740. edited_object = self.collection.get_active()
  1741. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1742. isinstance(edited_object, ExcellonObject):
  1743. pass
  1744. else:
  1745. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1746. return
  1747. if isinstance(edited_object, GeometryObject):
  1748. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1749. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1750. # we set the notebook to hidden
  1751. # self.ui.splitter.setSizes([0, 1])
  1752. if edited_object.multigeo is True:
  1753. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1754. if len(sel_rows) > 1:
  1755. self.inform.emit('[WARNING_NOTCL] %s' %
  1756. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1757. "is not possible.\n"
  1758. "Edit only one geometry at a time."))
  1759. # determine the tool dia of the selected tool
  1760. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1761. # now find the key in the edited_object.tools that has this tooldia
  1762. multi_tool = 1
  1763. for tool in edited_object.tools:
  1764. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1765. multi_tool = tool
  1766. break
  1767. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1768. else:
  1769. self.geo_editor.edit_fcgeometry(edited_object)
  1770. # set call source to the Editor we go into
  1771. self.call_source = 'geo_editor'
  1772. elif isinstance(edited_object, ExcellonObject):
  1773. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1774. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1775. if self.ui.splitter.sizes()[0] == 0:
  1776. self.ui.splitter.setSizes([1, 1])
  1777. self.exc_editor.edit_fcexcellon(edited_object)
  1778. # set call source to the Editor we go into
  1779. self.call_source = 'exc_editor'
  1780. elif isinstance(edited_object, GerberObject):
  1781. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1782. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1783. if self.ui.splitter.sizes()[0] == 0:
  1784. self.ui.splitter.setSizes([1, 1])
  1785. self.grb_editor.edit_fcgerber(edited_object)
  1786. # set call source to the Editor we go into
  1787. self.call_source = 'grb_editor'
  1788. # reset the following variables so the UI is built again after edit
  1789. edited_object.ui_build = False
  1790. edited_object.build_aperture_storage = False
  1791. # make sure that we can't select another object while in Editor Mode:
  1792. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1793. self.ui.project_frame.setDisabled(True)
  1794. # delete any selection shape that might be active as they are not relevant in Editor
  1795. self.delete_selection_shape()
  1796. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1797. self.ui.plot_tab_area.protectTab(0)
  1798. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1799. self.should_we_save = True
  1800. def editor2object(self, cleanup=None):
  1801. """
  1802. Transfers the Geometry or Excellon from it's editor to the current object.
  1803. :return: None
  1804. """
  1805. self.defaults.report_usage("editor2object()")
  1806. # re-enable the objects menu that was disabled on entry in Editor mode
  1807. self.ui.menuobjects.setDisabled(False)
  1808. # do not update a geometry or excellon object unless it comes out of an editor
  1809. if self.call_source != 'app':
  1810. edited_obj = self.collection.get_active()
  1811. if cleanup is None:
  1812. msgbox = QtWidgets.QMessageBox()
  1813. msgbox.setText(_("Do you want to save the edited object?"))
  1814. msgbox.setWindowTitle(_("Close Editor"))
  1815. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1816. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1817. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1818. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1819. msgbox.setDefaultButton(bt_yes)
  1820. msgbox.exec_()
  1821. response = msgbox.clickedButton()
  1822. if response == bt_yes:
  1823. # clean the Tools Tab
  1824. self.ui.tool_scroll_area.takeWidget()
  1825. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1826. self.ui.notebook.setTabText(2, "Tool")
  1827. if isinstance(edited_obj, GeometryObject):
  1828. obj_type = "Geometry"
  1829. if cleanup is None:
  1830. self.geo_editor.update_fcgeometry(edited_obj)
  1831. # self.geo_editor.update_options(edited_obj)
  1832. self.geo_editor.deactivate()
  1833. # restore GUI to the Selected TAB
  1834. # Remove anything else in the GUI
  1835. self.ui.tool_scroll_area.takeWidget()
  1836. # update the geo object options so it is including the bounding box values
  1837. try:
  1838. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1839. edited_obj.options['xmin'] = xmin
  1840. edited_obj.options['ymin'] = ymin
  1841. edited_obj.options['xmax'] = xmax
  1842. edited_obj.options['ymax'] = ymax
  1843. except AttributeError as e:
  1844. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1845. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1846. edited_obj.build_ui()
  1847. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1848. elif isinstance(edited_obj, GerberObject):
  1849. obj_type = "Gerber"
  1850. if cleanup is None:
  1851. self.grb_editor.update_fcgerber()
  1852. self.grb_editor.update_options(edited_obj)
  1853. self.grb_editor.deactivate_grb_editor()
  1854. # delete the old object (the source object) if it was an empty one
  1855. try:
  1856. if len(edited_obj.solid_geometry) == 0:
  1857. old_name = edited_obj.options['name']
  1858. self.collection.set_active(old_name)
  1859. self.collection.delete_active()
  1860. except TypeError:
  1861. # if the solid_geometry is a single Polygon the len() will not work
  1862. # in any case, falling here means that we have something in the solid_geometry, even if only
  1863. # a single Polygon, therefore we pass this
  1864. pass
  1865. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1866. # restore GUI to the Selected TAB
  1867. # Remove anything else in the GUI
  1868. self.ui.selected_scroll_area.takeWidget()
  1869. elif isinstance(edited_obj, ExcellonObject):
  1870. obj_type = "Excellon"
  1871. if cleanup is None:
  1872. self.exc_editor.update_fcexcellon(edited_obj)
  1873. # self.exc_editor.update_options(edited_obj)
  1874. self.exc_editor.deactivate()
  1875. # restore GUI to the Selected TAB
  1876. # Remove anything else in the GUI
  1877. self.ui.tool_scroll_area.takeWidget()
  1878. # delete the old object (the source object) if it was an empty one
  1879. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1880. old_name = edited_obj.options['name']
  1881. self.collection.delete_by_name(name=old_name)
  1882. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1883. else:
  1884. self.inform.emit('[WARNING_NOTCL] %s' %
  1885. _("Select a Gerber, Geometry or Excellon Object to update."))
  1886. return
  1887. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1888. elif response == bt_no:
  1889. # clean the Tools Tab
  1890. self.ui.tool_scroll_area.takeWidget()
  1891. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1892. self.ui.notebook.setTabText(2, "Tool")
  1893. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1894. if isinstance(edited_obj, GeometryObject):
  1895. self.geo_editor.deactivate()
  1896. edited_obj.build_ui()
  1897. elif isinstance(edited_obj, GerberObject):
  1898. self.grb_editor.deactivate_grb_editor()
  1899. edited_obj.build_ui()
  1900. elif isinstance(edited_obj, ExcellonObject):
  1901. self.exc_editor.deactivate()
  1902. edited_obj.build_ui()
  1903. else:
  1904. self.inform.emit('[WARNING_NOTCL] %s' %
  1905. _("Select a Gerber, Geometry or Excellon Object to update."))
  1906. return
  1907. elif response == bt_cancel:
  1908. return
  1909. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1910. # edited_obj.build_ui()
  1911. # Switch notebook to Selected page
  1912. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1913. else:
  1914. if isinstance(edited_obj, GeometryObject):
  1915. self.geo_editor.deactivate()
  1916. elif isinstance(edited_obj, GerberObject):
  1917. self.grb_editor.deactivate_grb_editor()
  1918. elif isinstance(edited_obj, ExcellonObject):
  1919. self.exc_editor.deactivate()
  1920. else:
  1921. self.inform.emit('[WARNING_NOTCL] %s' %
  1922. _("Select a Gerber, Geometry or Excellon Object to update."))
  1923. return
  1924. # if notebook is hidden we show it
  1925. if self.ui.splitter.sizes()[0] == 0:
  1926. self.ui.splitter.setSizes([1, 1])
  1927. # restore the call_source to app
  1928. self.call_source = 'app'
  1929. edited_obj.plot()
  1930. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1931. self.ui.plot_tab_area.protectTab(0)
  1932. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1933. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1934. self.ui.project_frame.setDisabled(False)
  1935. def get_last_folder(self):
  1936. """
  1937. Get the folder path from where the last file was opened.
  1938. :return: String, last opened folder path
  1939. """
  1940. return self.defaults["global_last_folder"]
  1941. def get_last_save_folder(self):
  1942. """
  1943. Get the folder path from where the last file was saved.
  1944. :return: String, last saved folder path
  1945. """
  1946. loc = self.defaults["global_last_save_folder"]
  1947. if loc is None:
  1948. loc = self.defaults["global_last_folder"]
  1949. if loc is None:
  1950. loc = os.path.dirname(__file__)
  1951. return loc
  1952. def info(self, msg):
  1953. """
  1954. Informs the user. Normally on the status bar, optionally
  1955. also on the shell.
  1956. :param msg: Text to write.
  1957. :return: None
  1958. """
  1959. # Type of message in brackets at the beginning of the message.
  1960. match = re.search(r"\[(.*)\](.*)", msg)
  1961. if match:
  1962. level = match.group(1)
  1963. msg_ = match.group(2)
  1964. self.ui.fcinfo.set_status(str(msg_), level=level)
  1965. if level.lower() == "error":
  1966. self.shell_message(msg, error=True, show=True)
  1967. elif level.lower() == "warning":
  1968. self.shell_message(msg, warning=True, show=True)
  1969. elif level.lower() == "error_notcl":
  1970. self.shell_message(msg, error=True, show=False)
  1971. elif level.lower() == "warning_notcl":
  1972. self.shell_message(msg, warning=True, show=False)
  1973. elif level.lower() == "success":
  1974. self.shell_message(msg, success=True, show=False)
  1975. elif level.lower() == "selected":
  1976. self.shell_message(msg, selected=True, show=False)
  1977. else:
  1978. self.shell_message(msg, show=False)
  1979. else:
  1980. self.ui.fcinfo.set_status(str(msg), level="info")
  1981. # make sure that if the message is to clear the infobar with a space
  1982. # is not printed over and over on the shell
  1983. if msg != '':
  1984. self.shell_message(msg)
  1985. def restore_toolbar_view(self):
  1986. """
  1987. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1988. was saved in the defaults dictionary.
  1989. :return: None
  1990. """
  1991. tb = self.defaults["global_toolbar_view"]
  1992. if tb & 1:
  1993. self.ui.toolbarfile.setVisible(True)
  1994. else:
  1995. self.ui.toolbarfile.setVisible(False)
  1996. if tb & 2:
  1997. self.ui.toolbargeo.setVisible(True)
  1998. else:
  1999. self.ui.toolbargeo.setVisible(False)
  2000. if tb & 4:
  2001. self.ui.toolbarview.setVisible(True)
  2002. else:
  2003. self.ui.toolbarview.setVisible(False)
  2004. if tb & 8:
  2005. self.ui.toolbartools.setVisible(True)
  2006. else:
  2007. self.ui.toolbartools.setVisible(False)
  2008. if tb & 16:
  2009. self.ui.exc_edit_toolbar.setVisible(True)
  2010. else:
  2011. self.ui.exc_edit_toolbar.setVisible(False)
  2012. if tb & 32:
  2013. self.ui.geo_edit_toolbar.setVisible(True)
  2014. else:
  2015. self.ui.geo_edit_toolbar.setVisible(False)
  2016. if tb & 64:
  2017. self.ui.grb_edit_toolbar.setVisible(True)
  2018. else:
  2019. self.ui.grb_edit_toolbar.setVisible(False)
  2020. if tb & 128:
  2021. self.ui.snap_toolbar.setVisible(True)
  2022. else:
  2023. self.ui.snap_toolbar.setVisible(False)
  2024. if tb & 256:
  2025. self.ui.toolbarshell.setVisible(True)
  2026. else:
  2027. self.ui.toolbarshell.setVisible(False)
  2028. def on_import_preferences(self):
  2029. """
  2030. Loads the application default settings from a saved file into
  2031. ``self.defaults`` dictionary.
  2032. :return: None
  2033. """
  2034. self.defaults.report_usage("on_import_preferences")
  2035. App.log.debug("App.on_import_preferences()")
  2036. # Show file chooser
  2037. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2038. try:
  2039. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2040. directory=self.data_path,
  2041. filter=filter_)
  2042. except TypeError:
  2043. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2044. filter=filter_)
  2045. filename = str(filename)
  2046. if filename == "":
  2047. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2048. return
  2049. # Load in the defaults from the chosen file
  2050. self.defaults.load(filename=filename)
  2051. self.preferencesUiManager.on_preferences_edited()
  2052. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2053. def on_export_preferences(self):
  2054. """
  2055. Save the defaults dictionary to a file.
  2056. :return: None
  2057. """
  2058. self.defaults.report_usage("on_export_preferences")
  2059. App.log.debug("on_export_preferences()")
  2060. # defaults_file_content = None
  2061. # Show file chooser
  2062. date = str(datetime.today()).rpartition('.')[0]
  2063. date = ''.join(c for c in date if c not in ':-')
  2064. date = date.replace(' ', '_')
  2065. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2066. try:
  2067. filename, _f = FCFileSaveDialog.get_saved_filename(
  2068. caption=_("Export FlatCAM Preferences"),
  2069. directory=self.data_path + '/preferences_' + date,
  2070. filter=filter__
  2071. )
  2072. except TypeError:
  2073. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2074. filename = str(filename)
  2075. if filename == "":
  2076. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2077. return
  2078. # Update options
  2079. self.preferencesUiManager.defaults_read_form()
  2080. self.defaults.propagate_defaults()
  2081. # Save update options
  2082. try:
  2083. self.defaults.write(filename=filename)
  2084. except Exception:
  2085. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2086. return
  2087. if self.defaults["global_open_style"] is False:
  2088. self.file_opened.emit("preferences", filename)
  2089. self.file_saved.emit("preferences", filename)
  2090. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2091. def save_to_file(self, content_to_save, txt_content):
  2092. """
  2093. Save something to a file.
  2094. :return: None
  2095. """
  2096. self.defaults.report_usage("save_to_file")
  2097. App.log.debug("save_to_file()")
  2098. self.date = str(datetime.today()).rpartition('.')[0]
  2099. self.date = ''.join(c for c in self.date if c not in ':-')
  2100. self.date = self.date.replace(' ', '_')
  2101. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2102. path_to_save = self.defaults["global_last_save_folder"] if \
  2103. self.defaults["global_last_save_folder"] is not None else self.data_path
  2104. try:
  2105. filename, _f = FCFileSaveDialog.get_saved_filename(
  2106. caption=_("Save to file"),
  2107. directory=path_to_save + '/file_' + self.date,
  2108. filter=filter__
  2109. )
  2110. except TypeError:
  2111. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2112. filename = str(filename)
  2113. if filename == "":
  2114. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2115. return
  2116. else:
  2117. try:
  2118. with open(filename, 'w') as f:
  2119. ___ = f.read()
  2120. except PermissionError:
  2121. self.inform.emit('[WARNING] %s' %
  2122. _("Permission denied, saving not possible.\n"
  2123. "Most likely another app is holding the file open and not accessible."))
  2124. return
  2125. except IOError:
  2126. App.log.debug('Creating a new file ...')
  2127. f = open(filename, 'w')
  2128. f.close()
  2129. except Exception:
  2130. e = sys.exc_info()[0]
  2131. App.log.error("Could not load the file.")
  2132. App.log.error(str(e))
  2133. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2134. return
  2135. # Save content
  2136. if filename.rpartition('.')[2].lower() == 'html':
  2137. file_content = content_to_save
  2138. else:
  2139. file_content = txt_content
  2140. try:
  2141. with open(filename, "w") as f:
  2142. f.write(file_content)
  2143. except Exception:
  2144. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2145. return
  2146. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2147. def save_geometry(self, x, y, width, height, notebook_width):
  2148. """
  2149. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2150. launch of the application.
  2151. :param x: X position of the main window
  2152. :param y: Y position of the main window
  2153. :param width: width of the main window
  2154. :param height: height of the main window
  2155. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2156. :return: None
  2157. """
  2158. self.defaults["global_def_win_x"] = x
  2159. self.defaults["global_def_win_y"] = y
  2160. self.defaults["global_def_win_w"] = width
  2161. self.defaults["global_def_win_h"] = height
  2162. self.defaults["global_def_notebook_width"] = notebook_width
  2163. self.preferencesUiManager.save_defaults()
  2164. def restore_main_win_geom(self):
  2165. try:
  2166. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2167. self.defaults["global_def_win_y"],
  2168. self.defaults["global_def_win_w"],
  2169. self.defaults["global_def_win_h"])
  2170. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2171. except KeyError as e:
  2172. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2173. def message_dialog(self, title, message, kind="info"):
  2174. """
  2175. Builds and show a custom QMessageBox to be used in FlatCAM.
  2176. :param title: title of the QMessageBox
  2177. :param message: message to be displayed
  2178. :param kind: type of QMessageBox; will display a specific icon.
  2179. :return:
  2180. """
  2181. icon = {"info": QtWidgets.QMessageBox.Information,
  2182. "warning": QtWidgets.QMessageBox.Warning,
  2183. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2184. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2185. dlg.setText(message)
  2186. dlg.exec_()
  2187. def register_recent(self, kind, filename):
  2188. """
  2189. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2190. dictionary.
  2191. :param kind: type of file that was opened
  2192. :param filename: the path and file name for the file that was opened
  2193. :return:
  2194. """
  2195. self.log.debug("register_recent()")
  2196. self.log.debug(" %s" % kind)
  2197. self.log.debug(" %s" % filename)
  2198. record = {'kind': str(kind), 'filename': str(filename)}
  2199. if record in self.recent:
  2200. return
  2201. if record in self.recent_projects:
  2202. return
  2203. if record['kind'] == 'project':
  2204. self.recent_projects.insert(0, record)
  2205. else:
  2206. self.recent.insert(0, record)
  2207. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2208. self.recent.pop()
  2209. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2210. self.recent_projects.pop()
  2211. try:
  2212. f = open(self.data_path + '/recent.json', 'w')
  2213. except IOError:
  2214. App.log.error("Failed to open recent items file for writing.")
  2215. self.inform.emit('[ERROR_NOTCL] %s' %
  2216. _('Failed to open recent files file for writing.'))
  2217. return
  2218. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2219. f.close()
  2220. try:
  2221. fp = open(self.data_path + '/recent_projects.json', 'w')
  2222. except IOError:
  2223. App.log.error("Failed to open recent items file for writing.")
  2224. self.inform.emit('[ERROR_NOTCL] %s' %
  2225. _('Failed to open recent projects file for writing.'))
  2226. return
  2227. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2228. fp.close()
  2229. # Re-build the recent items menu
  2230. self.setup_recent_items()
  2231. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2232. """
  2233. Creates a new specialized FlatCAMObj and attaches it to the application,
  2234. this is, updates the GUI accordingly, any other records and plots it.
  2235. This method is thread-safe.
  2236. Notes:
  2237. * If the name is in use, the self.collection will modify it
  2238. when appending it to the collection. There is no need to handle
  2239. name conflicts here.
  2240. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2241. :type kind: str
  2242. :param name: Name for the object.
  2243. :type name: str
  2244. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2245. The function is called with 2 parameters: the new object and the App instance.
  2246. :type initialize: function
  2247. :param plot: If to plot the resulting object
  2248. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2249. self.collection
  2250. :return: None
  2251. :rtype: None
  2252. """
  2253. App.log.debug("new_object()")
  2254. obj_plot = plot
  2255. obj_autoselected = autoselected
  2256. t0 = time.time() # Debug
  2257. # ## Create object
  2258. classdict = {
  2259. "gerber": GerberObject,
  2260. "excellon": ExcellonObject,
  2261. "cncjob": CNCJobObject,
  2262. "geometry": GeometryObject,
  2263. "script": ScriptObject,
  2264. "document": DocumentObject
  2265. }
  2266. App.log.debug("Calling object constructor...")
  2267. # Object creation/instantiation
  2268. obj = classdict[kind](name)
  2269. obj.units = self.options["units"]
  2270. # IMPORTANT
  2271. # The key names in defaults and options dictionary's are not random:
  2272. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2273. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2274. # copied to self.options. After that, below, depending on the type of
  2275. # object that is created, it will strip the name of the object and the underline (if the original key was
  2276. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2277. # "toolchange"
  2278. for option in self.options:
  2279. if option.find(kind + "_") == 0:
  2280. oname = option[len(kind) + 1:]
  2281. obj.options[oname] = self.options[option]
  2282. obj.isHovering = False
  2283. obj.notHovering = True
  2284. # Initialize as per user request
  2285. # User must take care to implement initialize
  2286. # in a thread-safe way as is is likely that we
  2287. # have been invoked in a separate thread.
  2288. t1 = time.time()
  2289. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2290. try:
  2291. return_value = initialize(obj, self)
  2292. except Exception as e:
  2293. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2294. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2295. msg += traceback.format_exc()
  2296. self.inform.emit(msg)
  2297. return "fail"
  2298. t2 = time.time()
  2299. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2300. if return_value == 'fail':
  2301. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2302. return "fail"
  2303. # Check units and convert if necessary
  2304. # This condition CAN be true because initialize() can change obj.units
  2305. if self.options["units"].upper() != obj.units.upper():
  2306. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2307. obj.convert_units(self.options["units"])
  2308. t3 = time.time()
  2309. self.log.debug("%f seconds converting units." % (t3 - t2))
  2310. # Create the bounding box for the object and then add the results to the obj.options
  2311. # But not for Scripts or for Documents
  2312. if kind != 'document' and kind != 'script':
  2313. try:
  2314. xmin, ymin, xmax, ymax = obj.bounds()
  2315. obj.options['xmin'] = xmin
  2316. obj.options['ymin'] = ymin
  2317. obj.options['xmax'] = xmax
  2318. obj.options['ymax'] = ymax
  2319. except Exception as e:
  2320. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2321. return "fail"
  2322. try:
  2323. if kind == 'excellon':
  2324. obj.fill_color = self.defaults["excellon_plot_fill"]
  2325. obj.outline_color = self.defaults["excellon_plot_line"]
  2326. if kind == 'gerber':
  2327. obj.fill_color = self.defaults["gerber_plot_fill"]
  2328. obj.outline_color = self.defaults["gerber_plot_line"]
  2329. except Exception as e:
  2330. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2331. # update the KeyWords list with the name of the file
  2332. self.myKeywords.append(obj.options['name'])
  2333. log.debug("Moving new object back to main thread.")
  2334. # Move the object to the main thread and let the app know that it is available.
  2335. obj.moveToThread(self.main_thread)
  2336. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2337. return obj
  2338. def new_excellon_object(self):
  2339. """
  2340. Creates a new, blank Excellon object.
  2341. :return: None
  2342. """
  2343. self.defaults.report_usage("new_excellon_object()")
  2344. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2345. def new_geometry_object(self):
  2346. """
  2347. Creates a new, blank and single-tool Geometry object.
  2348. :return: None
  2349. """
  2350. self.defaults.report_usage("new_geometry_object()")
  2351. def initialize(obj, app):
  2352. obj.multitool = False
  2353. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2354. def new_gerber_object(self):
  2355. """
  2356. Creates a new, blank Gerber object.
  2357. :return: None
  2358. """
  2359. self.defaults.report_usage("new_gerber_object()")
  2360. def initialize(grb_obj, app):
  2361. grb_obj.multitool = False
  2362. grb_obj.source_file = []
  2363. grb_obj.multigeo = False
  2364. grb_obj.follow = False
  2365. grb_obj.apertures = {}
  2366. grb_obj.solid_geometry = []
  2367. try:
  2368. grb_obj.options['xmin'] = 0
  2369. grb_obj.options['ymin'] = 0
  2370. grb_obj.options['xmax'] = 0
  2371. grb_obj.options['ymax'] = 0
  2372. except KeyError:
  2373. pass
  2374. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2375. def new_script_object(self):
  2376. """
  2377. Creates a new, blank TCL Script object.
  2378. :return: None
  2379. """
  2380. self.defaults.report_usage("new_script_object()")
  2381. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2382. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2383. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2384. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2385. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2386. # "ListSys, MillDrills,\n" \
  2387. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2388. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2389. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2390. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2391. # "# SubtractRectangle, Version, WriteGCode\n"
  2392. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2393. '# %s:\n' % _('TCL Tutorial is here') + \
  2394. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2395. '# %s:\n' % _("FlatCAM commands list")
  2396. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2397. "(displayed in Tcl Shell).")
  2398. def initialize(obj, app):
  2399. obj.source_file = deepcopy(new_source_file)
  2400. outname = 'new_script'
  2401. self.new_object('script', outname, initialize, plot=False)
  2402. def new_document_object(self):
  2403. """
  2404. Creates a new, blank Document object.
  2405. :return: None
  2406. """
  2407. self.defaults.report_usage("new_document_object()")
  2408. def initialize(obj, app):
  2409. obj.source_file = ""
  2410. self.new_object('document', 'new_document', initialize, plot=False)
  2411. def on_object_created(self, obj, plot, auto_select):
  2412. """
  2413. Event callback for object creation.
  2414. It will add the new object to the collection. After that it will plot the object in a threaded way
  2415. :param obj: The newly created FlatCAM object.
  2416. :param plot: if the newly create object t obe plotted
  2417. :param auto_select: if the newly created object to be autoselected after creation
  2418. :return: None
  2419. """
  2420. t0 = time.time() # DEBUG
  2421. self.log.debug("on_object_created()")
  2422. # The Collection might change the name if there is a collision
  2423. self.collection.append(obj)
  2424. # after adding the object to the collection always update the list of objects that are in the collection
  2425. self.all_objects_list = self.collection.get_list()
  2426. # self.inform.emit('[selected] %s created & selected: %s' %
  2427. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2428. if obj.kind == 'gerber':
  2429. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2430. kind=obj.kind.capitalize(),
  2431. color='green',
  2432. name=str(obj.options['name']), tx=_("created/selected"))
  2433. )
  2434. elif obj.kind == 'excellon':
  2435. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2436. kind=obj.kind.capitalize(),
  2437. color='brown',
  2438. name=str(obj.options['name']), tx=_("created/selected"))
  2439. )
  2440. elif obj.kind == 'cncjob':
  2441. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2442. kind=obj.kind.capitalize(),
  2443. color='blue',
  2444. name=str(obj.options['name']), tx=_("created/selected"))
  2445. )
  2446. elif obj.kind == 'geometry':
  2447. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2448. kind=obj.kind.capitalize(),
  2449. color='red',
  2450. name=str(obj.options['name']), tx=_("created/selected"))
  2451. )
  2452. elif obj.kind == 'script':
  2453. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2454. kind=obj.kind.capitalize(),
  2455. color='orange',
  2456. name=str(obj.options['name']), tx=_("created/selected"))
  2457. )
  2458. elif obj.kind == 'document':
  2459. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2460. kind=obj.kind.capitalize(),
  2461. color='darkCyan',
  2462. name=str(obj.options['name']), tx=_("created/selected"))
  2463. )
  2464. # update the SHELL auto-completer model with the name of the new object
  2465. self.shell._edit.set_model_data(self.myKeywords)
  2466. if auto_select:
  2467. # select the just opened object but deselect the previous ones
  2468. self.collection.set_all_inactive()
  2469. self.collection.set_active(obj.options["name"])
  2470. else:
  2471. self.collection.set_all_inactive()
  2472. # here it is done the object plotting
  2473. def worker_task(t_obj):
  2474. with self.proc_container.new(_("Plotting")):
  2475. if isinstance(t_obj, CNCJobObject):
  2476. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2477. else:
  2478. t_obj.plot()
  2479. t1 = time.time() # DEBUG
  2480. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2481. self.object_plotted.emit(t_obj)
  2482. # Send to worker
  2483. # self.worker.add_task(worker_task, [self])
  2484. if plot is True:
  2485. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2486. def on_object_changed(self, obj):
  2487. """
  2488. Called whenever the geometry of the object was changed in some way.
  2489. This require the update of it's bounding values so it can be the selected on canvas.
  2490. Update the bounding box data from obj.options
  2491. :param obj: the object that was changed
  2492. :return: None
  2493. """
  2494. xmin, ymin, xmax, ymax = obj.bounds()
  2495. obj.options['xmin'] = xmin
  2496. obj.options['ymin'] = ymin
  2497. obj.options['xmax'] = xmax
  2498. obj.options['ymax'] = ymax
  2499. log.debug("Object changed, updating the bounding box data on self.options")
  2500. # delete the old selection shape
  2501. self.delete_selection_shape()
  2502. self.should_we_save = True
  2503. def on_object_plotted(self):
  2504. """
  2505. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2506. :return: None
  2507. """
  2508. self.on_zoom_fit(None)
  2509. def on_about(self):
  2510. """
  2511. Displays the "about" dialog found in the Menu --> Help.
  2512. :return: None
  2513. """
  2514. self.defaults.report_usage("on_about")
  2515. version = self.version
  2516. version_date = self.version_date
  2517. beta = self.beta
  2518. class AboutDialog(QtWidgets.QDialog):
  2519. def __init__(self, app, parent=None):
  2520. QtWidgets.QDialog.__init__(self, parent)
  2521. self.app = app
  2522. # Icon and title
  2523. self.setWindowIcon(parent.app_icon)
  2524. self.setWindowTitle(_("About FlatCAM"))
  2525. self.resize(600, 200)
  2526. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2527. # self.setStyleSheet(
  2528. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2529. # "background-attachment: fixed"
  2530. # )
  2531. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2532. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2533. # palette = QtGui.QPalette()
  2534. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2535. # self.setPalette(palette)
  2536. logo = QtWidgets.QLabel()
  2537. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2538. title = QtWidgets.QLabel(
  2539. "<font size=8><B>FlatCAM</B></font><BR>"
  2540. "{title}<BR>"
  2541. "<BR>"
  2542. "<BR>"
  2543. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2544. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2545. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2546. "<B>{issue}</B></a><BR>".format(
  2547. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2548. devel=_("Development"),
  2549. down=_("DOWNLOAD"),
  2550. issue=_("Issue tracker"))
  2551. )
  2552. title.setOpenExternalLinks(True)
  2553. closebtn = QtWidgets.QPushButton(_("Close"))
  2554. tab_widget = QtWidgets.QTabWidget()
  2555. description_label = QtWidgets.QLabel(
  2556. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2557. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2558. version=version,
  2559. beta=('BETA' if beta else ''),
  2560. date=version_date,
  2561. arch=platform.architecture()[0])
  2562. )
  2563. description_label.setOpenExternalLinks(True)
  2564. lic_lbl_header = QtWidgets.QLabel(
  2565. '%s:<br>%s<br>' % (
  2566. _('Licensed under the MIT license'),
  2567. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2568. "http://www.opensource.org/licenses/mit-license.php</a>"
  2569. )
  2570. )
  2571. lic_lbl_header.setOpenExternalLinks(True)
  2572. lic_lbl_body = QtWidgets.QLabel(
  2573. _(
  2574. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2575. 'of this software and associated documentation files (the "Software"), to deal\n'
  2576. 'in the Software without restriction, including without limitation the rights\n'
  2577. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2578. 'copies of the Software, and to permit persons to whom the Software is\n'
  2579. 'furnished to do so, subject to the following conditions:\n\n'
  2580. 'The above copyright notice and this permission notice shall be included in\n'
  2581. 'all copies or substantial portions of the Software.\n\n'
  2582. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2583. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2584. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2585. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2586. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2587. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2588. 'THE SOFTWARE.'
  2589. )
  2590. )
  2591. attributions_label = QtWidgets.QLabel(
  2592. _(
  2593. 'Some of the icons used are from the following sources:<br>'
  2594. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2595. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2596. 'title="Flaticon">www.flaticon.com</a></div>'
  2597. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2598. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2599. )
  2600. )
  2601. attributions_label.setOpenExternalLinks(True)
  2602. # layouts
  2603. layout1 = QtWidgets.QVBoxLayout()
  2604. layout1_1 = QtWidgets.QHBoxLayout()
  2605. layout1_2 = QtWidgets.QHBoxLayout()
  2606. layout2 = QtWidgets.QHBoxLayout()
  2607. layout3 = QtWidgets.QHBoxLayout()
  2608. self.setLayout(layout1)
  2609. layout1.addLayout(layout1_1)
  2610. layout1.addLayout(layout1_2)
  2611. layout1.addLayout(layout2)
  2612. layout1.addLayout(layout3)
  2613. layout1_1.addStretch()
  2614. layout1_1.addWidget(description_label)
  2615. layout1_2.addWidget(tab_widget)
  2616. self.splash_tab = QtWidgets.QWidget()
  2617. self.splash_tab.setObjectName("splash_about")
  2618. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2619. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2620. tab_widget.addTab(self.splash_tab, _("Splash"))
  2621. self.programmmers_tab = QtWidgets.QWidget()
  2622. self.programmmers_tab.setObjectName("programmers_about")
  2623. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2624. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2625. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2626. self.translators_tab = QtWidgets.QWidget()
  2627. self.translators_tab.setObjectName("translators_about")
  2628. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2629. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2630. tab_widget.addTab(self.translators_tab, _("Translators"))
  2631. self.license_tab = QtWidgets.QWidget()
  2632. self.license_tab.setObjectName("license_about")
  2633. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2634. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2635. tab_widget.addTab(self.license_tab, _("License"))
  2636. self.attributions_tab = QtWidgets.QWidget()
  2637. self.attributions_tab.setObjectName("attributions_about")
  2638. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2639. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2640. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2641. self.splash_tab_layout.addWidget(logo, stretch=0)
  2642. self.splash_tab_layout.addWidget(title, stretch=1)
  2643. pal = QtGui.QPalette()
  2644. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2645. self.prog_grid_lay = QtWidgets.QGridLayout()
  2646. self.prog_grid_lay.setHorizontalSpacing(20)
  2647. self.prog_grid_lay.setColumnStretch(0, 0)
  2648. self.prog_grid_lay.setColumnStretch(2, 1)
  2649. prog_widget = QtWidgets.QWidget()
  2650. prog_widget.setLayout(self.prog_grid_lay)
  2651. prog_scroll = QtWidgets.QScrollArea()
  2652. prog_scroll.setWidget(prog_widget)
  2653. prog_scroll.setWidgetResizable(True)
  2654. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2655. prog_scroll.setPalette(pal)
  2656. self.programmmers_tab_layout.addWidget(prog_scroll)
  2657. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2658. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2659. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2660. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2661. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2662. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2663. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2664. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2665. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2704. self.translator_grid_lay = QtWidgets.QGridLayout()
  2705. self.translator_grid_lay.setColumnStretch(0, 0)
  2706. self.translator_grid_lay.setColumnStretch(1, 0)
  2707. self.translator_grid_lay.setColumnStretch(2, 1)
  2708. self.translator_grid_lay.setColumnStretch(3, 0)
  2709. # trans_widget = QtWidgets.QWidget()
  2710. # trans_widget.setLayout(self.translator_grid_lay)
  2711. # self.translators_tab_layout.addWidget(trans_widget)
  2712. # self.translators_tab_layout.addStretch()
  2713. trans_widget = QtWidgets.QWidget()
  2714. trans_widget.setLayout(self.translator_grid_lay)
  2715. trans_scroll = QtWidgets.QScrollArea()
  2716. trans_scroll.setWidget(trans_widget)
  2717. trans_scroll.setWidgetResizable(True)
  2718. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2719. trans_scroll.setPalette(pal)
  2720. self.translators_tab_layout.addWidget(trans_scroll)
  2721. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2722. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2723. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2724. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2725. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2726. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2727. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2728. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2750. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2751. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2752. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2753. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2754. self.translator_grid_lay.setColumnStretch(0, 0)
  2755. self.translators_tab_layout.addStretch()
  2756. self.license_tab_layout.addWidget(lic_lbl_header)
  2757. self.license_tab_layout.addWidget(lic_lbl_body)
  2758. self.license_tab_layout.addStretch()
  2759. self.attributions_tab_layout.addWidget(attributions_label)
  2760. self.attributions_tab_layout.addStretch()
  2761. layout3.addStretch()
  2762. layout3.addWidget(closebtn)
  2763. closebtn.clicked.connect(self.accept)
  2764. AboutDialog(app=self, parent=self.ui).exec_()
  2765. def install_bookmarks(self, book_dict=None):
  2766. """
  2767. Install the bookmarks actions in the Help menu -> Bookmarks
  2768. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2769. :return: None
  2770. """
  2771. if book_dict is None:
  2772. self.defaults["global_bookmarks"].update(
  2773. {
  2774. '1': ['FlatCAM', "http://flatcam.org"],
  2775. '2': ['Backup Site', ""]
  2776. }
  2777. )
  2778. else:
  2779. self.defaults["global_bookmarks"].clear()
  2780. self.defaults["global_bookmarks"].update(book_dict)
  2781. # first try to disconnect if somehow they get connected from elsewhere
  2782. for act in self.ui.menuhelp_bookmarks.actions():
  2783. try:
  2784. act.triggered.disconnect()
  2785. except TypeError:
  2786. pass
  2787. # clear all actions except the last one who is the Bookmark manager
  2788. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2789. pass
  2790. else:
  2791. self.ui.menuhelp_bookmarks.removeAction(act)
  2792. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2793. if self.defaults["global_bookmarks"]:
  2794. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2795. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2796. # the JSON is first making the keys as strings (therefore I have to use strings too
  2797. # or do the conversion :(
  2798. # )
  2799. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2800. # the '10' entry jsut after '1' therefore ordering as strings
  2801. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2802. key=lambda x: int(x[0]))
  2803. for entry, bookmark in sorted_bookmarks:
  2804. title = bookmark[0]
  2805. weblink = bookmark[1]
  2806. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2807. act.setText(title)
  2808. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2809. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2810. if title == 'Backup Site' and weblink == "":
  2811. act.triggered.connect(self.on_backup_site)
  2812. else:
  2813. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2814. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2815. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2816. def on_bookmarks_manager(self):
  2817. """
  2818. Adds the bookmark manager in a Tab in Plot Area
  2819. :return:
  2820. """
  2821. for idx in range(self.ui.plot_tab_area.count()):
  2822. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2823. # there can be only one instance of Bookmark Manager at one time
  2824. return
  2825. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2826. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2827. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2828. # add the tab if it was closed
  2829. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2830. # delete the absolute and relative position and messages in the infobar
  2831. self.ui.position_label.setText("")
  2832. self.ui.rel_position_label.setText("")
  2833. # Switch plot_area to preferences page
  2834. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2835. def on_backup_site(self):
  2836. msgbox = QtWidgets.QMessageBox()
  2837. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2838. "1. FlatCAM.org website is down\n"
  2839. "2. Someone forked FlatCAM project and wants to point\n"
  2840. "to his own website\n\n"
  2841. "If you can't get any informations about FlatCAM beta\n"
  2842. "use the YouTube channel link from the Help menu."))
  2843. msgbox.setWindowTitle(_("Alternative website"))
  2844. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2845. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2846. msgbox.setDefaultButton(bt_yes)
  2847. msgbox.exec_()
  2848. # response = msgbox.clickedButton()
  2849. def on_file_savedefaults(self):
  2850. """
  2851. Callback for menu item File->Save Defaults. Saves application default options
  2852. ``self.defaults`` to current_defaults.FlatConfig.
  2853. :return: None
  2854. """
  2855. self.preferencesUiManager.save_defaults()
  2856. def final_save(self):
  2857. """
  2858. Callback for doing a preferences save to file whenever the application is about to quit.
  2859. If the project has changes, it will ask the user to save the project.
  2860. :return: None
  2861. """
  2862. if self.save_in_progress:
  2863. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2864. return
  2865. if self.should_we_save and self.collection.get_list():
  2866. msgbox = QtWidgets.QMessageBox()
  2867. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2868. "\n"
  2869. "Do you want to Save the project?"))
  2870. msgbox.setWindowTitle(_("Save changes"))
  2871. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2872. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2873. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2874. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2875. msgbox.setDefaultButton(bt_yes)
  2876. msgbox.exec_()
  2877. response = msgbox.clickedButton()
  2878. if response == bt_yes:
  2879. try:
  2880. self.trayIcon.hide()
  2881. except Exception:
  2882. pass
  2883. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2884. elif response == bt_no:
  2885. try:
  2886. self.trayIcon.hide()
  2887. except Exception:
  2888. pass
  2889. self.quit_application()
  2890. elif response == bt_cancel:
  2891. return
  2892. else:
  2893. try:
  2894. self.trayIcon.hide()
  2895. except Exception:
  2896. pass
  2897. self.quit_application()
  2898. def quit_application(self):
  2899. """
  2900. Called (as a pyslot or not) when the application is quit.
  2901. :return: None
  2902. """
  2903. self.preferencesUiManager.save_defaults(silent=True)
  2904. log.debug("App.quit_application() --> App Defaults saved.")
  2905. if self.cmd_line_headless != 1:
  2906. # save app state to file
  2907. stgs = QSettings("Open Source", "FlatCAM")
  2908. stgs.setValue('saved_gui_state', self.ui.saveState())
  2909. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2910. stgs.setValue(
  2911. 'language',
  2912. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2913. )
  2914. stgs.setValue(
  2915. 'notebook_font_size',
  2916. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2917. )
  2918. stgs.setValue(
  2919. 'axis_font_size',
  2920. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2921. )
  2922. stgs.setValue(
  2923. 'textbox_font_size',
  2924. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2925. )
  2926. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2927. stgs.setValue(
  2928. 'machinist',
  2929. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2930. )
  2931. # This will write the setting to the platform specific storage.
  2932. del stgs
  2933. log.debug("App.quit_application() --> App UI state saved.")
  2934. # try to quit the Socket opened by ArgsThread class
  2935. try:
  2936. self.new_launch.thread_exit = True
  2937. self.new_launch.listener.close()
  2938. except Exception as err:
  2939. log.debug("App.quit_application() --> %s" % str(err))
  2940. # try to quit the QThread that run ArgsThread class
  2941. try:
  2942. self.th.terminate()
  2943. except Exception as e:
  2944. log.debug("App.quit_application() --> %s" % str(e))
  2945. # terminate workers
  2946. self.workers.__del__()
  2947. # quit app by signalling for self.kill_app() method
  2948. # self.close_app_signal.emit()
  2949. QtWidgets.qApp.quit()
  2950. # QtCore.QCoreApplication.exit()
  2951. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2952. # we use the following command
  2953. minor_v = sys.version_info.minor
  2954. if minor_v < 8:
  2955. sys.exit(0)
  2956. else:
  2957. os._exit(0) # fix to work with Python 3.8
  2958. @staticmethod
  2959. def kill_app():
  2960. # QtCore.QCoreApplication.quit()
  2961. QtWidgets.qApp.quit()
  2962. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2963. # we use the following command
  2964. sys.exit(0)
  2965. def on_portable_checked(self, state):
  2966. """
  2967. Callback called when the checkbox in Preferences GUI is checked.
  2968. It will set the application as portable by creating the preferences and recent files in the
  2969. 'config' folder found in the FlatCAM installation folder.
  2970. :param state: boolean, the state of the checkbox when clicked/checked
  2971. :return:
  2972. """
  2973. line_no = 0
  2974. data = None
  2975. if sys.platform != 'win32':
  2976. # this won't work in Linux or MacOS
  2977. return
  2978. # test if the app was frozen and choose the path for the configuration file
  2979. if getattr(sys, "frozen", False) is True:
  2980. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2981. else:
  2982. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2983. config_file = current_data_path + '\\configuration.txt'
  2984. try:
  2985. with open(config_file, 'r') as f:
  2986. try:
  2987. data = f.readlines()
  2988. except Exception as e:
  2989. log.debug('App.__init__() -->%s' % str(e))
  2990. return
  2991. except FileNotFoundError:
  2992. pass
  2993. for line in data:
  2994. line = line.strip('\n')
  2995. param = str(line).rpartition('=')
  2996. if param[0] == 'portable':
  2997. break
  2998. line_no += 1
  2999. if state:
  3000. data[line_no] = 'portable=True\n'
  3001. # create the new defauults files
  3002. # create current_defaults.FlatConfig file if there is none
  3003. try:
  3004. f = open(current_data_path + '/current_defaults.FlatConfig')
  3005. f.close()
  3006. except IOError:
  3007. App.log.debug('Creating empty current_defaults.FlatConfig')
  3008. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3009. json.dump({}, f)
  3010. f.close()
  3011. # create factory_defaults.FlatConfig file if there is none
  3012. try:
  3013. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3014. f.close()
  3015. except IOError:
  3016. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3017. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3018. json.dump({}, f)
  3019. f.close()
  3020. try:
  3021. f = open(current_data_path + '/recent.json')
  3022. f.close()
  3023. except IOError:
  3024. App.log.debug('Creating empty recent.json')
  3025. f = open(current_data_path + '/recent.json', 'w')
  3026. json.dump([], f)
  3027. f.close()
  3028. try:
  3029. fp = open(current_data_path + '/recent_projects.json')
  3030. fp.close()
  3031. except IOError:
  3032. App.log.debug('Creating empty recent_projects.json')
  3033. fp = open(current_data_path + '/recent_projects.json', 'w')
  3034. json.dump([], fp)
  3035. fp.close()
  3036. # save the current defaults to the new defaults file
  3037. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3038. else:
  3039. data[line_no] = 'portable=False\n'
  3040. with open(config_file, 'w') as f:
  3041. f.writelines(data)
  3042. def on_register_files(self, obj_type=None):
  3043. """
  3044. Called whenever there is a need to register file extensions with FlatCAM.
  3045. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3046. :param obj_type: the type of object to be register for.
  3047. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3048. :return: None
  3049. """
  3050. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3051. new_reg_path = 'Software\\Classes\\'
  3052. # find if the current user is admin
  3053. try:
  3054. is_admin = os.getuid() == 0
  3055. except AttributeError:
  3056. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3057. if is_admin is True:
  3058. root_path = winreg.HKEY_LOCAL_MACHINE
  3059. else:
  3060. root_path = winreg.HKEY_CURRENT_USER
  3061. # create the keys
  3062. def set_reg(name, root_pth, new_reg_path, value):
  3063. try:
  3064. winreg.CreateKey(root_pth, new_reg_path)
  3065. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3066. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3067. return True
  3068. except WindowsError:
  3069. return False
  3070. # delete key in registry
  3071. def delete_reg(root_pth, reg_path, key_to_del):
  3072. key_to_del_path = reg_path + key_to_del
  3073. try:
  3074. winreg.DeleteKey(root_pth, key_to_del_path)
  3075. return True
  3076. except WindowsError:
  3077. return False
  3078. if obj_type is None or obj_type == 'excellon':
  3079. exc_list = \
  3080. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3081. exc_list = [x for x in exc_list if x != '']
  3082. # register all keys in the Preferences window
  3083. for ext in exc_list:
  3084. new_k = new_reg_path + '.%s' % ext
  3085. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3086. # and unregister those that are no longer in the Preferences windows but are in the file
  3087. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3088. if ext not in exc_list:
  3089. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3090. # now write the updated extensions to the self.defaults
  3091. # new_ext = ''
  3092. # for ext in exc_list:
  3093. # new_ext = new_ext + ext + ', '
  3094. # self.defaults["fa_excellon"] = new_ext
  3095. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3096. if obj_type is None or obj_type == 'gcode':
  3097. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3098. gco_list = [x for x in gco_list if x != '']
  3099. # register all keys in the Preferences window
  3100. for ext in gco_list:
  3101. new_k = new_reg_path + '.%s' % ext
  3102. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3103. # and unregister those that are no longer in the Preferences windows but are in the file
  3104. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3105. if ext not in gco_list:
  3106. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3107. # now write the updated extensions to the self.defaults
  3108. # new_ext = ''
  3109. # for ext in gco_list:
  3110. # new_ext = new_ext + ext + ', '
  3111. # self.defaults["fa_gcode"] = new_ext
  3112. self.inform.emit('[success] %s' %
  3113. _("Selected GCode file extensions registered with FlatCAM."))
  3114. if obj_type is None or obj_type == 'gerber':
  3115. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3116. grb_list = [x for x in grb_list if x != '']
  3117. # register all keys in the Preferences window
  3118. for ext in grb_list:
  3119. new_k = new_reg_path + '.%s' % ext
  3120. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3121. # and unregister those that are no longer in the Preferences windows but are in the file
  3122. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3123. if ext not in grb_list:
  3124. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3125. # now write the updated extensions to the self.defaults
  3126. # new_ext = ''
  3127. # for ext in grb_list:
  3128. # new_ext = new_ext + ext + ', '
  3129. # self.defaults["fa_gerber"] = new_ext
  3130. self.inform.emit('[success] %s' %
  3131. _("Selected Gerber file extensions registered with FlatCAM."))
  3132. def add_extension(self, ext_type):
  3133. """
  3134. Add a file extension to the list for a specific object
  3135. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3136. :return:
  3137. """
  3138. if ext_type == 'excellon':
  3139. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3140. if new_ext == '':
  3141. return
  3142. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3143. if new_ext in old_val:
  3144. return
  3145. old_val.append(new_ext)
  3146. old_val.sort()
  3147. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3148. if ext_type == 'gcode':
  3149. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3150. if new_ext == '':
  3151. return
  3152. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3153. if new_ext in old_val:
  3154. return
  3155. old_val.append(new_ext)
  3156. old_val.sort()
  3157. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3158. if ext_type == 'gerber':
  3159. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3160. if new_ext == '':
  3161. return
  3162. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3163. if new_ext in old_val:
  3164. return
  3165. old_val.append(new_ext)
  3166. old_val.sort()
  3167. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3168. if ext_type == 'keyword':
  3169. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3170. if new_kw == '':
  3171. return
  3172. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3173. if new_kw in old_val:
  3174. return
  3175. old_val.append(new_kw)
  3176. old_val.sort()
  3177. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3178. # update the self.myKeywords so the model is updated
  3179. self.autocomplete_kw_list = \
  3180. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3181. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3182. self.shell._edit.set_model_data(self.myKeywords)
  3183. def del_extension(self, ext_type):
  3184. """
  3185. Remove a file extension from the list for a specific object
  3186. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3187. :return:
  3188. """
  3189. if ext_type == 'excellon':
  3190. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3191. if new_ext == '':
  3192. return
  3193. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3194. if new_ext not in old_val:
  3195. return
  3196. old_val.remove(new_ext)
  3197. old_val.sort()
  3198. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3199. if ext_type == 'gcode':
  3200. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3201. if new_ext == '':
  3202. return
  3203. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3204. if new_ext not in old_val:
  3205. return
  3206. old_val.remove(new_ext)
  3207. old_val.sort()
  3208. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3209. if ext_type == 'gerber':
  3210. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3211. if new_ext == '':
  3212. return
  3213. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3214. if new_ext not in old_val:
  3215. return
  3216. old_val.remove(new_ext)
  3217. old_val.sort()
  3218. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3219. if ext_type == 'keyword':
  3220. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3221. if new_kw == '':
  3222. return
  3223. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3224. if new_kw not in old_val:
  3225. return
  3226. old_val.remove(new_kw)
  3227. old_val.sort()
  3228. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3229. # update the self.myKeywords so the model is updated
  3230. self.autocomplete_kw_list = \
  3231. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3232. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3233. self.shell._edit.set_model_data(self.myKeywords)
  3234. def restore_extensions(self, ext_type):
  3235. """
  3236. Restore all file extensions associations with FlatCAM, for a specific object
  3237. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3238. :return:
  3239. """
  3240. if ext_type == 'excellon':
  3241. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3242. # for the ability to open Excellon files with .txt extension
  3243. new_exc_list = deepcopy(self.exc_list)
  3244. try:
  3245. new_exc_list.remove('txt')
  3246. except ValueError:
  3247. pass
  3248. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3249. if ext_type == 'gcode':
  3250. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3251. if ext_type == 'gerber':
  3252. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3253. if ext_type == 'keyword':
  3254. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3255. # update the self.myKeywords so the model is updated
  3256. self.autocomplete_kw_list = self.default_keywords
  3257. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3258. self.shell._edit.set_model_data(self.myKeywords)
  3259. def delete_all_extensions(self, ext_type):
  3260. """
  3261. Delete all file extensions associations with FlatCAM, for a specific object
  3262. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3263. :return:
  3264. """
  3265. if ext_type == 'excellon':
  3266. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3267. if ext_type == 'gcode':
  3268. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3269. if ext_type == 'gerber':
  3270. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3271. if ext_type == 'keyword':
  3272. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3273. # update the self.myKeywords so the model is updated
  3274. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3275. self.shell._edit.set_model_data(self.myKeywords)
  3276. def on_edit_join(self, name=None):
  3277. """
  3278. Callback for Edit->Join. Joins the selected geometry objects into
  3279. a new one.
  3280. :return: None
  3281. """
  3282. self.defaults.report_usage("on_edit_join()")
  3283. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3284. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3285. geo_type_set = set()
  3286. objs = self.collection.get_selected()
  3287. if len(objs) < 2:
  3288. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3289. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3290. return 'fail'
  3291. for obj in objs:
  3292. geo_type_set.add(obj.multigeo)
  3293. # if len(geo_type_list) == 1 means that all list elements are the same
  3294. if len(geo_type_set) != 1:
  3295. self.inform.emit('[ERROR] %s' %
  3296. _("Failed join. The Geometry objects are of different types.\n"
  3297. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3298. "convert from one to another and retry joining \n"
  3299. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3300. "the result may not be what was expected. \n"
  3301. "Check the generated GCODE."))
  3302. return
  3303. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3304. if True in geo_type_set:
  3305. def initialize(geo_obj, app):
  3306. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  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_multi
  3311. self.new_object("geometry", obj_name_multi, initialize)
  3312. else:
  3313. def initialize(geo_obj, app):
  3314. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3315. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3316. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3317. for v in geo_obj.tools.values():
  3318. v['data']['name'] = obj_name_single
  3319. self.new_object("geometry", obj_name_single, initialize)
  3320. self.should_we_save = True
  3321. def on_edit_join_exc(self):
  3322. """
  3323. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3324. a new Excellon.
  3325. :return: None
  3326. """
  3327. self.defaults.report_usage("on_edit_join_exc()")
  3328. objs = self.collection.get_selected()
  3329. for obj in objs:
  3330. if not isinstance(obj, ExcellonObject):
  3331. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3332. return
  3333. if len(objs) < 2:
  3334. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3335. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3336. return 'fail'
  3337. def initialize(exc_obj, app):
  3338. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3339. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3340. self.new_object("excellon", 'Combo_Excellon', initialize)
  3341. self.should_we_save = True
  3342. def on_edit_join_grb(self):
  3343. """
  3344. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3345. a new Gerber object.
  3346. :return: None
  3347. """
  3348. self.defaults.report_usage("on_edit_join_grb()")
  3349. objs = self.collection.get_selected()
  3350. for obj in objs:
  3351. if not isinstance(obj, GerberObject):
  3352. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3353. return
  3354. if len(objs) < 2:
  3355. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3356. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3357. return 'fail'
  3358. def initialize(grb_obj, app):
  3359. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3360. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3361. self.new_object("gerber", 'Combo_Gerber', initialize)
  3362. self.should_we_save = True
  3363. def on_convert_singlegeo_to_multigeo(self):
  3364. """
  3365. Called for converting a Geometry object from single-geo to multi-geo.
  3366. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3367. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3368. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3369. the solid-geometry of that tool.
  3370. :return: None
  3371. """
  3372. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3373. obj = self.collection.get_active()
  3374. if obj is None:
  3375. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3376. return
  3377. if not isinstance(obj, GeometryObject):
  3378. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3379. return
  3380. obj.multigeo = True
  3381. for tooluid, dict_value in obj.tools.items():
  3382. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3383. if not isinstance(obj.solid_geometry, list):
  3384. obj.solid_geometry = [obj.solid_geometry]
  3385. # obj.solid_geometry[:] = []
  3386. obj.plot()
  3387. self.should_we_save = True
  3388. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3389. def on_convert_multigeo_to_singlegeo(self):
  3390. """
  3391. Called for converting a Geometry object from multi-geo to single-geo.
  3392. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3393. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3394. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3395. the solid-geometry of that tool.
  3396. :return: None
  3397. """
  3398. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3399. obj = self.collection.get_active()
  3400. if obj is None:
  3401. self.inform.emit('[ERROR_NOTCL] %s' %
  3402. _("Failed. Select a Geometry Object and try again."))
  3403. return
  3404. if not isinstance(obj, GeometryObject):
  3405. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3406. (_("Expected a GeometryObject, got"), type(obj)))
  3407. return
  3408. obj.multigeo = False
  3409. total_solid_geometry = []
  3410. for tooluid, dict_value in obj.tools.items():
  3411. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3412. # clear the original geometry
  3413. dict_value['solid_geometry'][:] = []
  3414. obj.solid_geometry = deepcopy(total_solid_geometry)
  3415. obj.plot()
  3416. self.should_we_save = True
  3417. self.inform.emit('[success] %s' %
  3418. _("A Geometry object was converted to SingleGeo type."))
  3419. def on_defaults_dict_change(self, field):
  3420. """
  3421. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3422. Edit -> Preferences tab window.
  3423. :param field: the key of the self.defaults dictionary that was changed.
  3424. :return: None
  3425. """
  3426. self.preferencesUiManager.defaults_write_form_field(field=field)
  3427. if field == "units":
  3428. self.set_screen_units(self.defaults['units'])
  3429. def set_screen_units(self, units):
  3430. """
  3431. Set the FlatCAM units on the status bar.
  3432. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3433. :return: None
  3434. """
  3435. self.ui.units_label.setText("[" + units.lower() + "]")
  3436. def on_toggle_units_click(self):
  3437. try:
  3438. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3439. except (TypeError, AttributeError):
  3440. pass
  3441. if self.defaults["units"] == 'MM':
  3442. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3443. else:
  3444. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3445. self.on_toggle_units(no_pref=True)
  3446. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3447. lambda: self.on_toggle_units(no_pref=False))
  3448. def on_toggle_units(self, no_pref=False):
  3449. """
  3450. Callback for the Units radio-button change in the Preferences tab.
  3451. Changes the application's default units adn for the project too.
  3452. If changing the project's units, the change propagates to all of
  3453. the objects in the project.
  3454. :return: None
  3455. """
  3456. self.defaults.report_usage("on_toggle_units")
  3457. if self.toggle_units_ignore:
  3458. return
  3459. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3460. # If option is the same, then ignore
  3461. if new_units == self.defaults["units"].upper():
  3462. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3463. return
  3464. # Options to scale
  3465. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3466. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3467. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3468. "gerber_editor_ma_high",
  3469. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3470. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3471. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3472. "excellon_feedrate_probe", "excellon_milling_dia",
  3473. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3474. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3475. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3476. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3477. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3478. "geometry_extracut_length", "geometry_z_pdepth",
  3479. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3480. 'cncjob_tooldia',
  3481. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3482. "tools_paintnewdia",
  3483. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3484. "tools_nccnewdia", "tools_ncc_offset_value",
  3485. "tools_2sided_drilldia",
  3486. "tools_film_boundary", "tools_film_scale_stroke",
  3487. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3488. "tools_cutout_depthperpass",
  3489. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3490. "tools_panelize_spacing_rows",
  3491. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3492. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3493. "tools_transform_buffer_dis",
  3494. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3495. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3496. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3497. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3498. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3499. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3500. "tools_cr_h2h_val", "tools_cr_dh_val",
  3501. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3502. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3503. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3504. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3505. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3506. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3507. "tools_copper_thieving_mask_clearance",
  3508. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3509. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3510. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3511. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3512. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3513. "tools_invert_margin",
  3514. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3515. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3516. def scale_defaults(sfactor):
  3517. for dim in dimensions:
  3518. if dim == 'gerber_editor_newdim':
  3519. if self.defaults["gerber_editor_newdim"] is None or self.defaults["gerber_editor_newdim"] == '':
  3520. continue
  3521. coordinates = self.defaults["gerber_editor_newdim"].split(",")
  3522. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3523. coords_xy[0] *= sfactor
  3524. coords_xy[1] *= sfactor
  3525. self.defaults['gerber_editor_newdim'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3526. self.decimals, coords_xy[1])
  3527. if dim == 'excellon_toolchangexy':
  3528. if self.defaults["excellon_toolchangexy"] is None or self.defaults["excellon_toolchangexy"] == '':
  3529. continue
  3530. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3531. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3532. coords_xy[0] *= sfactor
  3533. coords_xy[1] *= sfactor
  3534. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3535. self.decimals, coords_xy[1])
  3536. elif dim == 'geometry_toolchangexy':
  3537. if self.defaults["geometry_toolchangexy"] is None or self.defaults["geometry_toolchangexy"] == '':
  3538. continue
  3539. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3540. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3541. coords_xy[0] *= sfactor
  3542. coords_xy[1] *= sfactor
  3543. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3544. self.decimals, coords_xy[1])
  3545. elif dim == 'excellon_endxy':
  3546. if self.defaults["excellon_endxy"] is None or self.defaults["excellon_endxy"] == '':
  3547. continue
  3548. coordinates = self.defaults["excellon_endxy"].split(",")
  3549. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3550. end_coords_xy[0] *= sfactor
  3551. end_coords_xy[1] *= sfactor
  3552. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3553. self.decimals, end_coords_xy[1])
  3554. elif dim == 'geometry_endxy':
  3555. if self.defaults["geometry_endxy"] is None or self.defaults["geometry_endxy"] == '':
  3556. continue
  3557. coordinates = self.defaults["geometry_endxy"].split(",")
  3558. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3559. end_coords_xy[0] *= sfactor
  3560. end_coords_xy[1] *= sfactor
  3561. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3562. self.decimals, end_coords_xy[1])
  3563. elif dim == 'geometry_cnctooldia':
  3564. if self.defaults["geometry_cnctooldia"] is None or self.defaults["geometry_cnctooldia"] == '':
  3565. continue
  3566. if type(self.defaults["geometry_cnctooldia"]) is float:
  3567. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  3568. else:
  3569. try:
  3570. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3571. tools_diameters = [eval(a) for a in tools_string if a != '']
  3572. except Exception as e:
  3573. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3574. continue
  3575. self.defaults['geometry_cnctooldia'] = ''
  3576. for t in range(len(tools_diameters)):
  3577. tools_diameters[t] *= sfactor
  3578. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  3579. elif dim == 'tools_ncctools':
  3580. if self.defaults["tools_ncctools"] is None or self.defaults["tools_ncctools"] == '':
  3581. continue
  3582. if type(self.defaults["tools_ncctools"]) == float:
  3583. ncctools = [self.defaults["tools_ncctools"]]
  3584. else:
  3585. try:
  3586. tools_string = self.defaults["tools_ncctools"].split(",")
  3587. ncctools = [eval(a) for a in tools_string if a != '']
  3588. except Exception as e:
  3589. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3590. continue
  3591. self.defaults['tools_ncctools'] = ''
  3592. for t in range(len(ncctools)):
  3593. ncctools[t] *= sfactor
  3594. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  3595. elif dim == 'tools_solderpaste_tools':
  3596. if self.defaults["tools_solderpaste_tools"] is None or \
  3597. self.defaults["tools_solderpaste_tools"] == '':
  3598. continue
  3599. if type(self.defaults["tools_solderpaste_tools"]) == float:
  3600. sptools = [self.defaults["tools_solderpaste_tools"]]
  3601. else:
  3602. try:
  3603. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3604. sptools = [eval(a) for a in tools_string if a != '']
  3605. except Exception as e:
  3606. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3607. continue
  3608. self.defaults['tools_solderpaste_tools'] = ""
  3609. for t in range(len(sptools)):
  3610. sptools[t] *= sfactor
  3611. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  3612. elif dim == 'tools_solderpaste_xy_toolchange':
  3613. if self.defaults["tools_solderpaste_xy_toolchange"] is None or \
  3614. self.defaults["tools_solderpaste_xy_toolchange"] == '':
  3615. continue
  3616. try:
  3617. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3618. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3619. sp_coords[0] *= sfactor
  3620. sp_coords[1] *= sfactor
  3621. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  3622. self.decimals, sp_coords[1])
  3623. except Exception as e:
  3624. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3625. continue
  3626. elif dim == 'tools_cal_toolchange_xy':
  3627. if self.defaults["tools_cal_toolchange_xy"] is None or \
  3628. self.defaults["tools_cal_toolchange_xy"] == '':
  3629. continue
  3630. coordinates = self.defaults["tools_cal_toolchange_xy"].split(",")
  3631. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3632. end_coords_xy[0] *= sfactor
  3633. end_coords_xy[1] *= sfactor
  3634. self.defaults['tools_cal_toolchange_xy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3635. self.decimals, end_coords_xy[1])
  3636. elif dim == 'global_gridx' or dim == 'global_gridy':
  3637. if new_units == 'IN':
  3638. try:
  3639. val = float(self.defaults[dim]) * sfactor
  3640. except Exception as e:
  3641. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3642. continue
  3643. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3644. else:
  3645. try:
  3646. val = float(self.defaults[dim]) * sfactor
  3647. except Exception as e:
  3648. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3649. continue
  3650. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3651. else:
  3652. if self.defaults[dim]:
  3653. try:
  3654. val = float(self.defaults[dim]) * sfactor
  3655. except Exception as e:
  3656. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3657. continue
  3658. self.defaults[dim] = val
  3659. # The scaling factor depending on choice of units.
  3660. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3661. # Changing project units. Warn user.
  3662. msgbox = QtWidgets.QMessageBox()
  3663. msgbox.setWindowTitle(_("Toggle Units"))
  3664. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3665. msgbox.setText(_("Changing the units of the project\n"
  3666. "will scale all objects.\n\n"
  3667. "Do you want to continue?"))
  3668. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3669. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3670. msgbox.setDefaultButton(bt_ok)
  3671. msgbox.exec_()
  3672. response = msgbox.clickedButton()
  3673. if response == bt_ok:
  3674. if no_pref is False:
  3675. self.preferencesUiManager.defaults_read_form()
  3676. scale_defaults(factor)
  3677. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3678. self.defaults["units"] = new_units
  3679. # update the defaults from form, some may assume that the conversion is enough and it's not
  3680. self.on_options_app2project()
  3681. # update the objects
  3682. for obj in self.collection.get_list():
  3683. obj.convert_units(new_units)
  3684. # make that the properties stored in the object are also updated
  3685. self.object_changed.emit(obj)
  3686. # rebuild the object UI
  3687. obj.build_ui()
  3688. # change this only if the workspace is active
  3689. if self.defaults['global_workspace'] is True:
  3690. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3691. # adjust the grid values on the main toolbar
  3692. val_x = float(self.defaults['global_gridx']) * factor
  3693. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3694. current = self.collection.get_active()
  3695. if current is not None:
  3696. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3697. if not isinstance(current, GeometryObject):
  3698. current.to_form()
  3699. # replot all objects
  3700. self.plot_all()
  3701. # set the status labels to reflect the current FlatCAM units
  3702. self.set_screen_units(new_units)
  3703. # signal to the app that we changed the object properties and it shoud save the project
  3704. self.should_we_save = True
  3705. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3706. else:
  3707. # Undo toggling
  3708. self.toggle_units_ignore = True
  3709. if self.defaults['units'].upper() == 'MM':
  3710. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3711. else:
  3712. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3713. self.toggle_units_ignore = False
  3714. # store the grid values so they are not changed in the next step
  3715. val_x = float(self.defaults['global_gridx'])
  3716. val_y = float(self.defaults['global_gridy'])
  3717. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3718. self.preferencesUiManager.defaults_read_form()
  3719. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3720. # in self.defaults from the GUI elements but
  3721. # I don't want it for the grid values, so I update them here
  3722. self.defaults['global_gridx'] = val_x
  3723. self.defaults['global_gridy'] = val_y
  3724. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3725. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3726. def on_fullscreen(self, disable=False):
  3727. self.defaults.report_usage("on_fullscreen()")
  3728. flags = self.ui.windowFlags()
  3729. if self.toggle_fscreen is False and disable is False:
  3730. # self.ui.showFullScreen()
  3731. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3732. a = self.ui.geometry()
  3733. self.x_pos = a.x()
  3734. self.y_pos = a.y()
  3735. self.width = a.width()
  3736. self.height = a.height()
  3737. # set new geometry to full desktop rect
  3738. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3739. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3740. # everything else will not work without this hack. This happen in Windows.
  3741. # https://bugreports.qt.io/browse/QTBUG-41309
  3742. desktop = QtWidgets.QApplication.desktop()
  3743. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3744. rec = desktop.screenGeometry(screen)
  3745. x = rec.x() - 1
  3746. y = rec.y() - 1
  3747. h = rec.height() + 2
  3748. w = rec.width() + 2
  3749. self.ui.setGeometry(x, y, w, h)
  3750. self.ui.show()
  3751. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3752. tb.setVisible(False)
  3753. self.ui.splitter_left.setVisible(False)
  3754. self.toggle_fscreen = True
  3755. elif self.toggle_fscreen is True or disable is True:
  3756. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3757. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3758. self.ui.showNormal()
  3759. self.restore_toolbar_view()
  3760. self.ui.splitter_left.setVisible(True)
  3761. self.toggle_fscreen = False
  3762. def on_toggle_plotarea(self):
  3763. self.defaults.report_usage("on_toggle_plotarea()")
  3764. try:
  3765. name = self.ui.plot_tab_area.widget(0).objectName()
  3766. except AttributeError:
  3767. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3768. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3769. self.ui.plot_tab_area.protectTab(0)
  3770. return
  3771. if name != 'plotarea_tab':
  3772. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3773. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3774. self.ui.plot_tab_area.protectTab(0)
  3775. else:
  3776. self.ui.plot_tab_area.closeTab(0)
  3777. def on_toggle_notebook(self):
  3778. if self.ui.splitter.sizes()[0] == 0:
  3779. self.ui.splitter.setSizes([1, 1])
  3780. self.ui.menu_toggle_nb.setChecked(True)
  3781. else:
  3782. self.ui.splitter.setSizes([0, 1])
  3783. self.ui.menu_toggle_nb.setChecked(False)
  3784. def on_toggle_axis(self):
  3785. self.defaults.report_usage("on_toggle_axis()")
  3786. if self.toggle_axis is False:
  3787. if self.is_legacy is False:
  3788. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3789. parent=self.plotcanvas.view.scene)
  3790. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3791. parent=self.plotcanvas.view.scene)
  3792. else:
  3793. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3794. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3795. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3796. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3797. self.plotcanvas.canvas.draw()
  3798. self.toggle_axis = True
  3799. else:
  3800. if self.is_legacy is False:
  3801. self.plotcanvas.v_line.parent = None
  3802. self.plotcanvas.h_line.parent = None
  3803. else:
  3804. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3805. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3806. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3807. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3808. self.plotcanvas.canvas.draw()
  3809. self.toggle_axis = False
  3810. def on_toggle_grid(self):
  3811. self.defaults.report_usage("on_toggle_grid()")
  3812. self.ui.grid_snap_btn.trigger()
  3813. self.ui.on_grid_snap_triggered(state=True)
  3814. def on_toggle_grid_lines(self):
  3815. self.defaults.report_usage("on_toggle_grd_lines()")
  3816. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3817. if tt_settings.contains("theme"):
  3818. theme = tt_settings.value('theme', type=str)
  3819. else:
  3820. theme = 'white'
  3821. if self.toggle_grid_lines is False:
  3822. if self.is_legacy is False:
  3823. if theme == 'white':
  3824. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3825. else:
  3826. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3827. else:
  3828. self.plotcanvas.axes.grid(True)
  3829. try:
  3830. self.plotcanvas.canvas.draw()
  3831. except IndexError:
  3832. pass
  3833. pass
  3834. self.toggle_grid_lines = True
  3835. else:
  3836. if self.is_legacy is False:
  3837. if theme == 'white':
  3838. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3839. else:
  3840. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3841. else:
  3842. self.plotcanvas.axes.grid(False)
  3843. try:
  3844. self.plotcanvas.canvas.draw()
  3845. except IndexError:
  3846. pass
  3847. self.toggle_grid_lines = False
  3848. if self.is_legacy is False:
  3849. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3850. # - perhaps is a bug in VisPy implementation
  3851. if self.grid_status() is True:
  3852. self.app_cursor.enabled = False
  3853. self.app_cursor.enabled = True
  3854. else:
  3855. self.app_cursor.enabled = True
  3856. self.app_cursor.enabled = False
  3857. def on_update_exc_export(self, state):
  3858. """
  3859. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3860. if the update_excellon_cb checkbox is checked
  3861. :param state: state of the checkbox whose signals is tied to his slot
  3862. :return:
  3863. """
  3864. if state:
  3865. # first try to disconnect
  3866. try:
  3867. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3868. disconnect(self.on_excellon_format_changed)
  3869. except TypeError:
  3870. pass
  3871. try:
  3872. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3873. disconnect(self.on_excellon_format_changed)
  3874. except TypeError:
  3875. pass
  3876. try:
  3877. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3878. disconnect(self.on_excellon_format_changed)
  3879. except TypeError:
  3880. pass
  3881. try:
  3882. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3883. disconnect(self.on_excellon_format_changed)
  3884. except TypeError:
  3885. pass
  3886. try:
  3887. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3888. disconnect(self.on_excellon_zeros_changed)
  3889. except TypeError:
  3890. pass
  3891. try:
  3892. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3893. disconnect(self.on_excellon_zeros_changed)
  3894. except TypeError:
  3895. pass
  3896. # the connect them
  3897. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3898. self.on_excellon_format_changed)
  3899. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3900. self.on_excellon_format_changed)
  3901. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3902. self.on_excellon_format_changed)
  3903. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3904. self.on_excellon_format_changed)
  3905. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3906. self.on_excellon_zeros_changed)
  3907. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3908. self.on_excellon_units_changed)
  3909. else:
  3910. # disconnect the signals
  3911. try:
  3912. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3913. disconnect(self.on_excellon_format_changed)
  3914. except TypeError:
  3915. pass
  3916. try:
  3917. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3918. disconnect(self.on_excellon_format_changed)
  3919. except TypeError:
  3920. pass
  3921. try:
  3922. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3923. disconnect(self.on_excellon_format_changed)
  3924. except TypeError:
  3925. pass
  3926. try:
  3927. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3928. disconnect(self.on_excellon_format_changed)
  3929. except TypeError:
  3930. pass
  3931. try:
  3932. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3933. disconnect(self.on_excellon_zeros_changed)
  3934. except TypeError:
  3935. pass
  3936. try:
  3937. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3938. disconnect(self.on_excellon_zeros_changed)
  3939. except TypeError:
  3940. pass
  3941. def on_excellon_format_changed(self):
  3942. """
  3943. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3944. :return: None
  3945. """
  3946. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3947. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3948. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3949. )
  3950. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3951. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3952. )
  3953. else:
  3954. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3955. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3956. )
  3957. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3958. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3959. )
  3960. def on_excellon_zeros_changed(self):
  3961. """
  3962. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3963. :return: None
  3964. """
  3965. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3966. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3967. )
  3968. def on_excellon_units_changed(self):
  3969. """
  3970. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3971. :return: None
  3972. """
  3973. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3974. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3975. )
  3976. self.on_excellon_format_changed()
  3977. def on_film_color_entry(self):
  3978. self.defaults['tools_film_color'] = \
  3979. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3980. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3981. "background-color:%s;"
  3982. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3983. )
  3984. def on_film_color_button(self):
  3985. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3986. c_dialog = QtWidgets.QColorDialog()
  3987. film_color = c_dialog.getColor(initial=current_color)
  3988. if film_color.isValid() is False:
  3989. return
  3990. # if new color is different then mark that the Preferences are changed
  3991. if film_color != current_color:
  3992. self.preferencesUiManager.on_preferences_edited()
  3993. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3994. "background-color:%s;"
  3995. "border-color: dimgray" % str(film_color.name())
  3996. )
  3997. new_val_sel = str(film_color.name())
  3998. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3999. self.defaults['tools_film_color'] = new_val_sel
  4000. def on_qrcode_fill_color_entry(self):
  4001. self.defaults['tools_qrcode_fill_color'] = \
  4002. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  4003. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4004. "background-color:%s;"
  4005. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  4006. )
  4007. def on_qrcode_fill_color_button(self):
  4008. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  4009. c_dialog = QtWidgets.QColorDialog()
  4010. fill_color = c_dialog.getColor(initial=current_color)
  4011. if fill_color.isValid() is False:
  4012. return
  4013. # if new color is different then mark that the Preferences are changed
  4014. if fill_color != current_color:
  4015. self.preferencesUiManager.on_preferences_edited()
  4016. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  4017. "background-color:%s;"
  4018. "border-color: dimgray" % str(fill_color.name())
  4019. )
  4020. new_val_sel = str(fill_color.name())
  4021. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  4022. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  4023. def on_qrcode_back_color_entry(self):
  4024. self.defaults['tools_qrcode_back_color'] = \
  4025. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  4026. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4027. "background-color:%s;"
  4028. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  4029. )
  4030. def on_qrcode_back_color_button(self):
  4031. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  4032. c_dialog = QtWidgets.QColorDialog()
  4033. back_color = c_dialog.getColor(initial=current_color)
  4034. if back_color.isValid() is False:
  4035. return
  4036. # if new color is different then mark that the Preferences are changed
  4037. if back_color != current_color:
  4038. self.preferencesUiManager.on_preferences_edited()
  4039. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4040. "background-color:%s;"
  4041. "border-color: dimgray" % str(back_color.name())
  4042. )
  4043. new_val_sel = str(back_color.name())
  4044. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  4045. self.defaults['tools_qrcode_back_color'] = new_val_sel
  4046. def on_tab_rmb_click(self, checked):
  4047. self.ui.notebook.set_detachable(val=checked)
  4048. self.defaults["global_tabs_detachable"] = checked
  4049. self.ui.plot_tab_area.set_detachable(val=checked)
  4050. self.defaults["global_tabs_detachable"] = checked
  4051. def on_tab_setup_context_menu(self):
  4052. initial_checked = self.defaults["global_tabs_detachable"]
  4053. action_name = str(_("Detachable Tabs"))
  4054. action = QtWidgets.QAction(self)
  4055. action.setCheckable(True)
  4056. action.setText(action_name)
  4057. action.setChecked(initial_checked)
  4058. self.ui.notebook.tabBar.addAction(action)
  4059. self.ui.plot_tab_area.tabBar.addAction(action)
  4060. try:
  4061. action.triggered.disconnect()
  4062. except TypeError:
  4063. pass
  4064. action.triggered.connect(self.on_tab_rmb_click)
  4065. def on_deselect_all(self):
  4066. self.collection.set_all_inactive()
  4067. self.delete_selection_shape()
  4068. def on_workspace_modified(self):
  4069. # self.save_defaults(silent=True)
  4070. if self.is_legacy is True:
  4071. self.plotcanvas.delete_workspace()
  4072. self.preferencesUiManager.defaults_read_form()
  4073. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4074. def on_workspace(self):
  4075. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4076. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4077. else:
  4078. self.plotcanvas.delete_workspace()
  4079. self.preferencesUiManager.defaults_read_form()
  4080. # self.save_defaults(silent=True)
  4081. def on_workspace_toggle(self):
  4082. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4083. try:
  4084. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4085. except TypeError:
  4086. pass
  4087. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4088. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4089. self.on_workspace()
  4090. def on_cursor_type(self, val):
  4091. """
  4092. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4093. :return: None
  4094. """
  4095. self.app_cursor.enabled = False
  4096. if val == 'small':
  4097. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4098. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4099. self.app_cursor = self.plotcanvas.new_cursor()
  4100. else:
  4101. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4102. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4103. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4104. if self.ui.grid_snap_btn.isChecked():
  4105. self.app_cursor.enabled = True
  4106. else:
  4107. self.app_cursor.enabled = False
  4108. def on_tool_add_keypress(self):
  4109. # ## Current application units in Upper Case
  4110. self.units = self.defaults['units'].upper()
  4111. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4112. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4113. if notebook_widget_name == 'selected_tab':
  4114. if self.collection.get_active().kind == 'geometry':
  4115. # Tool add works for Geometry only if Advanced is True in Preferences
  4116. if self.defaults["global_app_level"] == 'a':
  4117. tool_add_popup = FCInputDialog(title="New Tool ...",
  4118. text='Enter a Tool Diameter:',
  4119. min=0.0000, max=99.9999, decimals=4)
  4120. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4121. val, ok = tool_add_popup.get_value()
  4122. if ok:
  4123. if float(val) == 0:
  4124. self.inform.emit('[WARNING_NOTCL] %s' %
  4125. _("Please enter a tool diameter with non-zero value, in Float format."))
  4126. return
  4127. self.collection.get_active().on_tool_add(dia=float(val))
  4128. else:
  4129. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4130. else:
  4131. msgbox = QtWidgets.QMessageBox()
  4132. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4133. "Go to Preferences -> General - Show Advanced Options."))
  4134. msgbox.setWindowTitle("Tool adding ...")
  4135. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4136. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4137. msgbox.setDefaultButton(bt_ok)
  4138. msgbox.exec_()
  4139. # work only if the notebook tab on focus is the Tools_Tab
  4140. if notebook_widget_name == 'tool_tab':
  4141. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4142. # and only if the tool is NCC Tool
  4143. if tool_widget == self.ncclear_tool.toolName:
  4144. self.ncclear_tool.on_add_tool_by_key()
  4145. # and only if the tool is Paint Area Tool
  4146. elif tool_widget == self.paint_tool.toolName:
  4147. self.paint_tool.on_add_tool_by_key()
  4148. # and only if the tool is Solder Paste Dispensing Tool
  4149. elif tool_widget == self.paste_tool.toolName:
  4150. self.paste_tool.on_add_tool_by_key()
  4151. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4152. # See description below.
  4153. def on_delete_keypress(self):
  4154. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4155. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4156. if notebook_widget_name == 'selected_tab':
  4157. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4158. self.collection.get_active().on_tool_delete()
  4159. # work only if the notebook tab on focus is the Tools_Tab
  4160. elif notebook_widget_name == 'tool_tab':
  4161. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4162. # and only if the tool is NCC Tool
  4163. if tool_widget == self.ncclear_tool.toolName:
  4164. self.ncclear_tool.on_tool_delete()
  4165. # and only if the tool is Paint Tool
  4166. elif tool_widget == self.paint_tool.toolName:
  4167. self.paint_tool.on_tool_delete()
  4168. # and only if the tool is Solder Paste Dispensing Tool
  4169. elif tool_widget == self.paste_tool.toolName:
  4170. self.paste_tool.on_tool_delete()
  4171. else:
  4172. self.on_delete()
  4173. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4174. # some screens you have to be careful where you hover with your mouse.
  4175. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4176. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4177. # Complicated, I know :)
  4178. def on_delete(self, force_deletion=False):
  4179. """
  4180. Delete the currently selected FlatCAMObjs.
  4181. :param force_deletion: used by Tcl command
  4182. :return: None
  4183. """
  4184. self.defaults.report_usage("on_delete()")
  4185. response = None
  4186. bt_ok = None
  4187. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4188. # a geometry object before we update it.
  4189. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4190. and self.grb_editor.editor_active is False:
  4191. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4192. msgbox = QtWidgets.QMessageBox()
  4193. msgbox.setWindowTitle(_("Delete objects"))
  4194. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4195. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4196. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4197. "the selected objects?"))
  4198. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4199. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4200. msgbox.setDefaultButton(bt_ok)
  4201. msgbox.exec_()
  4202. response = msgbox.clickedButton()
  4203. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4204. response = bt_ok
  4205. if response == bt_ok:
  4206. if self.collection.get_active():
  4207. self.log.debug("App.on_delete()")
  4208. for obj_active in self.collection.get_selected():
  4209. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4210. if obj_active.kind == 'gerber':
  4211. for el in obj_active.mark_shapes:
  4212. obj_active.mark_shapes[el].clear(update=True)
  4213. obj_active.mark_shapes[el].enabled = False
  4214. # obj_active.mark_shapes[el] = None
  4215. del el
  4216. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4217. if obj_active.kind == 'geometry':
  4218. obj_active.exclusion_shapes.clear(update=True)
  4219. obj_active.exclusion_shapes.enabled = False
  4220. del obj_active.exclusion_shapes
  4221. elif isinstance(obj_active, CNCJobObject):
  4222. try:
  4223. obj_active.text_col.enabled = False
  4224. del obj_active.text_col
  4225. obj_active.annotation.clear(update=True)
  4226. del obj_active.annotation
  4227. except AttributeError as e:
  4228. log.debug(
  4229. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4230. )
  4231. while self.collection.get_selected():
  4232. self.delete_first_selected()
  4233. self.inform.emit('%s...' % _("Object(s) deleted"))
  4234. # make sure that the selection shape is deleted, too
  4235. self.delete_selection_shape()
  4236. else:
  4237. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4238. else:
  4239. self.inform.emit(_("Save the work in Editor and try again ..."))
  4240. def delete_first_selected(self):
  4241. # Keep this for later
  4242. try:
  4243. sel_obj = self.collection.get_active()
  4244. name = sel_obj.options["name"]
  4245. isPlotted = sel_obj.options["plot"]
  4246. except AttributeError:
  4247. self.log.debug("Nothing selected for deletion")
  4248. return
  4249. if self.is_legacy is True:
  4250. # Remove plot only if the object was plotted otherwise delaxes will fail
  4251. if isPlotted:
  4252. try:
  4253. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4254. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4255. except Exception as e:
  4256. log.debug("App.delete_first_selected() --> %s" % str(e))
  4257. self.plotcanvas.auto_adjust_axes()
  4258. # Remove from dictionary
  4259. self.collection.delete_active()
  4260. # Clear form
  4261. self.setup_component_editor()
  4262. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4263. def on_set_origin(self):
  4264. """
  4265. Set the origin to the left mouse click position
  4266. :return: None
  4267. """
  4268. # display the message for the user
  4269. # and ask him to click on the desired position
  4270. self.defaults.report_usage("on_set_origin()")
  4271. def origin_replot():
  4272. def worker_task():
  4273. with self.proc_container.new('%s...' % _("Plotting")):
  4274. for obj in self.collection.get_list():
  4275. obj.plot()
  4276. self.plotcanvas.fit_view()
  4277. if self.is_legacy:
  4278. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4279. else:
  4280. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4281. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4282. self.inform.emit(_('Click to set the origin ...'))
  4283. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4284. # first disconnect it as it may have been used by something else
  4285. try:
  4286. self.replot_signal.disconnect()
  4287. except TypeError:
  4288. pass
  4289. self.replot_signal[list].connect(origin_replot)
  4290. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4291. """
  4292. :param event:
  4293. :param location:
  4294. :param noplot:
  4295. :param use_thread:
  4296. :return:
  4297. """
  4298. noplot_sig = noplot
  4299. def worker_task():
  4300. with self.proc_container.new(_("Setting Origin...")):
  4301. obj_list = self.collection.get_list()
  4302. for obj in obj_list:
  4303. obj.offset((x, y))
  4304. self.object_changed.emit(obj)
  4305. # Update the object bounding box options
  4306. a, b, c, d = obj.bounds()
  4307. obj.options['xmin'] = a
  4308. obj.options['ymin'] = b
  4309. obj.options['xmax'] = c
  4310. obj.options['ymax'] = d
  4311. self.inform.emit('[success] %s...' % _('Origin set'))
  4312. for obj in obj_list:
  4313. out_name = obj.options["name"]
  4314. if obj.kind == 'gerber':
  4315. obj.source_file = self.export_gerber(
  4316. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4317. elif obj.kind == 'excellon':
  4318. obj.source_file = self.export_excellon(
  4319. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4320. if noplot_sig is False:
  4321. self.replot_signal.emit([])
  4322. if location is not None:
  4323. if len(location) != 2:
  4324. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4325. return 'fail'
  4326. x, y = location
  4327. if use_thread is True:
  4328. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4329. else:
  4330. worker_task()
  4331. self.should_we_save = True
  4332. return
  4333. if event.button == 1:
  4334. if self.is_legacy is False:
  4335. event_pos = event.pos
  4336. else:
  4337. event_pos = (event.xdata, event.ydata)
  4338. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4339. if self.grid_status():
  4340. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4341. else:
  4342. pos = pos_canvas
  4343. x = 0 - pos[0]
  4344. y = 0 - pos[1]
  4345. if use_thread is True:
  4346. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4347. else:
  4348. worker_task()
  4349. self.should_we_save = True
  4350. def on_move2origin(self, use_thread=True):
  4351. """
  4352. Move selected objects to origin.
  4353. :param use_thread: Control if to use threaded operation. Boolean.
  4354. :return:
  4355. """
  4356. def worker_task():
  4357. with self.proc_container.new(_("Moving to Origin...")):
  4358. obj_list = self.collection.get_selected()
  4359. if not obj_list:
  4360. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4361. return
  4362. xminlist = []
  4363. yminlist = []
  4364. # first get a bounding box to fit all
  4365. for obj in obj_list:
  4366. xmin, ymin, xmax, ymax = obj.bounds()
  4367. xminlist.append(xmin)
  4368. yminlist.append(ymin)
  4369. # get the minimum x,y for all objects selected
  4370. x = min(xminlist)
  4371. y = min(yminlist)
  4372. for obj in obj_list:
  4373. obj.offset((-x, -y))
  4374. self.object_changed.emit(obj)
  4375. # Update the object bounding box options
  4376. a, b, c, d = obj.bounds()
  4377. obj.options['xmin'] = a
  4378. obj.options['ymin'] = b
  4379. obj.options['xmax'] = c
  4380. obj.options['ymax'] = d
  4381. for obj in obj_list:
  4382. obj.plot()
  4383. for obj in obj_list:
  4384. out_name = obj.options["name"]
  4385. if obj.kind == 'gerber':
  4386. obj.source_file = self.export_gerber(
  4387. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4388. elif obj.kind == 'excellon':
  4389. obj.source_file = self.export_excellon(
  4390. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4391. self.inform.emit('[success] %s...' % _('Origin set'))
  4392. if use_thread is True:
  4393. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4394. else:
  4395. worker_task()
  4396. self.should_we_save = True
  4397. def on_jump_to(self, custom_location=None, fit_center=True):
  4398. """
  4399. Jump to a location by setting the mouse cursor location.
  4400. :param custom_location: Jump to a specified point. (x, y) tuple.
  4401. :param fit_center: If to fit view. Boolean.
  4402. :return:
  4403. """
  4404. self.defaults.report_usage("on_jump_to()")
  4405. if not custom_location:
  4406. dia_box_location = None
  4407. try:
  4408. dia_box_location = eval(self.clipboard.text())
  4409. except Exception:
  4410. pass
  4411. if type(dia_box_location) == tuple:
  4412. dia_box_location = str(dia_box_location)
  4413. else:
  4414. dia_box_location = None
  4415. # dia_box = Dialog_box(title=_("Jump to ..."),
  4416. # label=_("Enter the coordinates in format X,Y:"),
  4417. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4418. # initial_text=dia_box_location)
  4419. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4420. label=_("Enter the coordinates in format X,Y:"),
  4421. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4422. initial_text=dia_box_location,
  4423. reference=self.defaults['global_jump_ref'])
  4424. if dia_box.ok is True:
  4425. try:
  4426. location = eval(dia_box.location)
  4427. if not isinstance(location, tuple):
  4428. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4429. return
  4430. if dia_box.reference == 'rel':
  4431. rel_x = self.mouse[0] + location[0]
  4432. rel_y = self.mouse[1] + location[1]
  4433. location = (rel_x, rel_y)
  4434. self.defaults['global_jump_ref'] = dia_box.reference
  4435. except Exception:
  4436. return
  4437. else:
  4438. return
  4439. else:
  4440. location = custom_location
  4441. self.jump_signal.emit(location)
  4442. if fit_center:
  4443. self.plotcanvas.fit_center(loc=location)
  4444. cursor = QtGui.QCursor()
  4445. if self.is_legacy is False:
  4446. # I don't know where those differences come from but they are constant for the current
  4447. # execution of the application and they are multiples of a value around 0.0263mm.
  4448. # In a random way sometimes they are more sometimes they are less
  4449. # if units == 'MM':
  4450. # cal_factor = 0.0263
  4451. # else:
  4452. # cal_factor = 0.0263 / 25.4
  4453. cal_location = (location[0], location[1])
  4454. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4455. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4456. j_pos = (
  4457. int(canvas_origin.x() + round(jump_loc[0])),
  4458. int(canvas_origin.y() + round(jump_loc[1]))
  4459. )
  4460. cursor.setPos(j_pos[0], j_pos[1])
  4461. else:
  4462. # find the canvas origin which is in the top left corner
  4463. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4464. # determine the coordinates for the lowest left point of the canvas
  4465. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4466. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4467. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4468. # canvas) and the point (width, height) is in the top-right location
  4469. loc = self.plotcanvas.axes.transData.transform_point(location)
  4470. j_pos = (
  4471. int(x0 + loc[0]),
  4472. int(y0 - loc[1])
  4473. )
  4474. cursor.setPos(j_pos[0], j_pos[1])
  4475. self.plotcanvas.mouse = [location[0], location[1]]
  4476. if self.defaults["global_cursor_color_enabled"] is True:
  4477. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4478. else:
  4479. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4480. if self.grid_status():
  4481. # Update cursor
  4482. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4483. symbol='++', edge_color=self.cursor_color_3D,
  4484. edge_width=self.defaults["global_cursor_width"],
  4485. size=self.defaults["global_cursor_size"])
  4486. # Set the position label
  4487. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4488. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4489. # Set the relative position label
  4490. dx = location[0] - float(self.rel_point1[0])
  4491. dy = location[1] - float(self.rel_point1[1])
  4492. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4493. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4494. self.inform.emit('[success] %s' % _("Done."))
  4495. return location
  4496. def on_locate(self, obj, fit_center=True):
  4497. """
  4498. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4499. :param obj: The object on which to locate certain points
  4500. :param fit_center: If to fit view. Boolean.
  4501. :return: A point location. (x, y) tuple.
  4502. """
  4503. self.defaults.report_usage("on_locate()")
  4504. if obj is None:
  4505. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4506. return 'fail'
  4507. class DialogBoxChoice(QtWidgets.QDialog):
  4508. def __init__(self, title=None, icon=None, choice='bl'):
  4509. """
  4510. :param title: string with the window title
  4511. """
  4512. super(DialogBoxChoice, self).__init__()
  4513. self.ok = False
  4514. self.setWindowIcon(icon)
  4515. self.setWindowTitle(str(title))
  4516. self.form = QtWidgets.QFormLayout(self)
  4517. self.ref_radio = RadioSet([
  4518. {"label": _("Bottom-Left"), "value": "bl"},
  4519. {"label": _("Top-Left"), "value": "tl"},
  4520. {"label": _("Bottom-Right"), "value": "br"},
  4521. {"label": _("Top-Right"), "value": "tr"},
  4522. {"label": _("Center"), "value": "c"}
  4523. ], orientation='vertical', stretch=False)
  4524. self.ref_radio.set_value(choice)
  4525. self.form.addRow(self.ref_radio)
  4526. self.button_box = QtWidgets.QDialogButtonBox(
  4527. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4528. Qt.Horizontal, parent=self)
  4529. self.form.addRow(self.button_box)
  4530. self.button_box.accepted.connect(self.accept)
  4531. self.button_box.rejected.connect(self.reject)
  4532. if self.exec_() == QtWidgets.QDialog.Accepted:
  4533. self.ok = True
  4534. self.location_point = self.ref_radio.get_value()
  4535. else:
  4536. self.ok = False
  4537. self.location_point = None
  4538. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4539. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4540. choice=self.defaults['global_locate_pt'])
  4541. if dia_box.ok is True:
  4542. try:
  4543. location_point = dia_box.location_point
  4544. self.defaults['global_locate_pt'] = dia_box.location_point
  4545. except Exception:
  4546. return
  4547. else:
  4548. return
  4549. loc_b = obj.bounds()
  4550. if location_point == 'bl':
  4551. location = (loc_b[0], loc_b[1])
  4552. elif location_point == 'tl':
  4553. location = (loc_b[0], loc_b[3])
  4554. elif location_point == 'br':
  4555. location = (loc_b[2], loc_b[1])
  4556. elif location_point == 'tr':
  4557. location = (loc_b[2], loc_b[3])
  4558. else:
  4559. # center
  4560. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4561. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4562. location = (cx, cy)
  4563. self.locate_signal.emit(location, location_point)
  4564. if fit_center:
  4565. self.plotcanvas.fit_center(loc=location)
  4566. cursor = QtGui.QCursor()
  4567. if self.is_legacy is False:
  4568. # I don't know where those differences come from but they are constant for the current
  4569. # execution of the application and they are multiples of a value around 0.0263mm.
  4570. # In a random way sometimes they are more sometimes they are less
  4571. # if units == 'MM':
  4572. # cal_factor = 0.0263
  4573. # else:
  4574. # cal_factor = 0.0263 / 25.4
  4575. cal_location = (location[0], location[1])
  4576. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4577. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4578. j_pos = (
  4579. int(canvas_origin.x() + round(jump_loc[0])),
  4580. int(canvas_origin.y() + round(jump_loc[1]))
  4581. )
  4582. cursor.setPos(j_pos[0], j_pos[1])
  4583. else:
  4584. # find the canvas origin which is in the top left corner
  4585. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4586. # determine the coordinates for the lowest left point of the canvas
  4587. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4588. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4589. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4590. # canvas) and the point (width, height) is in the top-right location
  4591. loc = self.plotcanvas.axes.transData.transform_point(location)
  4592. j_pos = (
  4593. int(x0 + loc[0]),
  4594. int(y0 - loc[1])
  4595. )
  4596. cursor.setPos(j_pos[0], j_pos[1])
  4597. self.plotcanvas.mouse = [location[0], location[1]]
  4598. if self.defaults["global_cursor_color_enabled"] is True:
  4599. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4600. else:
  4601. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4602. if self.grid_status():
  4603. # Update cursor
  4604. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4605. symbol='++', edge_color=self.cursor_color_3D,
  4606. edge_width=self.defaults["global_cursor_width"],
  4607. size=self.defaults["global_cursor_size"])
  4608. # Set the position label
  4609. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4610. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4611. # Set the relative position label
  4612. self.dx = location[0] - float(self.rel_point1[0])
  4613. self.dy = location[1] - float(self.rel_point1[1])
  4614. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4615. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4616. self.inform.emit('[success] %s' % _("Done."))
  4617. return location
  4618. def on_copy_command(self):
  4619. """
  4620. Will copy a selection of objects, creating new objects.
  4621. :return:
  4622. """
  4623. self.defaults.report_usage("on_copy_command()")
  4624. def initialize(obj_init, app):
  4625. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4626. try:
  4627. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4628. except AttributeError:
  4629. pass
  4630. try:
  4631. obj_init.apertures = deepcopy(obj.apertures)
  4632. except AttributeError:
  4633. pass
  4634. try:
  4635. if obj.tools:
  4636. obj_init.tools = deepcopy(obj.tools)
  4637. except Exception as err:
  4638. log.debug("App.on_copy_command() --> %s" % str(err))
  4639. try:
  4640. obj_init.source_file = deepcopy(obj.source_file)
  4641. except (AttributeError, TypeError):
  4642. pass
  4643. def initialize_excellon(obj_init, app):
  4644. obj_init.source_file = deepcopy(obj.source_file)
  4645. obj_init.tools = deepcopy(obj.tools)
  4646. # drills are offset, so they need to be deep copied
  4647. obj_init.drills = deepcopy(obj.drills)
  4648. # slots are offset, so they need to be deep copied
  4649. obj_init.slots = deepcopy(obj.slots)
  4650. obj_init.create_geometry()
  4651. def initialize_script(obj_init, app_obj):
  4652. obj_init.source_file = deepcopy(obj.source_file)
  4653. def initialize_document(obj_init, app_obj):
  4654. obj_init.source_file = deepcopy(obj.source_file)
  4655. for obj in self.collection.get_selected():
  4656. obj_name = obj.options["name"]
  4657. try:
  4658. if isinstance(obj, ExcellonObject):
  4659. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4660. elif isinstance(obj, GerberObject):
  4661. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4662. elif isinstance(obj, GeometryObject):
  4663. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4664. elif isinstance(obj, ScriptObject):
  4665. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4666. elif isinstance(obj, DocumentObject):
  4667. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4668. except Exception as e:
  4669. return "Operation failed: %s" % str(e)
  4670. def on_copy_object2(self, custom_name):
  4671. def initialize_geometry(obj_init, app):
  4672. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4673. try:
  4674. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4675. except AttributeError:
  4676. pass
  4677. try:
  4678. obj_init.apertures = deepcopy(obj.apertures)
  4679. except AttributeError:
  4680. pass
  4681. try:
  4682. if obj.tools:
  4683. obj_init.tools = deepcopy(obj.tools)
  4684. except Exception as ee:
  4685. log.debug("on_copy_object2() --> %s" % str(ee))
  4686. def initialize_gerber(obj_init, app):
  4687. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4688. obj_init.apertures = deepcopy(obj.apertures)
  4689. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4690. def initialize_excellon(obj_init, app):
  4691. obj_init.tools = deepcopy(obj.tools)
  4692. # drills are offset, so they need to be deep copied
  4693. obj_init.drills = deepcopy(obj.drills)
  4694. # slots are offset, so they need to be deep copied
  4695. obj_init.slots = deepcopy(obj.slots)
  4696. obj_init.create_geometry()
  4697. for obj in self.collection.get_selected():
  4698. obj_name = obj.options["name"]
  4699. try:
  4700. if isinstance(obj, ExcellonObject):
  4701. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4702. elif isinstance(obj, GerberObject):
  4703. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4704. elif isinstance(obj, GeometryObject):
  4705. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4706. except Exception as er:
  4707. return "Operation failed: %s" % str(er)
  4708. def on_rename_object(self, text):
  4709. """
  4710. Will rename an object.
  4711. :param text: New name for the object.
  4712. :return:
  4713. """
  4714. self.defaults.report_usage("on_rename_object()")
  4715. named_obj = self.collection.get_active()
  4716. for obj in named_obj:
  4717. if obj is list:
  4718. self.on_rename_object(text)
  4719. else:
  4720. try:
  4721. obj.options['name'] = text
  4722. except Exception as e:
  4723. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4724. def convert_any2geo(self):
  4725. """
  4726. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4727. :return:
  4728. """
  4729. self.defaults.report_usage("convert_any2geo()")
  4730. def initialize(obj_init, app):
  4731. obj_init.solid_geometry = obj.solid_geometry
  4732. try:
  4733. obj_init.follow_geometry = obj.follow_geometry
  4734. except AttributeError:
  4735. pass
  4736. try:
  4737. obj_init.apertures = obj.apertures
  4738. except AttributeError:
  4739. pass
  4740. try:
  4741. if obj.tools:
  4742. obj_init.tools = obj.tools
  4743. except AttributeError:
  4744. pass
  4745. def initialize_excellon(obj_init, app):
  4746. # objs = self.collection.get_selected()
  4747. # GeometryObject.merge(objs, obj)
  4748. solid_geo = []
  4749. for tool in obj.tools:
  4750. for geo in obj.tools[tool]['solid_geometry']:
  4751. solid_geo.append(geo)
  4752. obj_init.solid_geometry = deepcopy(solid_geo)
  4753. if not self.collection.get_selected():
  4754. log.warning("App.convert_any2geo --> No object selected")
  4755. self.inform.emit('[WARNING_NOTCL] %s' %
  4756. _("No object is selected. Select an object and try again."))
  4757. return
  4758. for obj in self.collection.get_selected():
  4759. obj_name = obj.options["name"]
  4760. try:
  4761. if isinstance(obj, ExcellonObject):
  4762. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4763. else:
  4764. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4765. except Exception as e:
  4766. return "Operation failed: %s" % str(e)
  4767. def convert_any2gerber(self):
  4768. """
  4769. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4770. :return:
  4771. """
  4772. self.defaults.report_usage("convert_any2gerber()")
  4773. def initialize_geometry(obj_init, app):
  4774. apertures = {}
  4775. apid = 0
  4776. apertures[str(apid)] = {}
  4777. apertures[str(apid)]['geometry'] = []
  4778. for obj_orig in obj.solid_geometry:
  4779. new_elem = {}
  4780. new_elem['solid'] = obj_orig
  4781. try:
  4782. new_elem['follow'] = obj_orig.exterior
  4783. except AttributeError:
  4784. pass
  4785. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4786. apertures[str(apid)]['size'] = 0.0
  4787. apertures[str(apid)]['type'] = 'C'
  4788. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4789. obj_init.apertures = deepcopy(apertures)
  4790. def initialize_excellon(obj_init, app):
  4791. apertures = {}
  4792. apid = 10
  4793. for tool in obj.tools:
  4794. apertures[str(apid)] = {}
  4795. apertures[str(apid)]['geometry'] = []
  4796. for geo in obj.tools[tool]['solid_geometry']:
  4797. new_el = {}
  4798. new_el['solid'] = geo
  4799. new_el['follow'] = geo.exterior
  4800. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4801. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4802. apertures[str(apid)]['type'] = 'C'
  4803. apid += 1
  4804. # create solid_geometry
  4805. solid_geometry = []
  4806. for apid in apertures:
  4807. for geo_el in apertures[apid]['geometry']:
  4808. solid_geometry.append(geo_el['solid'])
  4809. solid_geometry = MultiPolygon(solid_geometry)
  4810. solid_geometry = solid_geometry.buffer(0.0000001)
  4811. obj_init.solid_geometry = deepcopy(solid_geometry)
  4812. obj_init.apertures = deepcopy(apertures)
  4813. # clear the working objects (perhaps not necessary due of Python GC)
  4814. apertures.clear()
  4815. if not self.collection.get_selected():
  4816. log.warning("App.convert_any2gerber --> No object selected")
  4817. self.inform.emit('[WARNING_NOTCL] %s' %
  4818. _("No object is selected. Select an object and try again."))
  4819. return
  4820. for obj in self.collection.get_selected():
  4821. obj_name = obj.options["name"]
  4822. try:
  4823. if isinstance(obj, ExcellonObject):
  4824. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4825. elif isinstance(obj, GeometryObject):
  4826. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4827. else:
  4828. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4829. except Exception as e:
  4830. return "Operation failed: %s" % str(e)
  4831. def abort_all_tasks(self):
  4832. """
  4833. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4834. on the first possible occasion.
  4835. :return:
  4836. """
  4837. if self.abort_flag is False:
  4838. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4839. self.abort_flag = True
  4840. self.cleanup.emit()
  4841. def app_is_idle(self):
  4842. if self.abort_flag:
  4843. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4844. self.abort_flag = False
  4845. def on_selectall(self):
  4846. """
  4847. Will draw a selection box shape around the selected objects.
  4848. :return:
  4849. """
  4850. self.defaults.report_usage("on_selectall()")
  4851. # delete the possible selection box around a possible selected object
  4852. self.delete_selection_shape()
  4853. for name in self.collection.get_names():
  4854. self.collection.set_active(name)
  4855. curr_sel_obj = self.collection.get_by_name(name)
  4856. # create the selection box around the selected object
  4857. if self.defaults['global_selection_shape'] is True:
  4858. self.draw_selection_shape(curr_sel_obj)
  4859. def on_preferences(self):
  4860. """
  4861. Adds the Preferences in a Tab in Plot Area
  4862. :return:
  4863. """
  4864. # add the tab if it was closed
  4865. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4866. # delete the absolute and relative position and messages in the infobar
  4867. self.ui.position_label.setText("")
  4868. self.ui.rel_position_label.setText("")
  4869. # Switch plot_area to preferences page
  4870. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4871. # self.ui.show()
  4872. # detect changes in the preferences
  4873. for idx in range(self.ui.pref_tab_area.count()):
  4874. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4875. try:
  4876. try:
  4877. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4878. except (TypeError, AttributeError):
  4879. pass
  4880. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4881. except AttributeError:
  4882. pass
  4883. try:
  4884. try:
  4885. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4886. except (TypeError, AttributeError):
  4887. pass
  4888. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4889. except AttributeError:
  4890. pass
  4891. try:
  4892. try:
  4893. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4894. except (TypeError, AttributeError):
  4895. pass
  4896. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4897. except AttributeError:
  4898. pass
  4899. try:
  4900. try:
  4901. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4902. except (TypeError, AttributeError):
  4903. pass
  4904. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4905. except AttributeError:
  4906. pass
  4907. try:
  4908. try:
  4909. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4910. except (TypeError, AttributeError):
  4911. pass
  4912. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4913. except AttributeError:
  4914. pass
  4915. def on_tools_database(self, source='app'):
  4916. """
  4917. Adds the Tools Database in a Tab in Plot Area.
  4918. :return:
  4919. """
  4920. for idx in range(self.ui.plot_tab_area.count()):
  4921. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4922. # there can be only one instance of Tools Database at one time
  4923. return
  4924. if source == 'app':
  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.on_geometry_tool_add_from_db_executed
  4930. )
  4931. elif source == 'ncc':
  4932. self.tools_db_tab = ToolsDB2(
  4933. app=self,
  4934. parent=self.ui,
  4935. callback_on_edited=self.on_tools_db_edited,
  4936. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4937. )
  4938. elif source == 'paint':
  4939. self.tools_db_tab = ToolsDB2(
  4940. app=self,
  4941. parent=self.ui,
  4942. callback_on_edited=self.on_tools_db_edited,
  4943. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4944. )
  4945. # add the tab if it was closed
  4946. try:
  4947. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4948. self.tools_db_tab.setObjectName("database_tab")
  4949. except Exception as e:
  4950. log.debug("App.on_tools_database() --> %s" % str(e))
  4951. return
  4952. # delete the absolute and relative position and messages in the infobar
  4953. self.ui.position_label.setText("")
  4954. self.ui.rel_position_label.setText("")
  4955. # Switch plot_area to preferences page
  4956. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4957. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4958. self.tools_db_tab.ui_connect()
  4959. def on_tools_db_edited(self):
  4960. """
  4961. Executed whenever a tool is edited in Tools Database.
  4962. Will color the text of the Tools Database tab to Red color.
  4963. :return:
  4964. """
  4965. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4966. for idx in range(self.ui.plot_tab_area.count()):
  4967. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4968. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4969. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4970. self.tools_db_changed_flag = True
  4971. def on_geometry_tool_add_from_db_executed(self, tool):
  4972. """
  4973. Here add the tool from DB in the selected geometry object.
  4974. :return:
  4975. """
  4976. tool_from_db = deepcopy(tool)
  4977. obj = self.collection.get_active()
  4978. if isinstance(obj, GeometryObject):
  4979. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4980. # close the tab and delete it
  4981. for idx in range(self.ui.plot_tab_area.count()):
  4982. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4983. wdg = self.ui.plot_tab_area.widget(idx)
  4984. wdg.deleteLater()
  4985. self.ui.plot_tab_area.removeTab(idx)
  4986. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4987. else:
  4988. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4989. def on_plot_area_tab_closed(self, tab_obj_name):
  4990. """
  4991. Executed whenever a QTab is closed in the Plot Area.
  4992. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4993. :return:
  4994. """
  4995. if tab_obj_name == "preferences_tab":
  4996. self.preferencesUiManager.on_close_preferences_tab()
  4997. elif tab_obj_name == "database_tab":
  4998. # disconnect the signals from the table widget in tab
  4999. self.tools_db_tab.ui_disconnect()
  5000. if self.tools_db_changed_flag is True:
  5001. msgbox = QtWidgets.QMessageBox()
  5002. msgbox.setText(_("One or more Tools are edited.\n"
  5003. "Do you want to update the Tools Database?"))
  5004. msgbox.setWindowTitle(_("Save Tools Database"))
  5005. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5006. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5007. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5008. msgbox.setDefaultButton(bt_yes)
  5009. msgbox.exec_()
  5010. response = msgbox.clickedButton()
  5011. if response == bt_yes:
  5012. self.tools_db_tab.on_save_tools_db()
  5013. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  5014. else:
  5015. self.tools_db_changed_flag = False
  5016. self.inform.emit('')
  5017. return
  5018. self.tools_db_tab.deleteLater()
  5019. elif tab_obj_name == "text_editor_tab":
  5020. self.toggle_codeeditor = False
  5021. elif tab_obj_name == "bookmarks_tab":
  5022. self.book_dialog_tab.rebuild_actions()
  5023. self.book_dialog_tab.deleteLater()
  5024. else:
  5025. return
  5026. # def on_plotarea_tab_closed(self, tab_idx):
  5027. # """
  5028. #
  5029. # :param tab_idx: Index of the Tab from the plotarea that was closed
  5030. # :return:
  5031. # """
  5032. # widget = self.ui.plot_tab_area.widget(tab_idx)
  5033. #
  5034. # if widget is not None:
  5035. # widget.deleteLater()
  5036. # self.ui.plot_tab_area.removeTab(tab_idx)
  5037. def on_flipy(self):
  5038. """
  5039. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  5040. :return:
  5041. """
  5042. self.defaults.report_usage("on_flipy()")
  5043. obj_list = self.collection.get_selected()
  5044. xminlist = []
  5045. yminlist = []
  5046. xmaxlist = []
  5047. ymaxlist = []
  5048. if not obj_list:
  5049. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  5050. else:
  5051. try:
  5052. # first get a bounding box to fit all
  5053. for obj in obj_list:
  5054. xmin, ymin, xmax, ymax = obj.bounds()
  5055. xminlist.append(xmin)
  5056. yminlist.append(ymin)
  5057. xmaxlist.append(xmax)
  5058. ymaxlist.append(ymax)
  5059. # get the minimum x,y and maximum x,y for all objects selected
  5060. xminimal = min(xminlist)
  5061. yminimal = min(yminlist)
  5062. xmaximal = max(xmaxlist)
  5063. ymaximal = max(ymaxlist)
  5064. px = 0.5 * (xminimal + xmaximal)
  5065. py = 0.5 * (yminimal + ymaximal)
  5066. # execute mirroring
  5067. for obj in obj_list:
  5068. obj.mirror('X', [px, py])
  5069. obj.plot()
  5070. self.object_changed.emit(obj)
  5071. self.inform.emit('[success] %s' %
  5072. _("Flip on Y axis done."))
  5073. except Exception as e:
  5074. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5075. return
  5076. def on_flipx(self):
  5077. """
  5078. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5079. :return:
  5080. """
  5081. self.defaults.report_usage("on_flipx()")
  5082. obj_list = self.collection.get_selected()
  5083. xminlist = []
  5084. yminlist = []
  5085. xmaxlist = []
  5086. ymaxlist = []
  5087. if not obj_list:
  5088. self.inform.emit('[WARNING_NOTCL] %s' %
  5089. _("No object selected to Flip on X axis."))
  5090. else:
  5091. try:
  5092. # first get a bounding box to fit all
  5093. for obj in obj_list:
  5094. xmin, ymin, xmax, ymax = obj.bounds()
  5095. xminlist.append(xmin)
  5096. yminlist.append(ymin)
  5097. xmaxlist.append(xmax)
  5098. ymaxlist.append(ymax)
  5099. # get the minimum x,y and maximum x,y for all objects selected
  5100. xminimal = min(xminlist)
  5101. yminimal = min(yminlist)
  5102. xmaximal = max(xmaxlist)
  5103. ymaximal = max(ymaxlist)
  5104. px = 0.5 * (xminimal + xmaximal)
  5105. py = 0.5 * (yminimal + ymaximal)
  5106. # execute mirroring
  5107. for obj in obj_list:
  5108. obj.mirror('Y', [px, py])
  5109. obj.plot()
  5110. self.object_changed.emit(obj)
  5111. self.inform.emit('[success] %s' %
  5112. _("Flip on X axis done."))
  5113. except Exception as e:
  5114. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5115. return
  5116. def on_rotate(self, silent=False, preset=None):
  5117. """
  5118. Executed when Options -> Rotate Selection menu entry is clicked.
  5119. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5120. :param preset: A value to be used as predefined angle for rotation.
  5121. :return:
  5122. """
  5123. self.defaults.report_usage("on_rotate()")
  5124. obj_list = self.collection.get_selected()
  5125. xminlist = []
  5126. yminlist = []
  5127. xmaxlist = []
  5128. ymaxlist = []
  5129. if not obj_list:
  5130. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5131. else:
  5132. if silent is False:
  5133. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5134. min=-360, max=360, decimals=4,
  5135. init_val=float(self.defaults['tools_transform_rotate']))
  5136. num, ok = rotatebox.get_value()
  5137. else:
  5138. num = preset
  5139. ok = True
  5140. if ok:
  5141. try:
  5142. # first get a bounding box to fit all
  5143. for obj in obj_list:
  5144. xmin, ymin, xmax, ymax = obj.bounds()
  5145. xminlist.append(xmin)
  5146. yminlist.append(ymin)
  5147. xmaxlist.append(xmax)
  5148. ymaxlist.append(ymax)
  5149. # get the minimum x,y and maximum x,y for all objects selected
  5150. xminimal = min(xminlist)
  5151. yminimal = min(yminlist)
  5152. xmaximal = max(xmaxlist)
  5153. ymaximal = max(ymaxlist)
  5154. px = 0.5 * (xminimal + xmaximal)
  5155. py = 0.5 * (yminimal + ymaximal)
  5156. for sel_obj in obj_list:
  5157. sel_obj.rotate(-float(num), point=(px, py))
  5158. sel_obj.plot()
  5159. self.object_changed.emit(sel_obj)
  5160. self.inform.emit('[success] %s' %
  5161. _("Rotation done."))
  5162. except Exception as e:
  5163. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5164. return
  5165. def on_skewx(self):
  5166. """
  5167. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5168. :return:
  5169. """
  5170. self.defaults.report_usage("on_skewx()")
  5171. obj_list = self.collection.get_selected()
  5172. xminlist = []
  5173. yminlist = []
  5174. if not obj_list:
  5175. self.inform.emit('[WARNING_NOTCL] %s' %
  5176. _("No object selected to Skew/Shear on X axis."))
  5177. else:
  5178. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5179. min=-360, max=360, decimals=4,
  5180. init_val=float(self.defaults['tools_transform_skew_x']))
  5181. num, ok = skewxbox.get_value()
  5182. if ok:
  5183. # first get a bounding box to fit all
  5184. for obj in obj_list:
  5185. xmin, ymin, xmax, ymax = obj.bounds()
  5186. xminlist.append(xmin)
  5187. yminlist.append(ymin)
  5188. # get the minimum x,y and maximum x,y for all objects selected
  5189. xminimal = min(xminlist)
  5190. yminimal = min(yminlist)
  5191. for obj in obj_list:
  5192. obj.skew(num, 0, point=(xminimal, yminimal))
  5193. obj.plot()
  5194. self.object_changed.emit(obj)
  5195. self.inform.emit('[success] %s' %
  5196. _("Skew on X axis done."))
  5197. def on_skewy(self):
  5198. """
  5199. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5200. :return:
  5201. """
  5202. self.defaults.report_usage("on_skewy()")
  5203. obj_list = self.collection.get_selected()
  5204. xminlist = []
  5205. yminlist = []
  5206. if not obj_list:
  5207. self.inform.emit('[WARNING_NOTCL] %s' %
  5208. _("No object selected to Skew/Shear on Y axis."))
  5209. else:
  5210. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5211. min=-360, max=360, decimals=4,
  5212. init_val=float(self.defaults['tools_transform_skew_y']))
  5213. num, ok = skewybox.get_value()
  5214. if ok:
  5215. # first get a bounding box to fit all
  5216. for obj in obj_list:
  5217. xmin, ymin, xmax, ymax = obj.bounds()
  5218. xminlist.append(xmin)
  5219. yminlist.append(ymin)
  5220. # get the minimum x,y and maximum x,y for all objects selected
  5221. xminimal = min(xminlist)
  5222. yminimal = min(yminlist)
  5223. for obj in obj_list:
  5224. obj.skew(0, num, point=(xminimal, yminimal))
  5225. obj.plot()
  5226. self.object_changed.emit(obj)
  5227. self.inform.emit('[success] %s' %
  5228. _("Skew on Y axis done."))
  5229. def on_plots_updated(self):
  5230. """
  5231. Callback used to report when the plots have changed.
  5232. Adjust axes and zooms to fit.
  5233. :return: None
  5234. """
  5235. if self.is_legacy is False:
  5236. self.plotcanvas.update()
  5237. else:
  5238. self.plotcanvas.auto_adjust_axes()
  5239. self.on_zoom_fit(None)
  5240. self.collection.update_view()
  5241. # self.inform.emit(_("Plots updated ..."))
  5242. def on_toolbar_replot(self):
  5243. """
  5244. Callback for toolbar button. Re-plots all objects.
  5245. :return: None
  5246. """
  5247. self.defaults.report_usage("on_toolbar_replot")
  5248. self.log.debug("on_toolbar_replot()")
  5249. try:
  5250. self.collection.get_active().read_form()
  5251. except AttributeError:
  5252. self.log.debug("on_toolbar_replot(): AttributeError")
  5253. pass
  5254. self.plot_all()
  5255. def on_row_activated(self, index):
  5256. if index.isValid():
  5257. if index.internalPointer().parent_item != self.collection.root_item:
  5258. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5259. self.collection.on_item_activated(index)
  5260. def on_row_selected(self, obj_name):
  5261. """
  5262. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5263. It mean we clicked outside of the items and deselected all
  5264. :param obj_name:
  5265. :return:
  5266. """
  5267. if obj_name == 'none':
  5268. for act in self.ui.menuobjects.actions():
  5269. act.setChecked(False)
  5270. return
  5271. # get the name of the selected objects and add them to a list
  5272. name_list = []
  5273. for obj in self.collection.get_selected():
  5274. name_list.append(obj.options['name'])
  5275. # set all actions as unchecked but the ones selected make them checked
  5276. for act in self.ui.menuobjects.actions():
  5277. act.setChecked(False)
  5278. if act.text() in name_list:
  5279. act.setChecked(True)
  5280. def on_collection_updated(self, obj, state, old_name):
  5281. """
  5282. Create a menu from the object loaded in the collection.
  5283. :param obj: object that was changed (added, deleted, renamed)
  5284. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5285. :param old_name: the old name of the object before the action that triggered this slot happened
  5286. :return: None
  5287. """
  5288. icon_files = {
  5289. "gerber": self.resource_location + "/flatcam_icon16.png",
  5290. "excellon": self.resource_location + "/drill16.png",
  5291. "cncjob": self.resource_location + "/cnc16.png",
  5292. "geometry": self.resource_location + "/geometry16.png",
  5293. "script": self.resource_location + "/script_new16.png",
  5294. "document": self.resource_location + "/notes16_1.png"
  5295. }
  5296. if state == 'append':
  5297. for act in self.ui.menuobjects.actions():
  5298. try:
  5299. act.triggered.disconnect()
  5300. except TypeError:
  5301. pass
  5302. self.ui.menuobjects.clear()
  5303. gerber_list = []
  5304. exc_list = []
  5305. cncjob_list = []
  5306. geo_list = []
  5307. script_list = []
  5308. doc_list = []
  5309. for name in self.collection.get_names():
  5310. obj_named = self.collection.get_by_name(name)
  5311. if obj_named.kind == 'gerber':
  5312. gerber_list.append(name)
  5313. elif obj_named.kind == 'excellon':
  5314. exc_list.append(name)
  5315. elif obj_named.kind == 'cncjob':
  5316. cncjob_list.append(name)
  5317. elif obj_named.kind == 'geometry':
  5318. geo_list.append(name)
  5319. elif obj_named.kind == 'script':
  5320. script_list.append(name)
  5321. elif obj_named.kind == 'document':
  5322. doc_list.append(name)
  5323. def add_act(o_name):
  5324. obj_for_icon = self.collection.get_by_name(o_name)
  5325. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5326. add_action.setCheckable(True)
  5327. add_action.setText(o_name)
  5328. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5329. add_action.triggered.connect(
  5330. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5331. self.collection.set_inactive(o_name))
  5332. self.ui.menuobjects.addAction(add_action)
  5333. for name in gerber_list:
  5334. add_act(name)
  5335. self.ui.menuobjects.addSeparator()
  5336. for name in exc_list:
  5337. add_act(name)
  5338. self.ui.menuobjects.addSeparator()
  5339. for name in cncjob_list:
  5340. add_act(name)
  5341. self.ui.menuobjects.addSeparator()
  5342. for name in geo_list:
  5343. add_act(name)
  5344. self.ui.menuobjects.addSeparator()
  5345. for name in script_list:
  5346. add_act(name)
  5347. self.ui.menuobjects.addSeparator()
  5348. for name in doc_list:
  5349. add_act(name)
  5350. self.ui.menuobjects.addSeparator()
  5351. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5352. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5353. _('Select All')
  5354. )
  5355. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5356. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5357. _('Deselect All')
  5358. )
  5359. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5360. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5361. elif state == 'delete':
  5362. for act in self.ui.menuobjects.actions():
  5363. if act.text() == obj.options['name']:
  5364. try:
  5365. act.triggered.disconnect()
  5366. except TypeError:
  5367. pass
  5368. self.ui.menuobjects.removeAction(act)
  5369. break
  5370. elif state == 'rename':
  5371. for act in self.ui.menuobjects.actions():
  5372. if act.text() == old_name:
  5373. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5374. add_action.setText(obj.options['name'])
  5375. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5376. add_action.triggered.connect(
  5377. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5378. self.collection.set_inactive(obj.options['name']))
  5379. self.ui.menuobjects.insertAction(act, add_action)
  5380. try:
  5381. act.triggered.disconnect()
  5382. except TypeError:
  5383. pass
  5384. self.ui.menuobjects.removeAction(act)
  5385. break
  5386. elif state == 'delete_all':
  5387. for act in self.ui.menuobjects.actions():
  5388. try:
  5389. act.triggered.disconnect()
  5390. except TypeError:
  5391. pass
  5392. self.ui.menuobjects.clear()
  5393. self.ui.menuobjects.addSeparator()
  5394. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5395. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5396. _('Select All')
  5397. )
  5398. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5399. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5400. _('Deselect All')
  5401. )
  5402. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5403. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5404. def on_objects_selection(self, on_off):
  5405. obj_list = self.collection.get_names()
  5406. if on_off is True:
  5407. self.collection.set_all_active()
  5408. for act in self.ui.menuobjects.actions():
  5409. try:
  5410. act.setChecked(True)
  5411. except Exception:
  5412. pass
  5413. if obj_list:
  5414. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5415. else:
  5416. self.collection.set_all_inactive()
  5417. for act in self.ui.menuobjects.actions():
  5418. try:
  5419. act.setChecked(False)
  5420. except Exception:
  5421. pass
  5422. if obj_list:
  5423. self.inform.emit('%s' % _("Objects selection is cleared."))
  5424. else:
  5425. self.inform.emit('')
  5426. def grid_status(self):
  5427. if self.ui.grid_snap_btn.isChecked():
  5428. return True
  5429. else:
  5430. return False
  5431. def populate_cmenu_grids(self):
  5432. units = self.defaults['units'].lower()
  5433. # for act in self.ui.cmenu_gridmenu.actions():
  5434. # act.triggered.disconnect()
  5435. self.ui.cmenu_gridmenu.clear()
  5436. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5437. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5438. _("Grid On/Off"))
  5439. grid_toggle.setCheckable(True)
  5440. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5441. self.ui.cmenu_gridmenu.addSeparator()
  5442. for grid in sorted_list:
  5443. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5444. "%s" % str(grid))
  5445. action.triggered.connect(self.set_grid)
  5446. self.ui.cmenu_gridmenu.addSeparator()
  5447. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5448. _("Add"))
  5449. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5450. _("Delete"))
  5451. grid_add.triggered.connect(self.on_grid_add)
  5452. grid_delete.triggered.connect(self.on_grid_delete)
  5453. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5454. def set_grid(self):
  5455. menu_action = self.sender()
  5456. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5457. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5458. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5459. def on_grid_add(self):
  5460. # ## Current application units in lower Case
  5461. units = self.defaults['units'].lower()
  5462. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5463. text=_('Enter a Grid Value:'),
  5464. min=0.0000, max=99.9999, decimals=4)
  5465. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5466. val, ok = grid_add_popup.get_value()
  5467. if ok:
  5468. if float(val) == 0:
  5469. self.inform.emit('[WARNING_NOTCL] %s' %
  5470. _("Please enter a grid value with non-zero value, in Float format."))
  5471. return
  5472. else:
  5473. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5474. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5475. self.inform.emit('[success] %s...' %
  5476. _("New Grid added"))
  5477. else:
  5478. self.inform.emit('[WARNING_NOTCL] %s...' %
  5479. _("Grid already exists"))
  5480. else:
  5481. self.inform.emit('[WARNING_NOTCL] %s...' %
  5482. _("Adding New Grid cancelled"))
  5483. def on_grid_delete(self):
  5484. # ## Current application units in lower Case
  5485. units = self.defaults['units'].lower()
  5486. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5487. text='Enter a Grid Value:',
  5488. min=0.0000, max=99.9999, decimals=4)
  5489. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5490. val, ok = grid_del_popup.get_value()
  5491. if ok:
  5492. if float(val) == 0:
  5493. self.inform.emit('[WARNING_NOTCL] %s' %
  5494. _("Please enter a grid value with non-zero value, in Float format."))
  5495. return
  5496. else:
  5497. try:
  5498. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5499. except ValueError:
  5500. self.inform.emit('[ERROR_NOTCL]%s...' %
  5501. _(" Grid Value does not exist"))
  5502. return
  5503. self.inform.emit('[success] %s...' %
  5504. _("Grid Value deleted"))
  5505. else:
  5506. self.inform.emit('[WARNING_NOTCL] %s...' %
  5507. _("Delete Grid value cancelled"))
  5508. def on_shortcut_list(self):
  5509. self.defaults.report_usage("on_shortcut_list()")
  5510. # add the tab if it was closed
  5511. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5512. # delete the absolute and relative position and messages in the infobar
  5513. self.ui.position_label.setText("")
  5514. self.ui.rel_position_label.setText("")
  5515. # Switch plot_area to preferences page
  5516. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5517. # self.ui.show()
  5518. def on_select_tab(self, name):
  5519. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5520. if self.ui.splitter.sizes()[0] == 0:
  5521. self.ui.splitter.setSizes([1, 1])
  5522. else:
  5523. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5524. self.ui.splitter.setSizes([0, 1])
  5525. if name == 'project':
  5526. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5527. elif name == 'selected':
  5528. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5529. elif name == 'tool':
  5530. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5531. def on_copy_name(self):
  5532. self.defaults.report_usage("on_copy_name()")
  5533. obj = self.collection.get_active()
  5534. try:
  5535. name = obj.options["name"]
  5536. except AttributeError:
  5537. log.debug("on_copy_name() --> No object selected to copy it's name")
  5538. self.inform.emit('[WARNING_NOTCL]%s' %
  5539. _(" No object selected to copy it's name"))
  5540. return
  5541. self.clipboard.setText(name)
  5542. self.inform.emit(_("Name copied on clipboard ..."))
  5543. def on_mouse_click_over_plot(self, event):
  5544. """
  5545. Default actions are:
  5546. :param event: Contains information about the event, like which button
  5547. was clicked, the pixel coordinates and the axes coordinates.
  5548. :return: None
  5549. """
  5550. self.pos = []
  5551. if self.is_legacy is False:
  5552. event_pos = event.pos
  5553. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5554. # # Set the mouse button for panning
  5555. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5556. else:
  5557. event_pos = (event.xdata, event.ydata)
  5558. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5559. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5560. # So it can receive key presses
  5561. self.plotcanvas.native.setFocus()
  5562. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5563. if self.grid_status():
  5564. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5565. else:
  5566. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5567. try:
  5568. if event.button == 1:
  5569. # Reset here the relative coordinates so there is a new reference on the click position
  5570. if self.rel_point1 is None:
  5571. self.rel_point1 = self.pos
  5572. else:
  5573. self.rel_point2 = copy(self.rel_point1)
  5574. self.rel_point1 = self.pos
  5575. self.on_mouse_move_over_plot(event, origin_click=True)
  5576. except Exception as e:
  5577. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5578. def on_mouse_double_click_over_plot(self, event):
  5579. if event.button == 1:
  5580. self.doubleclick = True
  5581. def on_mouse_move_over_plot(self, event, origin_click=None):
  5582. """
  5583. Callback for the mouse motion event over the plot.
  5584. :param event: Contains information about the event.
  5585. :param origin_click
  5586. :return: None
  5587. """
  5588. if self.is_legacy is False:
  5589. event_pos = event.pos
  5590. if self.defaults["global_pan_button"] == '2':
  5591. pan_button = 2
  5592. else:
  5593. pan_button = 3
  5594. self.event_is_dragging = event.is_dragging
  5595. else:
  5596. event_pos = (event.xdata, event.ydata)
  5597. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5598. if self.defaults["global_pan_button"] == '2':
  5599. pan_button = 3
  5600. else:
  5601. pan_button = 2
  5602. self.event_is_dragging = self.plotcanvas.is_dragging
  5603. # So it can receive key presses but not when the Tcl Shell is active
  5604. if not self.ui.shell_dock.isVisible():
  5605. if not self.plotcanvas.native.hasFocus():
  5606. self.plotcanvas.native.setFocus()
  5607. self.pos_jump = event_pos
  5608. self.ui.popMenu.mouse_is_panning = False
  5609. if origin_click is None:
  5610. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5611. if event.button == pan_button and self.event_is_dragging == 1:
  5612. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5613. if self.ui.popMenu.popup_active:
  5614. self.ui.popMenu.popup_active = False
  5615. return
  5616. self.ui.popMenu.mouse_is_panning = True
  5617. return
  5618. if self.rel_point1 is not None:
  5619. try: # May fail in case mouse not within axes
  5620. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5621. if self.grid_status():
  5622. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5623. # Update cursor
  5624. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5625. symbol='++', edge_color=self.cursor_color_3D,
  5626. edge_width=self.defaults["global_cursor_width"],
  5627. size=self.defaults["global_cursor_size"])
  5628. else:
  5629. pos = (pos_canvas[0], pos_canvas[1])
  5630. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5631. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5632. self.dx = pos[0] - float(self.rel_point1[0])
  5633. self.dy = pos[1] - float(self.rel_point1[1])
  5634. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5635. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5636. self.mouse = [pos[0], pos[1]]
  5637. # if the mouse is moved and the LMB is clicked then the action is a selection
  5638. if self.event_is_dragging == 1 and event.button == 1:
  5639. self.delete_selection_shape()
  5640. if self.dx < 0:
  5641. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5642. face_color=self.defaults['global_alt_sel_fill'])
  5643. self.selection_type = False
  5644. elif self.dx >= 0:
  5645. self.draw_moving_selection_shape(self.pos, pos)
  5646. self.selection_type = True
  5647. else:
  5648. self.selection_type = None
  5649. else:
  5650. self.selection_type = None
  5651. # hover effect - enabled in Preferences -> General -> GUI Settings
  5652. if self.defaults['global_hover']:
  5653. for obj in self.collection.get_list():
  5654. try:
  5655. # select the object(s) only if it is enabled (plotted)
  5656. if obj.options['plot']:
  5657. if obj not in self.collection.get_selected():
  5658. poly_obj = Polygon(
  5659. [(obj.options['xmin'], obj.options['ymin']),
  5660. (obj.options['xmax'], obj.options['ymin']),
  5661. (obj.options['xmax'], obj.options['ymax']),
  5662. (obj.options['xmin'], obj.options['ymax'])]
  5663. )
  5664. if Point(pos).within(poly_obj):
  5665. if obj.isHovering is False:
  5666. obj.isHovering = True
  5667. obj.notHovering = True
  5668. # create the selection box around the selected object
  5669. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5670. else:
  5671. if obj.notHovering is True:
  5672. obj.notHovering = False
  5673. obj.isHovering = False
  5674. self.delete_hover_shape()
  5675. except Exception:
  5676. # the Exception here will happen if we try to select on screen and we have an
  5677. # newly (and empty) just created Geometry or Excellon object that do not have the
  5678. # xmin, xmax, ymin, ymax options.
  5679. # In this case poly_obj creation (see above) will fail
  5680. pass
  5681. except Exception:
  5682. self.ui.position_label.setText("")
  5683. self.ui.rel_position_label.setText("")
  5684. self.mouse = None
  5685. def on_mouse_click_release_over_plot(self, event):
  5686. """
  5687. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5688. and has been registered in ''self.__init__()''.
  5689. :param event: contains information about the event.
  5690. :return:
  5691. """
  5692. if self.is_legacy is False:
  5693. event_pos = event.pos
  5694. right_button = 2
  5695. else:
  5696. event_pos = (event.xdata, event.ydata)
  5697. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5698. right_button = 3
  5699. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5700. if self.grid_status():
  5701. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5702. else:
  5703. pos = (pos_canvas[0], pos_canvas[1])
  5704. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5705. # canvas menu
  5706. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5707. self.ui.popMenu.mouse_is_panning = False
  5708. self.cursor = QtGui.QCursor()
  5709. self.populate_cmenu_grids()
  5710. self.ui.popMenu.popup(self.cursor.pos())
  5711. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5712. # selection and then select a type of selection ("enclosing" or "touching")
  5713. if event.button == 1: # left click
  5714. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5715. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5716. if modifiers == QtCore.Qt.ShiftModifier:
  5717. # do not auto open the Project Tab
  5718. self.click_noproject = True
  5719. self.clipboard.setText(
  5720. self.defaults["global_point_clipboard_format"] %
  5721. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5722. )
  5723. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5724. return
  5725. if self.doubleclick is True:
  5726. self.doubleclick = False
  5727. if self.collection.get_selected():
  5728. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5729. if self.ui.splitter.sizes()[0] == 0:
  5730. self.ui.splitter.setSizes([1, 1])
  5731. try:
  5732. # delete the selection shape(S) as it may be in the way
  5733. self.delete_selection_shape()
  5734. self.delete_hover_shape()
  5735. except Exception as e:
  5736. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5737. return
  5738. else:
  5739. # WORKAROUND for LEGACY MODE
  5740. if self.is_legacy is True:
  5741. # if there is no move on canvas then we have no dragging selection
  5742. if self.dx == 0 or self.dy == 0:
  5743. self.selection_type = None
  5744. if self.selection_type is not None:
  5745. try:
  5746. self.selection_area_handler(self.pos, pos, self.selection_type)
  5747. self.selection_type = None
  5748. except Exception as e:
  5749. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5750. return
  5751. else:
  5752. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5753. if key_modifier == QtCore.Qt.ShiftModifier:
  5754. mod_key = 'Shift'
  5755. elif key_modifier == QtCore.Qt.ControlModifier:
  5756. mod_key = 'Control'
  5757. else:
  5758. mod_key = None
  5759. try:
  5760. if self.command_active is None:
  5761. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5762. # deselect, and if it's not selected then it will be selected
  5763. # If there is no active command (self.command_active is None) then we check if we clicked
  5764. # on a object by checking the bounding limits against mouse click position
  5765. if mod_key == self.defaults["global_mselect_key"]:
  5766. self.select_objects(key='multisel')
  5767. else:
  5768. # If there is no active command (self.command_active is None) then we check if
  5769. # we clicked on a object by checking the bounding limits against mouse click position
  5770. self.select_objects()
  5771. self.delete_hover_shape()
  5772. except Exception as e:
  5773. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5774. return
  5775. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5776. """
  5777. :param start_pos: mouse position when the selection LMB click was done
  5778. :param end_pos: mouse position when the left mouse button is released
  5779. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5780. :return:
  5781. """
  5782. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5783. # delete previous selection shape
  5784. self.delete_selection_shape()
  5785. # make all objects inactive
  5786. self.collection.set_all_inactive()
  5787. for obj in self.collection.get_list():
  5788. try:
  5789. # select the object(s) only if it is enabled (plotted)
  5790. if obj.options['plot']:
  5791. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5792. (obj.options['xmax'], obj.options['ymin']),
  5793. (obj.options['xmax'], obj.options['ymax']),
  5794. (obj.options['xmin'], obj.options['ymax'])])
  5795. if sel_type is True:
  5796. if poly_obj.within(poly_selection):
  5797. # create the selection box around the selected object
  5798. if self.defaults['global_selection_shape'] is True:
  5799. self.draw_selection_shape(obj)
  5800. self.collection.set_active(obj.options['name'])
  5801. else:
  5802. if poly_selection.intersects(poly_obj):
  5803. # create the selection box around the selected object
  5804. if self.defaults['global_selection_shape'] is True:
  5805. self.draw_selection_shape(obj)
  5806. self.collection.set_active(obj.options['name'])
  5807. obj.selection_shape_drawn = True
  5808. except Exception as e:
  5809. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5810. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5811. # In this case poly_obj creation (see above) will fail
  5812. log.debug("App.selection_area_handler() --> %s" % str(e))
  5813. def select_objects(self, key=None):
  5814. """
  5815. Will select objects clicked on canvas
  5816. :param key: for future use in cumulative selection
  5817. :return:
  5818. """
  5819. # list where we store the overlapped objects under our mouse left click position
  5820. if key is None:
  5821. self.objects_under_the_click_list = []
  5822. # Populate the list with the overlapped objects on the click position
  5823. curr_x, curr_y = self.pos
  5824. for obj in self.all_objects_list:
  5825. # ScriptObject and DocumentObject objects can't be selected
  5826. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5827. continue
  5828. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5829. continue
  5830. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5831. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5832. if obj.options['name'] not in self.objects_under_the_click_list:
  5833. if obj.options['plot']:
  5834. # add objects to the objects_under_the_click list only if the object is plotted
  5835. # (active and not disabled)
  5836. self.objects_under_the_click_list.append(obj.options['name'])
  5837. try:
  5838. if self.objects_under_the_click_list:
  5839. curr_sel_obj = self.collection.get_active()
  5840. # case when there is only an object under the click and we toggle it
  5841. if len(self.objects_under_the_click_list) == 1:
  5842. if curr_sel_obj is None:
  5843. self.collection.set_active(self.objects_under_the_click_list[0])
  5844. curr_sel_obj = self.collection.get_active()
  5845. # create the selection box around the selected object
  5846. if self.defaults['global_selection_shape'] is True:
  5847. self.draw_selection_shape(curr_sel_obj)
  5848. curr_sel_obj.selection_shape_drawn = True
  5849. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5850. self.on_objects_selection(False)
  5851. self.delete_selection_shape()
  5852. curr_sel_obj.selection_shape_drawn = False
  5853. self.collection.set_active(self.objects_under_the_click_list[0])
  5854. curr_sel_obj = self.collection.get_active()
  5855. # create the selection box around the selected object
  5856. if self.defaults['global_selection_shape'] is True:
  5857. self.draw_selection_shape(curr_sel_obj)
  5858. curr_sel_obj.selection_shape_drawn = True
  5859. self.selected_message(curr_sel_obj=curr_sel_obj)
  5860. elif curr_sel_obj.selection_shape_drawn is False:
  5861. if self.defaults['global_selection_shape'] is True:
  5862. self.draw_selection_shape(curr_sel_obj)
  5863. curr_sel_obj.selection_shape_drawn = True
  5864. else:
  5865. self.on_objects_selection(False)
  5866. self.delete_selection_shape()
  5867. if self.call_source != 'app':
  5868. self.call_source = 'app'
  5869. self.selected_message(curr_sel_obj=curr_sel_obj)
  5870. else:
  5871. # If there is no selected object
  5872. # make active the first element of the overlapped objects list
  5873. if self.collection.get_active() is None:
  5874. self.collection.set_active(self.objects_under_the_click_list[0])
  5875. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5876. name_sel_obj = self.collection.get_active().options['name']
  5877. # In case that there is a selected object but it is not in the overlapped object list
  5878. # make that object inactive and activate the first element in the overlapped object list
  5879. if name_sel_obj not in self.objects_under_the_click_list:
  5880. self.collection.set_inactive(name_sel_obj)
  5881. name_sel_obj = self.objects_under_the_click_list[0]
  5882. self.collection.set_active(name_sel_obj)
  5883. else:
  5884. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5885. self.collection.set_all_inactive()
  5886. self.collection.set_active(
  5887. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5888. curr_sel_obj = self.collection.get_active()
  5889. # delete the possible selection box around a possible selected object
  5890. self.delete_selection_shape()
  5891. curr_sel_obj.selection_shape_drawn = False
  5892. # create the selection box around the selected object
  5893. if self.defaults['global_selection_shape'] is True:
  5894. self.draw_selection_shape(curr_sel_obj)
  5895. curr_sel_obj.selection_shape_drawn = True
  5896. self.selected_message(curr_sel_obj=curr_sel_obj)
  5897. else:
  5898. # deselect everything
  5899. self.on_objects_selection(False)
  5900. # delete the possible selection box around a possible selected object
  5901. self.delete_selection_shape()
  5902. for o in self.collection.get_list():
  5903. o.selection_shape_drawn = False
  5904. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5905. # only when working on App
  5906. if self.call_source == 'app':
  5907. if self.click_noproject is False:
  5908. # if the Tool Tab is in focus don't change focus to Project Tab
  5909. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5910. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5911. else:
  5912. # restore auto open the Project Tab
  5913. self.click_noproject = False
  5914. # delete any text in the status bar, implicitly the last object name that was selected
  5915. # self.inform.emit("")
  5916. else:
  5917. self.call_source = 'app'
  5918. except Exception as e:
  5919. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5920. def selected_message(self, curr_sel_obj):
  5921. if curr_sel_obj:
  5922. if curr_sel_obj.kind == 'gerber':
  5923. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5924. color='green',
  5925. name=str(curr_sel_obj.options['name']),
  5926. tx=_("selected"))
  5927. )
  5928. elif curr_sel_obj.kind == 'excellon':
  5929. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5930. color='brown',
  5931. name=str(curr_sel_obj.options['name']),
  5932. tx=_("selected"))
  5933. )
  5934. elif curr_sel_obj.kind == 'cncjob':
  5935. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5936. color='blue',
  5937. name=str(curr_sel_obj.options['name']),
  5938. tx=_("selected"))
  5939. )
  5940. elif curr_sel_obj.kind == 'geometry':
  5941. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5942. color='red',
  5943. name=str(curr_sel_obj.options['name']),
  5944. tx=_("selected"))
  5945. )
  5946. def delete_hover_shape(self):
  5947. self.hover_shapes.clear()
  5948. self.hover_shapes.redraw()
  5949. def draw_hover_shape(self, sel_obj, color=None):
  5950. """
  5951. :param sel_obj: The object for which the hover shape must be drawn
  5952. :param color: The color of the hover shape
  5953. :return: None
  5954. """
  5955. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5956. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5957. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5958. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5959. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5960. if self.defaults['units'].upper() == 'MM':
  5961. hover_rect = hover_rect.buffer(-0.1)
  5962. hover_rect = hover_rect.buffer(0.2)
  5963. else:
  5964. hover_rect = hover_rect.buffer(-0.00393)
  5965. hover_rect = hover_rect.buffer(0.00787)
  5966. # if color:
  5967. # face = Color(color)
  5968. # face.alpha = 0.2
  5969. # outline = Color(color, alpha=0.8)
  5970. # else:
  5971. # face = Color(self.defaults['global_sel_fill'])
  5972. # face.alpha = 0.2
  5973. # outline = self.defaults['global_sel_line']
  5974. if color:
  5975. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5976. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5977. else:
  5978. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5979. outline = self.defaults['global_sel_line']
  5980. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5981. if self.is_legacy is True:
  5982. self.hover_shapes.redraw()
  5983. def delete_selection_shape(self):
  5984. self.move_tool.sel_shapes.clear()
  5985. self.move_tool.sel_shapes.redraw()
  5986. def draw_selection_shape(self, sel_obj, color=None):
  5987. """
  5988. Will draw a selection shape around the selected object.
  5989. :param sel_obj: The object for which the selection shape must be drawn
  5990. :param color: The color for the selection shape.
  5991. :return: None
  5992. """
  5993. if sel_obj is None:
  5994. return
  5995. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5996. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5997. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5998. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5999. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6000. if self.defaults['units'].upper() == 'MM':
  6001. sel_rect = sel_rect.buffer(-0.1)
  6002. sel_rect = sel_rect.buffer(0.2)
  6003. else:
  6004. sel_rect = sel_rect.buffer(-0.00393)
  6005. sel_rect = sel_rect.buffer(0.00787)
  6006. if color:
  6007. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6008. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6009. else:
  6010. if self.is_legacy is False:
  6011. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6012. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  6013. else:
  6014. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  6015. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  6016. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6017. color=outline,
  6018. face_color=face,
  6019. update=True,
  6020. layer=0,
  6021. tolerance=None))
  6022. if self.is_legacy is True:
  6023. self.move_tool.sel_shapes.redraw()
  6024. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6025. """
  6026. Will draw a selection shape when dragging mouse on canvas.
  6027. :param old_coords: Old coordinates
  6028. :param coords: New coordinates
  6029. :param kwargs: Keyword arguments
  6030. :return:
  6031. """
  6032. if 'color' in kwargs:
  6033. color = kwargs['color']
  6034. else:
  6035. color = self.defaults['global_sel_line']
  6036. if 'face_color' in kwargs:
  6037. face_color = kwargs['face_color']
  6038. else:
  6039. face_color = self.defaults['global_sel_fill']
  6040. if 'face_alpha' in kwargs:
  6041. face_alpha = kwargs['face_alpha']
  6042. else:
  6043. face_alpha = 0.3
  6044. x0, y0 = old_coords
  6045. x1, y1 = coords
  6046. pt1 = (x0, y0)
  6047. pt2 = (x1, y0)
  6048. pt3 = (x1, y1)
  6049. pt4 = (x0, y1)
  6050. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6051. # color_t = Color(face_color)
  6052. # color_t.alpha = face_alpha
  6053. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  6054. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6055. layer=0, tolerance=None)
  6056. if self.is_legacy is True:
  6057. self.move_tool.sel_shapes.redraw()
  6058. def on_file_new_click(self):
  6059. """
  6060. Callback for menu item File -> New.
  6061. Executed on clicking the Menu -> File -> New Project
  6062. :return:
  6063. """
  6064. if self.collection.get_list() and self.should_we_save:
  6065. msgbox = QtWidgets.QMessageBox()
  6066. # msgbox.setText("<B>Save changes ...</B>")
  6067. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6068. "Creating a New project will delete them.\n"
  6069. "Do you want to Save the project?"))
  6070. msgbox.setWindowTitle(_("Save changes"))
  6071. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6072. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6073. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6074. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6075. msgbox.setDefaultButton(bt_yes)
  6076. msgbox.exec_()
  6077. response = msgbox.clickedButton()
  6078. if response == bt_yes:
  6079. self.on_file_saveprojectas()
  6080. elif response == bt_cancel:
  6081. return
  6082. elif response == bt_no:
  6083. self.on_file_new()
  6084. else:
  6085. self.on_file_new()
  6086. self.inform.emit('[success] %s...' % _("New Project created"))
  6087. def on_file_new(self, cli=None):
  6088. """
  6089. Returns the application to its startup state. This method is thread-safe.
  6090. :param cli: Boolean. If True this method was run from command line
  6091. :return: None
  6092. """
  6093. self.defaults.report_usage("on_file_new")
  6094. # Remove everything from memory
  6095. App.log.debug("on_file_new()")
  6096. # close any editor that might be open
  6097. if self.call_source != 'app':
  6098. self.editor2object(cleanup=True)
  6099. # ## EDITOR section
  6100. self.geo_editor = FlatCAMGeoEditor(self)
  6101. self.exc_editor = FlatCAMExcEditor(self)
  6102. self.grb_editor = FlatCAMGrbEditor(self)
  6103. # Clear pool
  6104. self.clear_pool()
  6105. for obj in self.collection.get_list():
  6106. # delete shapes left drawn from mark shape_collections, if any
  6107. if isinstance(obj, GerberObject):
  6108. try:
  6109. for el in obj.mark_shapes:
  6110. obj.mark_shapes[el].clear(update=True)
  6111. obj.mark_shapes[el].enabled = False
  6112. del el
  6113. except AttributeError:
  6114. pass
  6115. # also delete annotation shapes, if any
  6116. elif isinstance(obj, CNCJobObject):
  6117. try:
  6118. obj.text_col.enabled = False
  6119. del obj.text_col
  6120. obj.annotation.clear(update=True)
  6121. del obj.annotation
  6122. except AttributeError:
  6123. pass
  6124. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6125. self.shell.init_tcl()
  6126. # delete any selection shape on canvas
  6127. self.delete_selection_shape()
  6128. # delete all FlatCAM objects
  6129. self.collection.delete_all()
  6130. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  6131. self.setup_component_editor()
  6132. # Clear project filename
  6133. self.project_filename = None
  6134. # Load the application defaults
  6135. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6136. # Re-fresh project options
  6137. self.on_options_app2project()
  6138. # Init FlatCAMTools
  6139. self.init_tools()
  6140. # Try to close all tabs in the PlotArea but only if the GUI is active (CLI is None)
  6141. if cli is None:
  6142. # we need to go in reverse because once we remove a tab then the index changes
  6143. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  6144. # and so on. Therefore the deletion should be done in reverse
  6145. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  6146. for index in range(wdg_count, -1, -1):
  6147. try:
  6148. self.ui.plot_tab_area.closeTab(index)
  6149. except Exception as e:
  6150. log.debug("App.on_file_new() --> %s" % str(e))
  6151. # # And then add again the Plot Area
  6152. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  6153. self.ui.plot_tab_area.protectTab(0)
  6154. # take the focus of the Notebook on Project Tab.
  6155. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6156. self.set_ui_title(name=_("New Project - Not saved"))
  6157. def obj_properties(self):
  6158. """
  6159. Will launch the object Properties Tool
  6160. :return:
  6161. """
  6162. self.defaults.report_usage("obj_properties()")
  6163. self.properties_tool.run(toggle=False)
  6164. def on_project_context_save(self):
  6165. """
  6166. Wrapper, will save the object function of it's type
  6167. :return:
  6168. """
  6169. obj = self.collection.get_active()
  6170. if type(obj) == GeometryObject:
  6171. self.on_file_exportdxf()
  6172. elif type(obj) == ExcellonObject:
  6173. self.on_file_saveexcellon()
  6174. elif type(obj) == CNCJobObject:
  6175. obj.on_exportgcode_button_click()
  6176. elif type(obj) == GerberObject:
  6177. self.on_file_savegerber()
  6178. elif type(obj) == ScriptObject:
  6179. self.on_file_savescript()
  6180. elif type(obj) == DocumentObject:
  6181. self.on_file_savedocument()
  6182. def obj_move(self):
  6183. """
  6184. Callback for the Move menu entry in various Context Menu's.
  6185. :return:
  6186. """
  6187. self.defaults.report_usage("obj_move()")
  6188. self.move_tool.run(toggle=False)
  6189. def on_fileopengerber(self, signal, name=None):
  6190. """
  6191. File menu callback for opening a Gerber.
  6192. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6193. :param name:
  6194. :return: None
  6195. """
  6196. self.defaults.report_usage("on_fileopengerber")
  6197. App.log.debug("on_fileopengerber()")
  6198. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6199. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6200. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6201. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6202. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6203. "*.mil);;" \
  6204. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6205. "Allegro Files (*.art);;" \
  6206. "Mentor Files (*.pho *.gdo);;" \
  6207. "All Files (*.*)"
  6208. if name is None:
  6209. try:
  6210. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6211. directory=self.get_last_folder(),
  6212. filter=_filter_)
  6213. except TypeError:
  6214. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6215. filenames = [str(filename) for filename in filenames]
  6216. else:
  6217. filenames = [name]
  6218. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6219. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6220. _("Opening Gerber file.")),
  6221. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6222. color=QtGui.QColor("gray"))
  6223. if len(filenames) == 0:
  6224. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6225. else:
  6226. for filename in filenames:
  6227. if filename != '':
  6228. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6229. def on_fileopenexcellon(self, signal, name=None):
  6230. """
  6231. File menu callback for opening an Excellon file.
  6232. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6233. :param name:
  6234. :return: None
  6235. """
  6236. self.defaults.report_usage("on_fileopenexcellon")
  6237. App.log.debug("on_fileopenexcellon()")
  6238. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6239. "All Files (*.*)"
  6240. if name is None:
  6241. try:
  6242. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6243. directory=self.get_last_folder(),
  6244. filter=_filter_)
  6245. except TypeError:
  6246. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6247. filenames = [str(filename) for filename in filenames]
  6248. else:
  6249. filenames = [str(name)]
  6250. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6251. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6252. _("Opening Excellon file.")),
  6253. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6254. color=QtGui.QColor("gray"))
  6255. if len(filenames) == 0:
  6256. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6257. else:
  6258. for filename in filenames:
  6259. if filename != '':
  6260. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6261. def on_fileopengcode(self, signal, name=None):
  6262. """
  6263. File menu call back for opening gcode.
  6264. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6265. :param name:
  6266. :return:
  6267. """
  6268. self.defaults.report_usage("on_fileopengcode")
  6269. App.log.debug("on_fileopengcode()")
  6270. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6271. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6272. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6273. "All Files (*.*)"
  6274. if name is None:
  6275. try:
  6276. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6277. directory=self.get_last_folder(),
  6278. filter=_filter_)
  6279. except TypeError:
  6280. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6281. filenames = [str(filename) for filename in filenames]
  6282. else:
  6283. filenames = [name]
  6284. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6285. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6286. _("Opening G-Code file.")),
  6287. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6288. color=QtGui.QColor("gray"))
  6289. if len(filenames) == 0:
  6290. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6291. else:
  6292. for filename in filenames:
  6293. if filename != '':
  6294. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6295. def on_file_openproject(self, signal):
  6296. """
  6297. File menu callback for opening a project.
  6298. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6299. :return: None
  6300. """
  6301. self.defaults.report_usage("on_file_openproject")
  6302. App.log.debug("on_file_openproject()")
  6303. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6304. try:
  6305. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6306. directory=self.get_last_folder(), filter=_filter_)
  6307. except TypeError:
  6308. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6309. # The Qt methods above will return a QString which can cause problems later.
  6310. # So far json.dump() will fail to serialize it.
  6311. # TODO: Improve the serialization methods and remove this fix.
  6312. filename = str(filename)
  6313. if filename == "":
  6314. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6315. else:
  6316. # self.worker_task.emit({'fcn': self.open_project,
  6317. # 'params': [filename]})
  6318. # The above was failing because open_project() is not
  6319. # thread safe. The new_project()
  6320. self.open_project(filename)
  6321. def on_fileopenhpgl2(self, signal, name=None):
  6322. """
  6323. File menu callback for opening a HPGL2.
  6324. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6325. :param name:
  6326. :return: None
  6327. """
  6328. self.defaults.report_usage("on_fileopenhpgl2")
  6329. App.log.debug("on_fileopenhpgl2()")
  6330. _filter_ = "HPGL2 Files (*.plt);;" \
  6331. "All Files (*.*)"
  6332. if name is None:
  6333. try:
  6334. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6335. directory=self.get_last_folder(),
  6336. filter=_filter_)
  6337. except TypeError:
  6338. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6339. filenames = [str(filename) for filename in filenames]
  6340. else:
  6341. filenames = [name]
  6342. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6343. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6344. _("Opening HPGL2 file.")),
  6345. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6346. color=QtGui.QColor("gray"))
  6347. if len(filenames) == 0:
  6348. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6349. else:
  6350. for filename in filenames:
  6351. if filename != '':
  6352. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6353. def on_file_openconfig(self, signal):
  6354. """
  6355. File menu callback for opening a config file.
  6356. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6357. :return: None
  6358. """
  6359. self.defaults.report_usage("on_file_openconfig")
  6360. App.log.debug("on_file_openconfig()")
  6361. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6362. try:
  6363. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6364. directory=self.data_path, filter=_filter_)
  6365. except TypeError:
  6366. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6367. filter=_filter_)
  6368. if filename == "":
  6369. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6370. else:
  6371. self.open_config_file(filename)
  6372. def on_file_exportsvg(self):
  6373. """
  6374. Callback for menu item File->Export SVG.
  6375. :return: None
  6376. """
  6377. self.defaults.report_usage("on_file_exportsvg")
  6378. App.log.debug("on_file_exportsvg()")
  6379. obj = self.collection.get_active()
  6380. if obj is None:
  6381. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6382. msg = _("Please Select a Geometry object to export")
  6383. msgbox = QtWidgets.QMessageBox()
  6384. msgbox.setInformativeText(msg)
  6385. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6386. msgbox.setDefaultButton(bt_ok)
  6387. msgbox.exec_()
  6388. return
  6389. # Check for more compatible types and add as required
  6390. if (not isinstance(obj, GeometryObject)
  6391. and not isinstance(obj, GerberObject)
  6392. and not isinstance(obj, CNCJobObject)
  6393. and not isinstance(obj, ExcellonObject)):
  6394. msg = '[ERROR_NOTCL] %s' % \
  6395. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6396. msgbox = QtWidgets.QMessageBox()
  6397. msgbox.setInformativeText(msg)
  6398. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6399. msgbox.setDefaultButton(bt_ok)
  6400. msgbox.exec_()
  6401. return
  6402. name = obj.options["name"]
  6403. _filter = "SVG File (*.svg);;All Files (*.*)"
  6404. try:
  6405. filename, _f = FCFileSaveDialog.get_saved_filename(
  6406. caption=_("Export SVG"),
  6407. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6408. filter=_filter)
  6409. except TypeError:
  6410. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6411. filename = str(filename)
  6412. if filename == "":
  6413. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6414. return
  6415. else:
  6416. self.export_svg(name, filename)
  6417. if self.defaults["global_open_style"] is False:
  6418. self.file_opened.emit("SVG", filename)
  6419. self.file_saved.emit("SVG", filename)
  6420. def on_file_exportpng(self):
  6421. self.defaults.report_usage("on_file_exportpng")
  6422. App.log.debug("on_file_exportpng()")
  6423. self.date = str(datetime.today()).rpartition('.')[0]
  6424. self.date = ''.join(c for c in self.date if c not in ':-')
  6425. self.date = self.date.replace(' ', '_')
  6426. if self.is_legacy is False:
  6427. image = _screenshot()
  6428. data = np.asarray(image)
  6429. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6430. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6431. return
  6432. filter_ = "PNG File (*.png);;All Files (*.*)"
  6433. try:
  6434. filename, _f = FCFileSaveDialog.get_saved_filename(
  6435. caption=_("Export PNG Image"),
  6436. directory=self.get_last_save_folder() + '/png_' + self.date,
  6437. filter=filter_)
  6438. except TypeError:
  6439. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6440. filename = str(filename)
  6441. if filename == "":
  6442. self.inform.emit(_("Cancelled."))
  6443. return
  6444. else:
  6445. if self.is_legacy is False:
  6446. write_png(filename, data)
  6447. else:
  6448. self.plotcanvas.figure.savefig(filename)
  6449. if self.defaults["global_open_style"] is False:
  6450. self.file_opened.emit("png", filename)
  6451. self.file_saved.emit("png", filename)
  6452. def on_file_savegerber(self):
  6453. """
  6454. Callback for menu item in Project context menu.
  6455. :return: None
  6456. """
  6457. self.defaults.report_usage("on_file_savegerber")
  6458. App.log.debug("on_file_savegerber()")
  6459. obj = self.collection.get_active()
  6460. if obj is None:
  6461. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6462. return
  6463. # Check for more compatible types and add as required
  6464. if not isinstance(obj, GerberObject):
  6465. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6466. return
  6467. name = self.collection.get_active().options["name"]
  6468. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6469. try:
  6470. filename, _f = FCFileSaveDialog.get_saved_filename(
  6471. caption="Save Gerber source file",
  6472. directory=self.get_last_save_folder() + '/' + name,
  6473. filter=_filter)
  6474. except TypeError:
  6475. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6476. filename = str(filename)
  6477. if filename == "":
  6478. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6479. return
  6480. else:
  6481. self.save_source_file(name, filename)
  6482. if self.defaults["global_open_style"] is False:
  6483. self.file_opened.emit("Gerber", filename)
  6484. self.file_saved.emit("Gerber", filename)
  6485. def on_file_savescript(self):
  6486. """
  6487. Callback for menu item in Project context menu.
  6488. :return: None
  6489. """
  6490. self.defaults.report_usage("on_file_savescript")
  6491. App.log.debug("on_file_savescript()")
  6492. obj = self.collection.get_active()
  6493. if obj is None:
  6494. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6495. return
  6496. # Check for more compatible types and add as required
  6497. if not isinstance(obj, ScriptObject):
  6498. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6499. return
  6500. name = self.collection.get_active().options["name"]
  6501. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6502. try:
  6503. filename, _f = FCFileSaveDialog.get_saved_filename(
  6504. caption="Save Script source file",
  6505. directory=self.get_last_save_folder() + '/' + name,
  6506. filter=_filter)
  6507. except TypeError:
  6508. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6509. filename = str(filename)
  6510. if filename == "":
  6511. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6512. return
  6513. else:
  6514. self.save_source_file(name, filename)
  6515. if self.defaults["global_open_style"] is False:
  6516. self.file_opened.emit("Script", filename)
  6517. self.file_saved.emit("Script", filename)
  6518. def on_file_savedocument(self):
  6519. """
  6520. Callback for menu item in Project context menu.
  6521. :return: None
  6522. """
  6523. self.defaults.report_usage("on_file_savedocument")
  6524. App.log.debug("on_file_savedocument()")
  6525. obj = self.collection.get_active()
  6526. if obj is None:
  6527. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6528. return
  6529. # Check for more compatible types and add as required
  6530. if not isinstance(obj, ScriptObject):
  6531. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6532. return
  6533. name = self.collection.get_active().options["name"]
  6534. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6535. try:
  6536. filename, _f = FCFileSaveDialog.get_saved_filename(
  6537. caption="Save Document source file",
  6538. directory=self.get_last_save_folder() + '/' + name,
  6539. filter=_filter)
  6540. except TypeError:
  6541. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6542. filename = str(filename)
  6543. if filename == "":
  6544. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6545. return
  6546. else:
  6547. self.save_source_file(name, filename)
  6548. if self.defaults["global_open_style"] is False:
  6549. self.file_opened.emit("Document", filename)
  6550. self.file_saved.emit("Document", filename)
  6551. def on_file_saveexcellon(self):
  6552. """
  6553. Callback for menu item in project context menu.
  6554. :return: None
  6555. """
  6556. self.defaults.report_usage("on_file_saveexcellon")
  6557. App.log.debug("on_file_saveexcellon()")
  6558. obj = self.collection.get_active()
  6559. if obj is None:
  6560. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6561. return
  6562. # Check for more compatible types and add as required
  6563. if not isinstance(obj, ExcellonObject):
  6564. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6565. return
  6566. name = self.collection.get_active().options["name"]
  6567. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6568. try:
  6569. filename, _f = FCFileSaveDialog.get_saved_filename(
  6570. caption=_("Save Excellon source file"),
  6571. directory=self.get_last_save_folder() + '/' + name,
  6572. filter=_filter)
  6573. except TypeError:
  6574. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6575. filename = str(filename)
  6576. if filename == "":
  6577. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6578. return
  6579. else:
  6580. self.save_source_file(name, filename)
  6581. if self.defaults["global_open_style"] is False:
  6582. self.file_opened.emit("Excellon", filename)
  6583. self.file_saved.emit("Excellon", filename)
  6584. def on_file_exportexcellon(self):
  6585. """
  6586. Callback for menu item File->Export->Excellon.
  6587. :return: None
  6588. """
  6589. self.defaults.report_usage("on_file_exportexcellon")
  6590. App.log.debug("on_file_exportexcellon()")
  6591. obj = self.collection.get_active()
  6592. if obj is None:
  6593. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6594. return
  6595. # Check for more compatible types and add as required
  6596. if not isinstance(obj, ExcellonObject):
  6597. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6598. return
  6599. name = self.collection.get_active().options["name"]
  6600. _filter = self.defaults["excellon_save_filters"]
  6601. try:
  6602. filename, _f = FCFileSaveDialog.get_saved_filename(
  6603. caption=_("Export Excellon"),
  6604. directory=self.get_last_save_folder() + '/' + name,
  6605. filter=_filter)
  6606. except TypeError:
  6607. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6608. filename = str(filename)
  6609. if filename == "":
  6610. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6611. return
  6612. else:
  6613. used_extension = filename.rpartition('.')[2]
  6614. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6615. self.export_excellon(name, filename)
  6616. if self.defaults["global_open_style"] is False:
  6617. self.file_opened.emit("Excellon", filename)
  6618. self.file_saved.emit("Excellon", filename)
  6619. def on_file_exportgerber(self):
  6620. """
  6621. Callback for menu item File->Export->Gerber.
  6622. :return: None
  6623. """
  6624. self.defaults.report_usage("on_file_exportgerber")
  6625. App.log.debug("on_file_exportgerber()")
  6626. obj = self.collection.get_active()
  6627. if obj is None:
  6628. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6629. return
  6630. # Check for more compatible types and add as required
  6631. if not isinstance(obj, GerberObject):
  6632. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6633. return
  6634. name = self.collection.get_active().options["name"]
  6635. _filter_ = self.defaults['gerber_save_filters']
  6636. try:
  6637. filename, _f = FCFileSaveDialog.get_saved_filename(
  6638. caption=_("Export Gerber"),
  6639. directory=self.get_last_save_folder() + '/' + name,
  6640. filter=_filter_)
  6641. except TypeError:
  6642. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6643. filename = str(filename)
  6644. if filename == "":
  6645. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6646. return
  6647. else:
  6648. used_extension = filename.rpartition('.')[2]
  6649. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6650. self.export_gerber(name, filename)
  6651. if self.defaults["global_open_style"] is False:
  6652. self.file_opened.emit("Gerber", filename)
  6653. self.file_saved.emit("Gerber", filename)
  6654. def on_file_exportdxf(self):
  6655. """
  6656. Callback for menu item File->Export DXF.
  6657. :return: None
  6658. """
  6659. self.defaults.report_usage("on_file_exportdxf")
  6660. App.log.debug("on_file_exportdxf()")
  6661. obj = self.collection.get_active()
  6662. if obj is None:
  6663. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6664. msg = _("Please Select a Geometry object to export")
  6665. msgbox = QtWidgets.QMessageBox()
  6666. msgbox.setInformativeText(msg)
  6667. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6668. msgbox.setDefaultButton(bt_ok)
  6669. msgbox.exec_()
  6670. return
  6671. # Check for more compatible types and add as required
  6672. if not isinstance(obj, GeometryObject):
  6673. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6674. msgbox = QtWidgets.QMessageBox()
  6675. msgbox.setInformativeText(msg)
  6676. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6677. msgbox.setDefaultButton(bt_ok)
  6678. msgbox.exec_()
  6679. return
  6680. name = self.collection.get_active().options["name"]
  6681. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6682. try:
  6683. filename, _f = FCFileSaveDialog.get_saved_filename(
  6684. caption=_("Export DXF"),
  6685. directory=self.get_last_save_folder() + '/' + name,
  6686. filter=_filter_)
  6687. except TypeError:
  6688. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6689. filename = str(filename)
  6690. if filename == "":
  6691. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6692. return
  6693. else:
  6694. self.export_dxf(name, filename)
  6695. if self.defaults["global_open_style"] is False:
  6696. self.file_opened.emit("DXF", filename)
  6697. self.file_saved.emit("DXF", filename)
  6698. def on_file_importsvg(self, type_of_obj):
  6699. """
  6700. Callback for menu item File->Import SVG.
  6701. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6702. :type type_of_obj: str
  6703. :return: None
  6704. """
  6705. self.defaults.report_usage("on_file_importsvg")
  6706. App.log.debug("on_file_importsvg()")
  6707. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6708. try:
  6709. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6710. directory=self.get_last_folder(), filter=_filter_)
  6711. except TypeError:
  6712. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6713. filter=_filter_)
  6714. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6715. type_of_obj = "geometry"
  6716. filenames = [str(filename) for filename in filenames]
  6717. if len(filenames) == 0:
  6718. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6719. else:
  6720. for filename in filenames:
  6721. if filename != '':
  6722. self.worker_task.emit({'fcn': self.import_svg,
  6723. 'params': [filename, type_of_obj]})
  6724. def on_file_importdxf(self, type_of_obj):
  6725. """
  6726. Callback for menu item File->Import DXF.
  6727. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6728. :type type_of_obj: str
  6729. :return: None
  6730. """
  6731. self.defaults.report_usage("on_file_importdxf")
  6732. App.log.debug("on_file_importdxf()")
  6733. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6734. try:
  6735. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6736. directory=self.get_last_folder(),
  6737. filter=_filter_)
  6738. except TypeError:
  6739. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6740. filter=_filter_)
  6741. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6742. type_of_obj = "geometry"
  6743. filenames = [str(filename) for filename in filenames]
  6744. if len(filenames) == 0:
  6745. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6746. else:
  6747. for filename in filenames:
  6748. if filename != '':
  6749. self.worker_task.emit({'fcn': self.import_dxf,
  6750. 'params': [filename, type_of_obj]})
  6751. # ###############################################################################################################
  6752. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6753. # ###############################################################################################################
  6754. def init_code_editor(self, name):
  6755. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6756. # add the tab if it was closed
  6757. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6758. self.text_editor_tab.setObjectName('text_editor_tab')
  6759. # delete the absolute and relative position and messages in the infobar
  6760. self.ui.position_label.setText("")
  6761. self.ui.rel_position_label.setText("")
  6762. # first clear previous text in text editor (if any)
  6763. self.text_editor_tab.code_editor.clear()
  6764. self.text_editor_tab.code_editor.setReadOnly(False)
  6765. self.toggle_codeeditor = True
  6766. self.text_editor_tab.code_editor.completer_enable = False
  6767. self.text_editor_tab.buttonRun.hide()
  6768. # make sure to keep a reference to the code editor
  6769. self.reference_code_editor = self.text_editor_tab.code_editor
  6770. # Switch plot_area to CNCJob tab
  6771. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6772. def on_view_source(self):
  6773. """
  6774. Called when the user wants to see the source file of the selected object
  6775. :return:
  6776. """
  6777. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6778. self.proc_container.view.set_busy(_("Loading..."))
  6779. try:
  6780. obj = self.collection.get_active()
  6781. except Exception as e:
  6782. log.debug("App.on_view_source() --> %s" % str(e))
  6783. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6784. return 'fail'
  6785. if obj is None:
  6786. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6787. return 'fail'
  6788. flt = "All Files (*.*)"
  6789. if obj.kind == 'gerber':
  6790. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6791. elif obj.kind == 'excellon':
  6792. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6793. elif obj.kind == 'cncjob':
  6794. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6795. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6796. # add the tab if it was closed
  6797. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6798. self.source_editor_tab.setObjectName('source_editor_tab')
  6799. # delete the absolute and relative position and messages in the infobar
  6800. self.ui.position_label.setText("")
  6801. self.ui.rel_position_label.setText("")
  6802. # first clear previous text in text editor (if any)
  6803. self.source_editor_tab.code_editor.clear()
  6804. self.source_editor_tab.code_editor.setReadOnly(False)
  6805. self.source_editor_tab.code_editor.completer_enable = False
  6806. self.source_editor_tab.buttonRun.hide()
  6807. # Switch plot_area to CNCJob tab
  6808. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6809. try:
  6810. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6811. except TypeError:
  6812. pass
  6813. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6814. try:
  6815. self.source_editor_tab.buttonSave.clicked.disconnect()
  6816. except TypeError:
  6817. pass
  6818. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6819. # then append the text from GCode to the text editor
  6820. if obj.kind == 'cncjob':
  6821. try:
  6822. file = obj.export_gcode(
  6823. preamble=self.defaults["cncjob_prepend"],
  6824. postamble=self.defaults["cncjob_append"],
  6825. to_file=True)
  6826. if file == 'fail':
  6827. return 'fail'
  6828. except AttributeError:
  6829. self.inform.emit('[WARNING_NOTCL] %s' %
  6830. _("There is no selected object for which to see it's source file code."))
  6831. return 'fail'
  6832. else:
  6833. try:
  6834. file = StringIO(obj.source_file)
  6835. except (AttributeError, TypeError):
  6836. self.inform.emit('[WARNING_NOTCL] %s' %
  6837. _("There is no selected object for which to see it's source file code."))
  6838. return 'fail'
  6839. self.source_editor_tab.t_frame.hide()
  6840. try:
  6841. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6842. # for line in file:
  6843. # QtWidgets.QApplication.processEvents()
  6844. # proc_line = str(line).strip('\n')
  6845. # self.source_editor_tab.code_editor.append(proc_line)
  6846. except Exception as e:
  6847. log.debug('App.on_view_source() -->%s' % str(e))
  6848. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6849. return
  6850. self.source_editor_tab.handleTextChanged()
  6851. self.source_editor_tab.t_frame.show()
  6852. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6853. self.proc_container.view.set_idle()
  6854. # self.ui.show()
  6855. def on_toggle_code_editor(self):
  6856. self.defaults.report_usage("on_toggle_code_editor()")
  6857. if self.toggle_codeeditor is False:
  6858. self.init_code_editor(name=_("Code Editor"))
  6859. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6860. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6861. self.text_editor_tab.buttonSave.clicked.disconnect()
  6862. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6863. else:
  6864. for idx in range(self.ui.plot_tab_area.count()):
  6865. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6866. self.ui.plot_tab_area.closeTab(idx)
  6867. break
  6868. self.toggle_codeeditor = False
  6869. def on_code_editor_close(self):
  6870. self.toggle_codeeditor = False
  6871. def goto_text_line(self):
  6872. """
  6873. Will scroll a text to the specified text line.
  6874. :return: None
  6875. """
  6876. dia_box = Dialog_box(title=_("Go to Line ..."),
  6877. label=_("Line:"),
  6878. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6879. initial_text='')
  6880. try:
  6881. line = int(dia_box.location) - 1
  6882. except (ValueError, TypeError):
  6883. line = 0
  6884. if dia_box.ok:
  6885. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6886. # at the top of the window
  6887. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6888. # get the document() of the TextEditor
  6889. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6890. # create a Text Cursor based on the searched line
  6891. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6892. # set cursor of the code editor with the cursor at the searcehd line
  6893. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6894. def on_filenewscript(self, silent=False):
  6895. """
  6896. Will create a new script file and open it in the Code Editor
  6897. :param silent: if True will not display status messages
  6898. :param name: if specified will be the name of the new script
  6899. :param text: pass a source file to the newly created script to be loaded in it
  6900. :return: None
  6901. """
  6902. if silent is False:
  6903. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6904. # delete the absolute and relative position and messages in the infobar
  6905. self.ui.position_label.setText("")
  6906. self.ui.rel_position_label.setText("")
  6907. self.new_script_object()
  6908. # script_text = script_obj.source_file
  6909. #
  6910. # self.proc_container.view.set_busy(_("Loading..."))
  6911. # script_obj.script_editor_tab.t_frame.hide()
  6912. #
  6913. # script_obj.script_editor_tab.t_frame.show()
  6914. # self.proc_container.view.set_idle()
  6915. def on_fileopenscript(self, name=None, silent=False):
  6916. """
  6917. Will open a Tcl script file into the Code Editor
  6918. :param silent: if True will not display status messages
  6919. :param name: name of a Tcl script file to open
  6920. :return: None
  6921. """
  6922. self.defaults.report_usage("on_fileopenscript")
  6923. App.log.debug("on_fileopenscript()")
  6924. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6925. "All Files (*.*)"
  6926. if name:
  6927. filenames = [name]
  6928. else:
  6929. try:
  6930. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6931. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6932. except TypeError:
  6933. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6934. if len(filenames) == 0:
  6935. if silent is False:
  6936. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6937. else:
  6938. for filename in filenames:
  6939. if filename != '':
  6940. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6941. def on_fileopenscript_example(self, name=None, silent=False):
  6942. """
  6943. Will open a Tcl script file into the Code Editor
  6944. :param silent: if True will not display status messages
  6945. :param name: name of a Tcl script file to open
  6946. :return:
  6947. """
  6948. self.defaults.report_usage("on_fileopenscript_example")
  6949. log.debug("on_fileopenscript_example()")
  6950. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6951. "All Files (*.*)"
  6952. # test if the app was frozen and choose the path for the configuration file
  6953. if getattr(sys, "frozen", False) is True:
  6954. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6955. else:
  6956. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6957. if name:
  6958. filenames = [name]
  6959. else:
  6960. try:
  6961. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6962. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6963. except TypeError:
  6964. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6965. if len(filenames) == 0:
  6966. if silent is False:
  6967. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6968. else:
  6969. for filename in filenames:
  6970. if filename != '':
  6971. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6972. def on_filerunscript(self, name=None, silent=False):
  6973. """
  6974. File menu callback for loading and running a TCL script.
  6975. :param silent: if True will not display status messages
  6976. :param name: name of a Tcl script file to be run by FlatCAM
  6977. :return: None
  6978. """
  6979. self.defaults.report_usage("on_filerunscript")
  6980. App.log.debug("on_file_runscript()")
  6981. if name:
  6982. filename = name
  6983. if self.cmd_line_headless != 1:
  6984. self.splash.showMessage('%s: %ssec\n%s' %
  6985. (_("Canvas initialization started.\n"
  6986. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6987. _("Executing ScriptObject file.")
  6988. ),
  6989. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6990. color=QtGui.QColor("gray"))
  6991. else:
  6992. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6993. "All Files (*.*)"
  6994. try:
  6995. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6996. directory=self.get_last_folder(), filter=_filter_)
  6997. except TypeError:
  6998. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6999. # The Qt methods above will return a QString which can cause problems later.
  7000. # So far json.dump() will fail to serialize it.
  7001. filename = str(filename)
  7002. if filename == "":
  7003. if silent is False:
  7004. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7005. else:
  7006. if self.cmd_line_headless != 1:
  7007. if self.ui.shell_dock.isHidden():
  7008. self.ui.shell_dock.show()
  7009. try:
  7010. with open(filename, "r") as tcl_script:
  7011. cmd_line_shellfile_content = tcl_script.read()
  7012. if self.cmd_line_headless != 1:
  7013. self.shell.exec_command(cmd_line_shellfile_content)
  7014. else:
  7015. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7016. if silent is False:
  7017. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7018. except Exception as e:
  7019. log.debug("App.on_filerunscript() -> %s" % str(e))
  7020. sys.exit(2)
  7021. def on_file_saveproject(self, silent=False):
  7022. """
  7023. Callback for menu item File->Save Project. Saves the project to
  7024. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7025. if set to None. The project is saved by calling ``self.save_project()``.
  7026. :param silent: if True will not display status messages
  7027. :return: None
  7028. """
  7029. self.defaults.report_usage("on_file_saveproject")
  7030. if self.project_filename is None:
  7031. self.on_file_saveprojectas()
  7032. else:
  7033. self.worker_task.emit({'fcn': self.save_project,
  7034. 'params': [self.project_filename, silent]})
  7035. if self.defaults["global_open_style"] is False:
  7036. self.file_opened.emit("project", self.project_filename)
  7037. self.file_saved.emit("project", self.project_filename)
  7038. self.set_ui_title(name=self.project_filename)
  7039. self.should_we_save = False
  7040. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7041. """
  7042. Callback for menu item File->Save Project As... Opens a file
  7043. chooser and saves the project to the given file via
  7044. ``self.save_project()``.
  7045. :param make_copy if to be create a copy of the project; boolean
  7046. :param use_thread: if to be run in a separate thread; boolean
  7047. :param quit_action: if to be followed by quiting the application; boolean
  7048. :return: None
  7049. """
  7050. self.defaults.report_usage("on_file_saveprojectas")
  7051. self.date = str(datetime.today()).rpartition('.')[0]
  7052. self.date = ''.join(c for c in self.date if c not in ':-')
  7053. self.date = self.date.replace(' ', '_')
  7054. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7055. try:
  7056. filename, _f = FCFileSaveDialog.get_saved_filename(
  7057. caption=_("Save Project As ..."),
  7058. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  7059. proj=_("Project")),
  7060. filter=filter_
  7061. )
  7062. except TypeError:
  7063. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  7064. filename = str(filename)
  7065. if filename == '':
  7066. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7067. return
  7068. if use_thread is True:
  7069. self.worker_task.emit({'fcn': self.save_project,
  7070. 'params': [filename, quit_action]})
  7071. else:
  7072. self.save_project(filename, quit_action)
  7073. # self.save_project(filename)
  7074. if self.defaults["global_open_style"] is False:
  7075. self.file_opened.emit("project", filename)
  7076. self.file_saved.emit("project", filename)
  7077. if not make_copy:
  7078. self.project_filename = filename
  7079. self.set_ui_title(name=self.project_filename)
  7080. self.should_we_save = False
  7081. def on_file_save_objects_pdf(self, use_thread=True):
  7082. self.date = str(datetime.today()).rpartition('.')[0]
  7083. self.date = ''.join(c for c in self.date if c not in ':-')
  7084. self.date = self.date.replace(' ', '_')
  7085. try:
  7086. obj_selection = self.collection.get_selected()
  7087. if len(obj_selection) == 1:
  7088. obj_name = str(obj_selection[0].options['name'])
  7089. else:
  7090. obj_name = _("FlatCAM objects print")
  7091. except AttributeError as err:
  7092. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7093. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7094. return
  7095. if not obj_selection:
  7096. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7097. return
  7098. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7099. try:
  7100. filename, _f = FCFileSaveDialog.get_saved_filename(
  7101. caption=_("Save Object as PDF ..."),
  7102. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7103. obj_name=obj_name,
  7104. date=self.date),
  7105. filter=filter_
  7106. )
  7107. except TypeError:
  7108. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7109. filename = str(filename)
  7110. if filename == '':
  7111. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7112. return
  7113. if use_thread is True:
  7114. self.proc_container.new(_("Printing PDF ... Please wait."))
  7115. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7116. else:
  7117. self.save_pdf(filename, obj_selection)
  7118. # self.save_project(filename)
  7119. if self.defaults["global_open_style"] is False:
  7120. self.file_opened.emit("pdf", filename)
  7121. self.file_saved.emit("pdf", filename)
  7122. def save_pdf(self, file_name, obj_selection):
  7123. p_size = self.defaults['global_workspaceT']
  7124. orientation = self.defaults['global_workspace_orientation']
  7125. color = 'black'
  7126. transparency_level = 1.0
  7127. self.pagesize = {}
  7128. self.pagesize.update(
  7129. {
  7130. 'Bounds': None,
  7131. 'A0': (841 * mm, 1189 * mm),
  7132. 'A1': (594 * mm, 841 * mm),
  7133. 'A2': (420 * mm, 594 * mm),
  7134. 'A3': (297 * mm, 420 * mm),
  7135. 'A4': (210 * mm, 297 * mm),
  7136. 'A5': (148 * mm, 210 * mm),
  7137. 'A6': (105 * mm, 148 * mm),
  7138. 'A7': (74 * mm, 105 * mm),
  7139. 'A8': (52 * mm, 74 * mm),
  7140. 'A9': (37 * mm, 52 * mm),
  7141. 'A10': (26 * mm, 37 * mm),
  7142. 'B0': (1000 * mm, 1414 * mm),
  7143. 'B1': (707 * mm, 1000 * mm),
  7144. 'B2': (500 * mm, 707 * mm),
  7145. 'B3': (353 * mm, 500 * mm),
  7146. 'B4': (250 * mm, 353 * mm),
  7147. 'B5': (176 * mm, 250 * mm),
  7148. 'B6': (125 * mm, 176 * mm),
  7149. 'B7': (88 * mm, 125 * mm),
  7150. 'B8': (62 * mm, 88 * mm),
  7151. 'B9': (44 * mm, 62 * mm),
  7152. 'B10': (31 * mm, 44 * mm),
  7153. 'C0': (917 * mm, 1297 * mm),
  7154. 'C1': (648 * mm, 917 * mm),
  7155. 'C2': (458 * mm, 648 * mm),
  7156. 'C3': (324 * mm, 458 * mm),
  7157. 'C4': (229 * mm, 324 * mm),
  7158. 'C5': (162 * mm, 229 * mm),
  7159. 'C6': (114 * mm, 162 * mm),
  7160. 'C7': (81 * mm, 114 * mm),
  7161. 'C8': (57 * mm, 81 * mm),
  7162. 'C9': (40 * mm, 57 * mm),
  7163. 'C10': (28 * mm, 40 * mm),
  7164. # American paper sizes
  7165. 'LETTER': (8.5 * inch, 11 * inch),
  7166. 'LEGAL': (8.5 * inch, 14 * inch),
  7167. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7168. # From https://en.wikipedia.org/wiki/Paper_size
  7169. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7170. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7171. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7172. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7173. 'LEDGER': (17 * inch, 11 * inch),
  7174. }
  7175. )
  7176. exported_svg = []
  7177. for obj in obj_selection:
  7178. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7179. scale_factor_x=None, scale_factor_y=None,
  7180. skew_factor_x=None, skew_factor_y=None,
  7181. mirror=None)
  7182. if obj.kind.lower() == 'gerber':
  7183. # color = self.defaults["gerber_plot_fill"][:-2]
  7184. color = obj.fill_color[:-2]
  7185. elif obj.kind.lower() == 'excellon':
  7186. color = '#C40000'
  7187. elif obj.kind.lower() == 'geometry':
  7188. color = self.defaults["global_draw_color"]
  7189. # Change the attributes of the exported SVG
  7190. # We don't need stroke-width
  7191. # We set opacity to maximum
  7192. # We set the colour to WHITE
  7193. root = ET.fromstring(svg_obj)
  7194. for child in root:
  7195. child.set('fill', str(color))
  7196. child.set('opacity', str(transparency_level))
  7197. child.set('stroke', str(color))
  7198. exported_svg.append(ET.tostring(root))
  7199. xmin = Inf
  7200. ymin = Inf
  7201. xmax = -Inf
  7202. ymax = -Inf
  7203. for obj in obj_selection:
  7204. try:
  7205. gxmin, gymin, gxmax, gymax = obj.bounds()
  7206. xmin = min([xmin, gxmin])
  7207. ymin = min([ymin, gymin])
  7208. xmax = max([xmax, gxmax])
  7209. ymax = max([ymax, gymax])
  7210. except Exception as e:
  7211. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7212. # Determine bounding area for svg export
  7213. bounds = [xmin, ymin, xmax, ymax]
  7214. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7215. # This contain the measure units
  7216. uom = obj_selection[0].units.lower()
  7217. # Define a boundary around SVG of about 1.0mm (~39mils)
  7218. if uom in "mm":
  7219. boundary = 1.0
  7220. else:
  7221. boundary = 0.0393701
  7222. # Convert everything to strings for use in the xml doc
  7223. svgwidth = str(size[0] + (2 * boundary))
  7224. svgheight = str(size[1] + (2 * boundary))
  7225. minx = str(bounds[0] - boundary)
  7226. miny = str(bounds[1] + boundary + size[1])
  7227. # Add a SVG Header and footer to the svg output from shapely
  7228. # The transform flips the Y Axis so that everything renders
  7229. # properly within svg apps such as inkscape
  7230. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7231. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7232. svg_header += 'width="' + svgwidth + uom + '" '
  7233. svg_header += 'height="' + svgheight + uom + '" '
  7234. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7235. svg_header += '>'
  7236. svg_header += '<g transform="scale(1,-1)">'
  7237. svg_footer = '</g> </svg>'
  7238. svg_elem = str(svg_header)
  7239. for svg_item in exported_svg:
  7240. svg_elem += str(svg_item)
  7241. svg_elem += str(svg_footer)
  7242. # Parse the xml through a xml parser just to add line feeds
  7243. # and to make it look more pretty for the output
  7244. doc = parse_xml_string(svg_elem)
  7245. doc_final = doc.toprettyxml()
  7246. try:
  7247. if self.defaults['units'].upper() == 'IN':
  7248. unit = inch
  7249. else:
  7250. unit = mm
  7251. doc_final = StringIO(doc_final)
  7252. drawing = svg2rlg(doc_final)
  7253. if p_size == 'Bounds':
  7254. renderPDF.drawToFile(drawing, file_name)
  7255. else:
  7256. if orientation == 'p':
  7257. page_size = portrait(self.pagesize[p_size])
  7258. else:
  7259. page_size = landscape(self.pagesize[p_size])
  7260. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7261. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7262. renderPDF.draw(drawing, my_canvas, 0, 0)
  7263. my_canvas.save()
  7264. except Exception as e:
  7265. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7266. return 'fail'
  7267. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7268. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7269. """
  7270. Exports a Geometry Object to an SVG file.
  7271. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7272. :param filename: Path to the SVG file to save to.
  7273. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7274. :return:
  7275. """
  7276. self.defaults.report_usage("export_svg()")
  7277. if filename is None:
  7278. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7279. is not None else self.defaults["global_last_folder"]
  7280. self.log.debug("export_svg()")
  7281. try:
  7282. obj = self.collection.get_by_name(str(obj_name))
  7283. except Exception:
  7284. # TODO: The return behavior has not been established... should raise exception?
  7285. return "Could not retrieve object: %s" % obj_name
  7286. with self.proc_container.new(_("Exporting SVG")) as proc:
  7287. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7288. # Determine bounding area for svg export
  7289. bounds = obj.bounds()
  7290. size = obj.size()
  7291. # Convert everything to strings for use in the xml doc
  7292. svgwidth = str(size[0])
  7293. svgheight = str(size[1])
  7294. minx = str(bounds[0])
  7295. miny = str(bounds[1] - size[1])
  7296. uom = obj.units.lower()
  7297. # Add a SVG Header and footer to the svg output from shapely
  7298. # The transform flips the Y Axis so that everything renders
  7299. # properly within svg apps such as inkscape
  7300. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7301. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7302. svg_header += 'width="' + svgwidth + uom + '" '
  7303. svg_header += 'height="' + svgheight + uom + '" '
  7304. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7305. svg_header += '<g transform="scale(1,-1)">'
  7306. svg_footer = '</g> </svg>'
  7307. svg_elem = svg_header + exported_svg + svg_footer
  7308. # Parse the xml through a xml parser just to add line feeds
  7309. # and to make it look more pretty for the output
  7310. svgcode = parse_xml_string(svg_elem)
  7311. svgcode = svgcode.toprettyxml()
  7312. try:
  7313. with open(filename, 'w') as fp:
  7314. fp.write(svgcode)
  7315. except PermissionError:
  7316. self.inform.emit('[WARNING] %s' %
  7317. _("Permission denied, saving not possible.\n"
  7318. "Most likely another app is holding the file open and not accessible."))
  7319. return 'fail'
  7320. if self.defaults["global_open_style"] is False:
  7321. self.file_opened.emit("SVG", filename)
  7322. self.file_saved.emit("SVG", filename)
  7323. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7324. def save_source_file(self, obj_name, filename, use_thread=True):
  7325. """
  7326. Exports a FlatCAM Object to an Gerber/Excellon file.
  7327. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7328. :param filename: Path to the Gerber file to save to.
  7329. :param use_thread: if to be run in a separate thread
  7330. :return:
  7331. """
  7332. self.defaults.report_usage("save source file()")
  7333. if filename is None:
  7334. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7335. is not None else self.defaults["global_last_folder"]
  7336. self.log.debug("save source file()")
  7337. obj = self.collection.get_by_name(obj_name)
  7338. file_string = StringIO(obj.source_file)
  7339. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7340. if file_string.getvalue() == '':
  7341. self.inform.emit('[ERROR_NOTCL] %s' %
  7342. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7343. return 'fail'
  7344. try:
  7345. with open(filename, 'w') as file:
  7346. file.writelines('G04*\n')
  7347. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7348. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7349. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7350. file.writelines('G04 Created on : %s*\n' % time_string)
  7351. for line in file_string:
  7352. file.writelines(line)
  7353. except PermissionError:
  7354. self.inform.emit('[WARNING] %s' %
  7355. _("Permission denied, saving not possible.\n"
  7356. "Most likely another app is holding the file open and not accessible."))
  7357. return 'fail'
  7358. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7359. """
  7360. Exports a Excellon Object to an Excellon file.
  7361. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7362. :param filename: Path to the Excellon file to save to.
  7363. :param local_use:
  7364. :param use_thread: if to be run in a separate thread
  7365. :return:
  7366. """
  7367. self.defaults.report_usage("export_excellon()")
  7368. if filename is None:
  7369. if self.defaults["global_last_save_folder"]:
  7370. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7371. else:
  7372. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7373. self.log.debug("export_excellon()")
  7374. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7375. self.defaults["excellon_exp_decimals"]
  7376. )
  7377. if local_use is None:
  7378. try:
  7379. obj = self.collection.get_by_name(str(obj_name))
  7380. except Exception:
  7381. return "Could not retrieve object: %s" % obj_name
  7382. else:
  7383. obj = local_use
  7384. if not isinstance(obj, ExcellonObject):
  7385. self.inform.emit('[ERROR_NOTCL] %s' %
  7386. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7387. return
  7388. # updated units
  7389. eunits = self.defaults["excellon_exp_units"]
  7390. ewhole = self.defaults["excellon_exp_integer"]
  7391. efract = self.defaults["excellon_exp_decimals"]
  7392. ezeros = self.defaults["excellon_exp_zeros"]
  7393. eformat = self.defaults["excellon_exp_format"]
  7394. slot_type = self.defaults["excellon_exp_slot_type"]
  7395. fc_units = self.defaults['units'].upper()
  7396. if fc_units == 'MM':
  7397. factor = 1 if eunits == 'METRIC' else 0.03937
  7398. else:
  7399. factor = 25.4 if eunits == 'METRIC' else 1
  7400. def make_excellon():
  7401. try:
  7402. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7403. header = 'M48\n'
  7404. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7405. (str(self.version), str(self.version_date))
  7406. header += ';Filename: %s' % str(obj_name) + '\n'
  7407. header += ';Created on : %s' % time_str + '\n'
  7408. if eformat == 'dec':
  7409. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7410. header += eunits + '\n'
  7411. for tool in obj.tools:
  7412. if eunits == 'METRIC':
  7413. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7414. tool=str(tool),
  7415. dec=2)
  7416. else:
  7417. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7418. tool=str(tool),
  7419. dec=4)
  7420. else:
  7421. if ezeros == 'LZ':
  7422. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7423. form='ndec', e_zeros='LZ', factor=factor,
  7424. slot_type=slot_type)
  7425. header += '%s,%s\n' % (eunits, 'LZ')
  7426. header += format_exc
  7427. for tool in obj.tools:
  7428. if eunits == 'METRIC':
  7429. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7430. tool=str(tool),
  7431. dec=2)
  7432. else:
  7433. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7434. tool=str(tool),
  7435. dec=4)
  7436. else:
  7437. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7438. form='ndec', e_zeros='TZ', factor=factor,
  7439. slot_type=slot_type)
  7440. header += '%s,%s\n' % (eunits, 'TZ')
  7441. header += format_exc
  7442. for tool in obj.tools:
  7443. if eunits == 'METRIC':
  7444. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7445. tool=str(tool),
  7446. dec=2)
  7447. else:
  7448. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7449. tool=str(tool),
  7450. dec=4)
  7451. header += '%\n'
  7452. footer = 'M30\n'
  7453. exported_excellon = header
  7454. exported_excellon += excellon_code
  7455. exported_excellon += footer
  7456. if local_use is None:
  7457. try:
  7458. with open(filename, 'w') as fp:
  7459. fp.write(exported_excellon)
  7460. except PermissionError:
  7461. self.inform.emit('[WARNING] %s' %
  7462. _("Permission denied, saving not possible.\n"
  7463. "Most likely another app is holding the file open and not accessible."))
  7464. return 'fail'
  7465. if self.defaults["global_open_style"] is False:
  7466. self.file_opened.emit("Excellon", filename)
  7467. self.file_saved.emit("Excellon", filename)
  7468. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7469. else:
  7470. return exported_excellon
  7471. except Exception as e:
  7472. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7473. return 'fail'
  7474. if use_thread is True:
  7475. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7476. def job_thread_exc(app_obj):
  7477. ret = make_excellon()
  7478. if ret == 'fail':
  7479. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7480. return
  7481. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7482. else:
  7483. eret = make_excellon()
  7484. if eret == 'fail':
  7485. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7486. return 'fail'
  7487. if local_use is not None:
  7488. return eret
  7489. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7490. """
  7491. Exports a Gerber Object to an Gerber file.
  7492. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7493. :param filename: Path to the Gerber file to save to.
  7494. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7495. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7496. :param use_thread: if to be run in a separate thread
  7497. :return:
  7498. """
  7499. self.defaults.report_usage("export_gerber()")
  7500. if filename is None:
  7501. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7502. is not None else self.defaults["global_last_folder"]
  7503. self.log.debug("export_gerber()")
  7504. if local_use is None:
  7505. try:
  7506. obj = self.collection.get_by_name(str(obj_name))
  7507. except Exception:
  7508. return "Could not retrieve object: %s" % obj_name
  7509. else:
  7510. obj = local_use
  7511. # updated units
  7512. gunits = self.defaults["gerber_exp_units"]
  7513. gwhole = self.defaults["gerber_exp_integer"]
  7514. gfract = self.defaults["gerber_exp_decimals"]
  7515. gzeros = self.defaults["gerber_exp_zeros"]
  7516. fc_units = self.defaults['units'].upper()
  7517. if fc_units == 'MM':
  7518. factor = 1 if gunits == 'MM' else 0.03937
  7519. else:
  7520. factor = 25.4 if gunits == 'MM' else 1
  7521. def make_gerber():
  7522. try:
  7523. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7524. header = 'G04*\n'
  7525. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7526. (str(self.version), str(self.version_date))
  7527. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7528. header += 'G04 Created on : %s*' % time_str + '\n'
  7529. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7530. header += "%MO{units}*%\n".format(units=gunits)
  7531. for apid in obj.apertures:
  7532. if obj.apertures[apid]['type'] == 'C':
  7533. header += "%ADD{apid}{type},{size}*%\n".format(
  7534. apid=str(apid),
  7535. type='C',
  7536. size=(factor * obj.apertures[apid]['size'])
  7537. )
  7538. elif obj.apertures[apid]['type'] == 'R':
  7539. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7540. apid=str(apid),
  7541. type='R',
  7542. width=(factor * obj.apertures[apid]['width']),
  7543. height=(factor * obj.apertures[apid]['height'])
  7544. )
  7545. elif obj.apertures[apid]['type'] == 'O':
  7546. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7547. apid=str(apid),
  7548. type='O',
  7549. width=(factor * obj.apertures[apid]['width']),
  7550. height=(factor * obj.apertures[apid]['height'])
  7551. )
  7552. header += '\n'
  7553. # obsolete units but some software may need it
  7554. if gunits == 'IN':
  7555. header += 'G70*\n'
  7556. else:
  7557. header += 'G71*\n'
  7558. # Absolute Mode
  7559. header += 'G90*\n'
  7560. header += 'G01*\n'
  7561. # positive polarity
  7562. header += '%LPD*%\n'
  7563. footer = 'M02*\n'
  7564. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7565. exported_gerber = header
  7566. exported_gerber += gerber_code
  7567. exported_gerber += footer
  7568. if local_use is None:
  7569. try:
  7570. with open(filename, 'w') as fp:
  7571. fp.write(exported_gerber)
  7572. except PermissionError:
  7573. self.inform.emit('[WARNING] %s' %
  7574. _("Permission denied, saving not possible.\n"
  7575. "Most likely another app is holding the file open and not accessible."))
  7576. return 'fail'
  7577. if self.defaults["global_open_style"] is False:
  7578. self.file_opened.emit("Gerber", filename)
  7579. self.file_saved.emit("Gerber", filename)
  7580. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7581. else:
  7582. return exported_gerber
  7583. except Exception as e:
  7584. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7585. return 'fail'
  7586. if use_thread is True:
  7587. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7588. def job_thread_grb(app_obj):
  7589. ret = make_gerber()
  7590. if ret == 'fail':
  7591. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7592. return
  7593. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7594. else:
  7595. gret = make_gerber()
  7596. if gret == 'fail':
  7597. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7598. return 'fail'
  7599. if local_use is not None:
  7600. return gret
  7601. def export_dxf(self, obj_name, filename, use_thread=True):
  7602. """
  7603. Exports a Geometry Object to an DXF file.
  7604. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7605. :param filename: Path to the DXF file to save to.
  7606. :param use_thread: if to be run in a separate thread
  7607. :return:
  7608. """
  7609. self.defaults.report_usage("export_dxf()")
  7610. if filename is None:
  7611. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7612. is not None else self.defaults["global_last_folder"]
  7613. self.log.debug("export_dxf()")
  7614. try:
  7615. obj = self.collection.get_by_name(str(obj_name))
  7616. except Exception:
  7617. # TODO: The return behavior has not been established... should raise exception?
  7618. return "Could not retrieve object: %s" % obj_name
  7619. def make_dxf():
  7620. try:
  7621. dxf_code = obj.export_dxf()
  7622. dxf_code.saveas(filename)
  7623. if self.defaults["global_open_style"] is False:
  7624. self.file_opened.emit("DXF", filename)
  7625. self.file_saved.emit("DXF", filename)
  7626. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7627. except Exception:
  7628. return 'fail'
  7629. if use_thread is True:
  7630. with self.proc_container.new(_("Exporting DXF")) as proc:
  7631. def job_thread_exc(app_obj):
  7632. ret_dxf_val = make_dxf()
  7633. if ret_dxf_val == 'fail':
  7634. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7635. return
  7636. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7637. else:
  7638. ret = make_dxf()
  7639. if ret == 'fail':
  7640. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7641. return
  7642. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7643. """
  7644. Adds a new Geometry Object to the projects and populates
  7645. it with shapes extracted from the SVG file.
  7646. :param plot: If True then the resulting object will be plotted on canvas
  7647. :param filename: Path to the SVG file.
  7648. :param geo_type: Type of FlatCAM object that will be created from SVG
  7649. :param outname: The name given to the resulting FlatCAM object
  7650. :return:
  7651. """
  7652. self.defaults.report_usage("import_svg()")
  7653. log.debug("App.import_svg()")
  7654. obj_type = ""
  7655. if geo_type is None or geo_type == "geometry":
  7656. obj_type = "geometry"
  7657. elif geo_type == "gerber":
  7658. obj_type = "gerber"
  7659. else:
  7660. self.inform.emit('[ERROR_NOTCL] %s' %
  7661. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7662. return
  7663. units = self.defaults['units'].upper()
  7664. def obj_init(geo_obj, app_obj):
  7665. geo_obj.import_svg(filename, obj_type, units=units)
  7666. geo_obj.multigeo = False
  7667. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7668. with self.proc_container.new(_("Importing SVG")) as proc:
  7669. # Object name
  7670. name = outname or filename.split('/')[-1].split('\\')[-1]
  7671. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7672. if ret == 'fail':
  7673. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7674. return 'fail'
  7675. # Register recent file
  7676. self.file_opened.emit("svg", filename)
  7677. # GUI feedback
  7678. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7679. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7680. """
  7681. Adds a new Geometry Object to the projects and populates
  7682. it with shapes extracted from the DXF file.
  7683. :param filename: Path to the DXF file.
  7684. :param geo_type: Type of FlatCAM object that will be created from DXF
  7685. :param outname: Name for the imported Geometry
  7686. :param plot: If True then the resulting object will be plotted on canvas
  7687. :return:
  7688. """
  7689. self.defaults.report_usage("import_dxf()")
  7690. obj_type = ""
  7691. if geo_type is None or geo_type == "geometry":
  7692. obj_type = "geometry"
  7693. elif geo_type == "gerber":
  7694. obj_type = geo_type
  7695. else:
  7696. self.inform.emit('[ERROR_NOTCL] %s' %
  7697. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7698. return
  7699. units = self.defaults['units'].upper()
  7700. def obj_init(geo_obj, app_obj):
  7701. geo_obj.import_dxf(filename, obj_type, units=units)
  7702. geo_obj.multigeo = False
  7703. with self.proc_container.new(_("Importing DXF")):
  7704. # Object name
  7705. name = outname or filename.split('/')[-1].split('\\')[-1]
  7706. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7707. if ret == 'fail':
  7708. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7709. return 'fail'
  7710. # Register recent file
  7711. self.file_opened.emit("dxf", filename)
  7712. # GUI feedback
  7713. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7714. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7715. """
  7716. Opens a Gerber file, parses it and creates a new object for
  7717. it in the program. Thread-safe.
  7718. :param outname: Name of the resulting object. None causes the
  7719. name to be that of the file. Str.
  7720. :param filename: Gerber file filename
  7721. :type filename: str
  7722. :param plot: boolean, to plot or not the resulting object
  7723. :param from_tcl: True if run from Tcl Shell
  7724. :return: None
  7725. """
  7726. # How the object should be initialized
  7727. def obj_init(gerber_obj, app_obj):
  7728. assert isinstance(gerber_obj, GerberObject), \
  7729. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7730. # Opening the file happens here
  7731. try:
  7732. gerber_obj.parse_file(filename)
  7733. except IOError:
  7734. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7735. return "fail"
  7736. except ParseError as err:
  7737. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7738. app_obj.log.error(str(err))
  7739. return "fail"
  7740. except Exception as e:
  7741. log.debug("App.open_gerber() --> %s" % str(e))
  7742. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7743. msg += traceback.format_exc()
  7744. app_obj.inform.emit(msg)
  7745. return "fail"
  7746. if gerber_obj.is_empty():
  7747. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7748. _("Object is not Gerber file or empty. Aborting object creation."))
  7749. return "fail"
  7750. App.log.debug("open_gerber()")
  7751. with self.proc_container.new(_("Opening Gerber")):
  7752. # Object name
  7753. name = outname or filename.split('/')[-1].split('\\')[-1]
  7754. # # ## Object creation # ##
  7755. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7756. if ret_val == 'fail':
  7757. if from_tcl:
  7758. filename = self.defaults['global_tcl_path'] + '/' + name
  7759. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7760. if ret_val == 'fail':
  7761. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7762. return 'fail'
  7763. # Register recent file
  7764. self.file_opened.emit("gerber", filename)
  7765. # GUI feedback
  7766. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7767. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7768. """
  7769. Opens an Excellon file, parses it and creates a new object for
  7770. it in the program. Thread-safe.
  7771. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7772. :param filename: Excellon file filename
  7773. :type filename: str
  7774. :param plot: boolean, to plot or not the resulting object
  7775. :param from_tcl: True if run from Tcl Shell
  7776. :return: None
  7777. """
  7778. App.log.debug("open_excellon()")
  7779. # How the object should be initialized
  7780. def obj_init(excellon_obj, app_obj):
  7781. try:
  7782. ret = excellon_obj.parse_file(filename=filename)
  7783. if ret == "fail":
  7784. log.debug("Excellon parsing failed.")
  7785. self.inform.emit('[ERROR_NOTCL] %s' %
  7786. _("This is not Excellon file."))
  7787. return "fail"
  7788. except IOError:
  7789. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7790. (_("Cannot open file"), filename))
  7791. log.debug("Could not open Excellon object.")
  7792. return "fail"
  7793. except Exception:
  7794. msg = '[ERROR_NOTCL] %s' % \
  7795. _("An internal error has occurred. See shell.\n")
  7796. msg += traceback.format_exc()
  7797. app_obj.inform.emit(msg)
  7798. return "fail"
  7799. ret = excellon_obj.create_geometry()
  7800. if ret == 'fail':
  7801. log.debug("Could not create geometry for Excellon object.")
  7802. return "fail"
  7803. for tool in excellon_obj.tools:
  7804. if excellon_obj.tools[tool]['solid_geometry']:
  7805. return
  7806. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7807. return "fail"
  7808. with self.proc_container.new(_("Opening Excellon.")):
  7809. # Object name
  7810. name = outname or filename.split('/')[-1].split('\\')[-1]
  7811. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7812. if ret_val == 'fail':
  7813. if from_tcl:
  7814. filename = self.defaults['global_tcl_path'] + '/' + name
  7815. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7816. if ret_val == 'fail':
  7817. self.inform.emit('[ERROR_NOTCL] %s' %
  7818. _('Open Excellon file failed. Probable not an Excellon file.'))
  7819. return
  7820. # Register recent file
  7821. self.file_opened.emit("excellon", filename)
  7822. # GUI feedback
  7823. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7824. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7825. """
  7826. Opens a G-gcode file, parses it and creates a new object for
  7827. it in the program. Thread-safe.
  7828. :param filename: G-code file filename
  7829. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7830. :param force_parsing:
  7831. :param plot: If True plot the object on canvas
  7832. :param from_tcl: True if run from Tcl Shell
  7833. :return: None
  7834. """
  7835. App.log.debug("open_gcode()")
  7836. # How the object should be initialized
  7837. def obj_init(job_obj, app_obj_):
  7838. """
  7839. :param job_obj: the resulting object
  7840. :type app_obj_: App
  7841. """
  7842. assert isinstance(app_obj_, App), \
  7843. "Initializer expected App, got %s" % type(app_obj_)
  7844. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7845. try:
  7846. f = open(filename)
  7847. gcode = f.read()
  7848. f.close()
  7849. except IOError:
  7850. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7851. return "fail"
  7852. job_obj.gcode = gcode
  7853. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7854. if gcode_ret == "fail":
  7855. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7856. return "fail"
  7857. job_obj.create_geometry()
  7858. with self.proc_container.new(_("Opening G-Code.")):
  7859. # Object name
  7860. name = outname or filename.split('/')[-1].split('\\')[-1]
  7861. # New object creation and file processing
  7862. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7863. if ret_val == 'fail':
  7864. if from_tcl:
  7865. filename = self.defaults['global_tcl_path'] + '/' + name
  7866. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7867. if ret_val == 'fail':
  7868. self.inform.emit('[ERROR_NOTCL] %s' %
  7869. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7870. "Try to load it from File menu.\n "
  7871. "Attempting to create a FlatCAM CNCJob Object from "
  7872. "G-Code file failed during processing"))
  7873. return "fail"
  7874. # Register recent file
  7875. self.file_opened.emit("cncjob", filename)
  7876. # GUI feedback
  7877. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7878. def open_hpgl2(self, filename, outname=None):
  7879. """
  7880. Opens a HPGL2 file, parses it and creates a new object for
  7881. it in the program. Thread-safe.
  7882. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7883. :param filename: HPGL2 file filename
  7884. :return: None
  7885. """
  7886. filename = filename
  7887. # How the object should be initialized
  7888. def obj_init(geo_obj, app_obj):
  7889. assert isinstance(geo_obj, GeometryObject), \
  7890. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7891. # Opening the file happens here
  7892. obj = HPGL2(self)
  7893. try:
  7894. HPGL2.parse_file(obj, filename)
  7895. except IOError:
  7896. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7897. return "fail"
  7898. except ParseError as err:
  7899. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7900. app_obj.log.error(str(err))
  7901. return "fail"
  7902. except Exception as e:
  7903. log.debug("App.open_hpgl2() --> %s" % str(e))
  7904. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7905. msg += traceback.format_exc()
  7906. app_obj.inform.emit(msg)
  7907. return "fail"
  7908. geo_obj.multigeo = True
  7909. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7910. geo_obj.tools = deepcopy(obj.tools)
  7911. geo_obj.source_file = deepcopy(obj.source_file)
  7912. del obj
  7913. if not geo_obj.solid_geometry:
  7914. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7915. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7916. return "fail"
  7917. App.log.debug("open_hpgl2()")
  7918. with self.proc_container.new(_("Opening HPGL2")):
  7919. # Object name
  7920. name = outname or filename.split('/')[-1].split('\\')[-1]
  7921. # # ## Object creation # ##
  7922. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7923. if ret == 'fail':
  7924. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7925. return 'fail'
  7926. # Register recent file
  7927. self.file_opened.emit("geometry", filename)
  7928. # GUI feedback
  7929. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7930. def open_script(self, filename, outname=None, silent=False):
  7931. """
  7932. Opens a Script file, parses it and creates a new object for
  7933. it in the program. Thread-safe.
  7934. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7935. :param filename: Script file filename
  7936. :param silent: If True there will be no messages printed to StatusBar
  7937. :return: None
  7938. """
  7939. def obj_init(script_obj, app_obj):
  7940. assert isinstance(script_obj, ScriptObject), \
  7941. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7942. if silent is False:
  7943. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7944. try:
  7945. script_obj.parse_file(filename)
  7946. except IOError:
  7947. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7948. return "fail"
  7949. except ParseError as err:
  7950. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7951. app_obj.log.error(str(err))
  7952. return "fail"
  7953. except Exception as e:
  7954. log.debug("App.open_script() -> %s" % str(e))
  7955. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7956. msg += traceback.format_exc()
  7957. app_obj.inform.emit(msg)
  7958. return "fail"
  7959. App.log.debug("open_script()")
  7960. with self.proc_container.new(_("Opening TCL Script...")):
  7961. # Object name
  7962. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7963. # Object creation
  7964. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7965. if ret_val == 'fail':
  7966. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7967. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7968. if ret_val == 'fail':
  7969. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7970. return 'fail'
  7971. # Register recent file
  7972. self.file_opened.emit("script", filename)
  7973. # GUI feedback
  7974. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7975. def open_config_file(self, filename, run_from_arg=None):
  7976. """
  7977. Loads a config file from the specified file.
  7978. :param filename: Name of the file from which to load.
  7979. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7980. :return: None
  7981. """
  7982. App.log.debug("Opening config file: " + filename)
  7983. if run_from_arg:
  7984. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7985. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7986. _("Opening FlatCAM Config file.")),
  7987. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7988. color=QtGui.QColor("gray"))
  7989. # # add the tab if it was closed
  7990. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7991. # # first clear previous text in text editor (if any)
  7992. # self.ui.text_editor_tab.code_editor.clear()
  7993. #
  7994. # # Switch plot_area to CNCJob tab
  7995. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7996. # close the Code editor if already open
  7997. if self.toggle_codeeditor:
  7998. self.on_toggle_code_editor()
  7999. self.on_toggle_code_editor()
  8000. try:
  8001. if filename:
  8002. f = QtCore.QFile(filename)
  8003. if f.open(QtCore.QIODevice.ReadOnly):
  8004. stream = QtCore.QTextStream(f)
  8005. code_edited = stream.readAll()
  8006. self.text_editor_tab.code_editor.setPlainText(code_edited)
  8007. f.close()
  8008. except IOError:
  8009. App.log.error("Failed to open config file: %s" % filename)
  8010. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8011. (_("Failed to open config file"), filename))
  8012. return
  8013. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8014. """
  8015. Loads a project from the specified file.
  8016. 1) Loads and parses file
  8017. 2) Registers the file as recently opened.
  8018. 3) Calls on_file_new()
  8019. 4) Updates options
  8020. 5) Calls new_object() with the object's from_dict() as init method.
  8021. 6) Calls plot_all() if plot=True
  8022. :param filename: Name of the file from which to load.
  8023. :param run_from_arg: True if run for arguments
  8024. :param plot: If True plot all objects in the project
  8025. :param cli: Run from command line
  8026. :param from_tcl: True if run from Tcl Sehll
  8027. :return: None
  8028. """
  8029. App.log.debug("Opening project: " + filename)
  8030. # block autosaving while a project is loaded
  8031. self.block_autosave = True
  8032. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8033. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8034. if cli is None:
  8035. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8036. if run_from_arg:
  8037. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8038. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8039. _("Opening FlatCAM Project file.")),
  8040. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8041. color=QtGui.QColor("gray"))
  8042. # Open and parse an uncompressed Project file
  8043. try:
  8044. f = open(filename, 'r')
  8045. except IOError:
  8046. if from_tcl:
  8047. name = filename.split('/')[-1].split('\\')[-1]
  8048. filename = self.defaults['global_tcl_path'] + '/' + name
  8049. try:
  8050. f = open(filename, 'r')
  8051. except IOError:
  8052. log.error("Failed to open project file: %s" % filename)
  8053. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8054. return
  8055. else:
  8056. log.error("Failed to open project file: %s" % filename)
  8057. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8058. return
  8059. try:
  8060. d = json.load(f, object_hook=dict2obj)
  8061. except Exception as e:
  8062. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8063. (filename, str(e)))
  8064. f.close()
  8065. # Open and parse a compressed Project file
  8066. try:
  8067. with lzma.open(filename) as f:
  8068. file_content = f.read().decode('utf-8')
  8069. d = json.loads(file_content, object_hook=dict2obj)
  8070. except Exception as e:
  8071. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8072. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8073. return
  8074. # Clear the current project
  8075. # # NOT THREAD SAFE # ##
  8076. if run_from_arg is True:
  8077. pass
  8078. elif cli is True:
  8079. self.delete_selection_shape()
  8080. else:
  8081. self.on_file_new()
  8082. # Project options
  8083. self.options.update(d['options'])
  8084. self.project_filename = filename
  8085. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8086. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8087. if cli is None:
  8088. self.set_screen_units(self.options["units"])
  8089. # Re create objects
  8090. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8091. for obj in d['objs']:
  8092. try:
  8093. def obj_init(obj_inst, app_inst):
  8094. obj_inst.from_dict(obj)
  8095. App.log.debug("Recreating from opened project an %s object: %s" %
  8096. (obj['kind'].capitalize(), obj['options']['name']))
  8097. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8098. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8099. if cli is None:
  8100. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8101. obj['kind'].upper(),
  8102. obj['options']['name']
  8103. )
  8104. )
  8105. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8106. except Exception as e:
  8107. print('App.open_project() --> ' + str(e))
  8108. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8109. self.should_we_save = False
  8110. self.file_opened.emit("project", filename)
  8111. # restore autosaving after a project was loaded
  8112. self.block_autosave = False
  8113. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8114. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8115. if cli is None:
  8116. self.set_ui_title(name=self.project_filename)
  8117. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8118. def plot_all(self, fit_view=True, use_thread=True):
  8119. """
  8120. Re-generates all plots from all objects.
  8121. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8122. :param use_thread: if True will use threading for plotting the objects
  8123. :return: None
  8124. """
  8125. self.log.debug("Plot_all()")
  8126. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8127. for plot_obj in self.collection.get_list():
  8128. def worker_task(obj):
  8129. with self.proc_container.new("Plotting"):
  8130. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8131. if fit_view is True:
  8132. self.object_plotted.emit(obj)
  8133. if use_thread is True:
  8134. # Send to worker
  8135. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8136. else:
  8137. worker_task(plot_obj)
  8138. def register_folder(self, filename):
  8139. """
  8140. Register the last folder used by the app to open something
  8141. :param filename: the last folder is extracted from the filename
  8142. :return: None
  8143. """
  8144. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8145. def register_save_folder(self, filename):
  8146. """
  8147. Register the last folder used by the app to save something
  8148. :param filename: the last folder is extracted from the filename
  8149. :return: None
  8150. """
  8151. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8152. # def set_progress_bar(self, percentage, text=""):
  8153. # """
  8154. # Set a progress bar to a value (percentage)
  8155. #
  8156. # :param percentage: Value set to the progressbar
  8157. # :param text: Not used
  8158. # :return: None
  8159. # """
  8160. # self.ui.progress_bar.setValue(int(percentage))
  8161. def setup_recent_items(self):
  8162. """
  8163. Setup a dictionary with the recent files accessed, organized by type
  8164. :return:
  8165. """
  8166. icons = {
  8167. "gerber": self.resource_location + "/flatcam_icon16.png",
  8168. "excellon": self.resource_location + "/drill16.png",
  8169. 'geometry': self.resource_location + "/geometry16.png",
  8170. "cncjob": self.resource_location + "/cnc16.png",
  8171. "script": self.resource_location + "/script_new24.png",
  8172. "document": self.resource_location + "/notes16_1.png",
  8173. "project": self.resource_location + "/project16.png",
  8174. "svg": self.resource_location + "/geometry16.png",
  8175. "dxf": self.resource_location + "/dxf16.png",
  8176. "pdf": self.resource_location + "/pdf32.png",
  8177. "image": self.resource_location + "/image16.png"
  8178. }
  8179. try:
  8180. image_opener = self.image_tool.import_image
  8181. except AttributeError:
  8182. image_opener = None
  8183. openers = {
  8184. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8185. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8186. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8187. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8188. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8189. "document": None,
  8190. 'project': self.open_project,
  8191. 'svg': self.import_svg,
  8192. 'dxf': self.import_dxf,
  8193. 'image': image_opener,
  8194. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8195. }
  8196. # Open recent file for files
  8197. try:
  8198. f = open(self.data_path + '/recent.json')
  8199. except IOError:
  8200. App.log.error("Failed to load recent item list.")
  8201. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8202. return
  8203. try:
  8204. self.recent = json.load(f)
  8205. except json.errors.JSONDecodeError:
  8206. App.log.error("Failed to parse recent item list.")
  8207. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8208. f.close()
  8209. return
  8210. f.close()
  8211. # Open recent file for projects
  8212. try:
  8213. fp = open(self.data_path + '/recent_projects.json')
  8214. except IOError:
  8215. App.log.error("Failed to load recent project item list.")
  8216. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8217. return
  8218. try:
  8219. self.recent_projects = json.load(fp)
  8220. except json.errors.JSONDecodeError:
  8221. App.log.error("Failed to parse recent project item list.")
  8222. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8223. fp.close()
  8224. return
  8225. fp.close()
  8226. # Closure needed to create callbacks in a loop.
  8227. # Otherwise late binding occurs.
  8228. def make_callback(func, fname):
  8229. def opener():
  8230. func(fname)
  8231. return opener
  8232. def reset_recent_files():
  8233. # Reset menu
  8234. self.ui.recent.clear()
  8235. self.recent = []
  8236. try:
  8237. ff = open(self.data_path + '/recent.json', 'w')
  8238. except IOError:
  8239. App.log.error("Failed to open recent items file for writing.")
  8240. return
  8241. json.dump(self.recent, ff)
  8242. def reset_recent_projects():
  8243. # Reset menu
  8244. self.ui.recent_projects.clear()
  8245. self.recent_projects = []
  8246. try:
  8247. frp = open(self.data_path + '/recent_projects.json', 'w')
  8248. except IOError:
  8249. App.log.error("Failed to open recent projects items file for writing.")
  8250. return
  8251. json.dump(self.recent, frp)
  8252. # Reset menu
  8253. self.ui.recent.clear()
  8254. self.ui.recent_projects.clear()
  8255. # Create menu items for projects
  8256. for recent in self.recent_projects:
  8257. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8258. if recent['kind'] == 'project':
  8259. try:
  8260. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8261. # Attach callback
  8262. o = make_callback(openers[recent["kind"]], recent['filename'])
  8263. action.triggered.connect(o)
  8264. self.ui.recent_projects.addAction(action)
  8265. except KeyError:
  8266. App.log.error("Unsupported file type: %s" % recent["kind"])
  8267. # Last action in Recent Files menu is one that Clear the content
  8268. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8269. (_("Clear Recent projects")), self)
  8270. clear_action_proj.triggered.connect(reset_recent_projects)
  8271. self.ui.recent_projects.addSeparator()
  8272. self.ui.recent_projects.addAction(clear_action_proj)
  8273. # Create menu items for files
  8274. for recent in self.recent:
  8275. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8276. if recent['kind'] != 'project':
  8277. try:
  8278. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8279. # Attach callback
  8280. o = make_callback(openers[recent["kind"]], recent['filename'])
  8281. action.triggered.connect(o)
  8282. self.ui.recent.addAction(action)
  8283. except KeyError:
  8284. App.log.error("Unsupported file type: %s" % recent["kind"])
  8285. # Last action in Recent Files menu is one that Clear the content
  8286. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8287. (_("Clear Recent files")), self)
  8288. clear_action.triggered.connect(reset_recent_files)
  8289. self.ui.recent.addSeparator()
  8290. self.ui.recent.addAction(clear_action)
  8291. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8292. # self.ui.menufilerecent.set_submenu(recent_menu)
  8293. # recent_menu.show_all()
  8294. # self.ui.recent.show()
  8295. self.log.debug("Recent items list has been populated.")
  8296. def setup_component_editor(self):
  8297. """
  8298. Default text for the Selected tab when is not taken by the Object UI.
  8299. :return:
  8300. """
  8301. # label = QtWidgets.QLabel("Choose an item from Project")
  8302. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8303. sel_title = QtWidgets.QTextEdit(
  8304. _('<b>Shortcut Key List</b>'))
  8305. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8306. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8307. f_settings = QSettings("Open Source", "FlatCAM")
  8308. if f_settings.contains("notebook_font_size"):
  8309. fsize = f_settings.value('notebook_font_size', type=int)
  8310. else:
  8311. fsize = 12
  8312. tsize = fsize + int(fsize / 2)
  8313. # selected_text = (_('''
  8314. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8315. # </p>
  8316. #
  8317. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8318. # The normal flow when working in FlatCAM is the following:</span></p>
  8319. #
  8320. # <ol>
  8321. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8322. # file into
  8323. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8324. # even dragging and dropping the files on the GUI.<br />
  8325. # <br />
  8326. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8327. # drop of the
  8328. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8329. # &nbsp;</li>
  8330. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8331. # and then
  8332. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8333. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8334. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8335. # <br />
  8336. # If the selection of the object is done on the canvas by single click instead, and the
  8337. # <strong>SELECTED TAB</strong>
  8338. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8339. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8340. # it even if it was out of focus.<br />
  8341. # <br />
  8342. # You can change the parameters in this screen and the flow direction is like this:<br />
  8343. # <br />
  8344. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8345. # <strong> Geometry Object
  8346. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8347. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8348. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8349. # </ol>
  8350. #
  8351. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8352. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8353. # <strong>F3</strong>.</span></p>
  8354. #
  8355. # ''').format(fsize=fsize, tsize=tsize))
  8356. selected_text = '''
  8357. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8358. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8359. {s1}</span></p>
  8360. <ol>
  8361. <li><span style="font-size:{fsize}px">{s2}<br />
  8362. <br />
  8363. {s3}</span><br />
  8364. &nbsp;</li>
  8365. <li><span style="font-size:{fsize}px">{s4}<br />
  8366. &nbsp;</li>
  8367. <br />
  8368. <li><span style="font-size:{fsize}px">{s5}<br />
  8369. &nbsp;</li>
  8370. <br />
  8371. <li><span style="font-size:{fsize}px">{s6}<br />
  8372. <br />
  8373. {s7}</span></li>
  8374. </ol>
  8375. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8376. '''.format(
  8377. title=_("Selected Tab - Choose an Item from Project Tab"),
  8378. subtitle=_("Details"),
  8379. s1=_("The normal flow when working in FlatCAM is the following:"),
  8380. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8381. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8382. "files on the GUI."),
  8383. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8384. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8385. "actions offered within the app."),
  8386. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8387. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8388. "SELECTED TAB will be updated with the object properties according to its kind: "
  8389. "Gerber, Excellon, Geometry or CNCJob object."),
  8390. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8391. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8392. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8393. "the SELECTED TAB and populate it even if it was out of focus."),
  8394. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8395. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8396. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8397. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8398. "(again, done in SELECTED TAB) --> Save GCode."),
  8399. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8400. "or through its own key shortcut: <b>F3</b>."),
  8401. tsize=tsize,
  8402. fsize=fsize
  8403. )
  8404. sel_title.setText(selected_text)
  8405. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8406. self.ui.selected_scroll_area.setWidget(sel_title)
  8407. def setup_obj_classes(self):
  8408. """
  8409. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8410. class.
  8411. :return: None
  8412. """
  8413. FlatCAMObj.app = self
  8414. ObjectCollection.app = self
  8415. Gerber.app = self
  8416. Excellon.app = self
  8417. Geometry.app = self
  8418. CNCjob.app = self
  8419. FCProcess.app = self
  8420. FCProcessContainer.app = self
  8421. OptionsGroupUI.app = self
  8422. def version_check(self):
  8423. """
  8424. Checks for the latest version of the program. Alerts the
  8425. user if theirs is outdated. This method is meant to be run
  8426. in a separate thread.
  8427. :return: None
  8428. """
  8429. self.log.debug("version_check()")
  8430. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8431. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8432. App.version_url,
  8433. str(self.defaults['global_serial']),
  8434. str(self.version),
  8435. str(self.os),
  8436. urllib.parse.urlencode(self.defaults["global_stats"])
  8437. )
  8438. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8439. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8440. # urllib.parse.urlencode(self.defaults["global_stats"])
  8441. else:
  8442. # no_stats dict; just so it won't break things on website
  8443. no_ststs_dict = {}
  8444. no_ststs_dict["global_ststs"] = {}
  8445. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8446. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8447. App.log.debug("Checking for updates @ %s" % full_url)
  8448. # ## Get the data
  8449. try:
  8450. f = urllib.request.urlopen(full_url)
  8451. except Exception:
  8452. # App.log.warning("Failed checking for latest version. Could not connect.")
  8453. self.log.warning("Failed checking for latest version. Could not connect.")
  8454. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8455. return
  8456. try:
  8457. data = json.load(f)
  8458. except Exception as e:
  8459. App.log.error("Could not parse information about latest version.")
  8460. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8461. App.log.debug("json.load(): %s" % str(e))
  8462. f.close()
  8463. return
  8464. f.close()
  8465. # ## Latest version?
  8466. if self.version >= data["version"]:
  8467. App.log.debug("FlatCAM is up to date!")
  8468. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8469. return
  8470. App.log.debug("Newer version available.")
  8471. self.message.emit(
  8472. _("Newer Version Available"),
  8473. '%s<br><br>><b>%s</b><br>%s' % (
  8474. _("There is a newer version of FlatCAM available for download:"),
  8475. str(data["name"]),
  8476. str(data["message"])
  8477. ),
  8478. _("info")
  8479. )
  8480. def on_plotcanvas_setup(self, container=None):
  8481. """
  8482. This is doing the setup for the plot area (canvas).
  8483. :param container: QT Widget where to install the canvas
  8484. :return: None
  8485. """
  8486. if container:
  8487. plot_container = container
  8488. else:
  8489. plot_container = self.ui.right_layout
  8490. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8491. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8492. self.is_legacy = True
  8493. self.defaults["global_graphic_engine"] = "2D"
  8494. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8495. else:
  8496. try:
  8497. self.plotcanvas = PlotCanvas(plot_container, self)
  8498. except Exception as er:
  8499. msg_txt = traceback.format_exc()
  8500. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8501. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8502. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8503. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8504. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8505. msg += msg_txt
  8506. self.inform.emit(msg)
  8507. return 'fail'
  8508. # So it can receive key presses
  8509. self.plotcanvas.native.setFocus()
  8510. if self.is_legacy is False:
  8511. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8512. # Set the mouse button for panning
  8513. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8514. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8515. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8516. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8517. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8518. # Keys over plot enabled
  8519. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8520. if self.defaults['global_cursor_type'] == 'small':
  8521. self.app_cursor = self.plotcanvas.new_cursor()
  8522. else:
  8523. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8524. if self.ui.grid_snap_btn.isChecked():
  8525. self.app_cursor.enabled = True
  8526. else:
  8527. self.app_cursor.enabled = False
  8528. if self.is_legacy is False:
  8529. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8530. else:
  8531. # will use the default Matplotlib axes
  8532. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8533. def on_zoom_fit(self, event):
  8534. """
  8535. Callback for zoom-fit request. This can be either from the corresponding
  8536. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8537. with axes limits from the geometry bounds of all objects.
  8538. :param event: Ignored.
  8539. :return: None
  8540. """
  8541. if self.is_legacy is False:
  8542. self.plotcanvas.fit_view()
  8543. else:
  8544. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8545. width = xmax - xmin
  8546. height = ymax - ymin
  8547. xmin -= 0.05 * width
  8548. xmax += 0.05 * width
  8549. ymin -= 0.05 * height
  8550. ymax += 0.05 * height
  8551. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8552. def on_zoom_in(self):
  8553. """
  8554. Callback for zoom-in request.
  8555. :return:
  8556. """
  8557. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8558. def on_zoom_out(self):
  8559. """
  8560. Callback for zoom-out request.
  8561. :return:
  8562. """
  8563. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8564. def disable_all_plots(self):
  8565. self.defaults.report_usage("disable_all_plots()")
  8566. self.disable_plots(self.collection.get_list())
  8567. self.inform.emit('[success] %s' %
  8568. _("All plots disabled."))
  8569. def disable_other_plots(self):
  8570. self.defaults.report_usage("disable_other_plots()")
  8571. self.disable_plots(self.collection.get_non_selected())
  8572. self.inform.emit('[success] %s' %
  8573. _("All non selected plots disabled."))
  8574. def enable_all_plots(self):
  8575. self.defaults.report_usage("enable_all_plots()")
  8576. self.enable_plots(self.collection.get_list())
  8577. self.inform.emit('[success] %s' %
  8578. _("All plots enabled."))
  8579. def on_enable_sel_plots(self):
  8580. log.debug("App.on_enable_sel_plot()")
  8581. object_list = self.collection.get_selected()
  8582. self.enable_plots(objects=object_list)
  8583. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8584. def on_disable_sel_plots(self):
  8585. log.debug("App.on_disable_sel_plot()")
  8586. # self.inform.emit(_("Disabling plots ..."))
  8587. object_list = self.collection.get_selected()
  8588. self.disable_plots(objects=object_list)
  8589. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8590. def enable_plots(self, objects):
  8591. """
  8592. Enable plots
  8593. :param objects: list of Objects to be enabled
  8594. :return:
  8595. """
  8596. log.debug("Enabling plots ...")
  8597. # self.inform.emit(_("Working ..."))
  8598. for obj in objects:
  8599. if obj.options['plot'] is False:
  8600. obj.options.set_change_callback(lambda x: None)
  8601. obj.options['plot'] = True
  8602. try:
  8603. # only the Gerber obj has on_plot_cb_click() method
  8604. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8605. # disable this cb while disconnected,
  8606. # in case the operation takes time the user is not allowed to change it
  8607. obj.ui.plot_cb.setDisabled(True)
  8608. except AttributeError:
  8609. pass
  8610. obj.set_form_item("plot")
  8611. try:
  8612. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8613. obj.ui.plot_cb.setDisabled(False)
  8614. except AttributeError:
  8615. pass
  8616. obj.options.set_change_callback(obj.on_options_change)
  8617. def worker_task(objs):
  8618. with self.proc_container.new(_("Enabling plots ...")):
  8619. for plot_obj in objs:
  8620. # obj.options['plot'] = True
  8621. if isinstance(plot_obj, CNCJobObject):
  8622. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8623. else:
  8624. plot_obj.plot(visible=True)
  8625. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8626. # self.plots_updated.emit()
  8627. def disable_plots(self, objects):
  8628. """
  8629. Disables plots
  8630. :param objects: list of Objects to be disabled
  8631. :return:
  8632. """
  8633. # if no objects selected then do nothing
  8634. if not self.collection.get_selected():
  8635. return
  8636. log.debug("Disabling plots ...")
  8637. # self.inform.emit(_("Working ..."))
  8638. for obj in objects:
  8639. if obj.options['plot'] is True:
  8640. obj.options.set_change_callback(lambda x: None)
  8641. obj.options['plot'] = False
  8642. try:
  8643. # only the Gerber obj has on_plot_cb_click() method
  8644. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8645. obj.ui.plot_cb.setDisabled(True)
  8646. except AttributeError:
  8647. pass
  8648. obj.set_form_item("plot")
  8649. try:
  8650. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8651. obj.ui.plot_cb.setDisabled(False)
  8652. except AttributeError:
  8653. pass
  8654. obj.options.set_change_callback(obj.on_options_change)
  8655. try:
  8656. self.delete_selection_shape()
  8657. except Exception as e:
  8658. log.debug("App.disable_plots() --> %s" % str(e))
  8659. # self.plots_updated.emit()
  8660. def worker_task(objs):
  8661. with self.proc_container.new(_("Disabling plots ...")):
  8662. for plot_obj in objs:
  8663. # obj.options['plot'] = True
  8664. if isinstance(plot_obj, CNCJobObject):
  8665. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8666. else:
  8667. plot_obj.plot(visible=False)
  8668. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8669. def toggle_plots(self, objects):
  8670. """
  8671. Toggle plots visibility
  8672. :param objects: list of Objects for which to be toggled the visibility
  8673. :return: None
  8674. """
  8675. # if no objects selected then do nothing
  8676. if not self.collection.get_selected():
  8677. return
  8678. log.debug("Toggling plots ...")
  8679. self.inform.emit(_("Working ..."))
  8680. for obj in objects:
  8681. if obj.options['plot'] is False:
  8682. obj.options['plot'] = True
  8683. else:
  8684. obj.options['plot'] = False
  8685. self.plots_updated.emit()
  8686. def clear_plots(self):
  8687. """
  8688. Clear the plots
  8689. :return: None
  8690. """
  8691. objects = self.collection.get_list()
  8692. for obj in objects:
  8693. obj.clear(obj == objects[-1])
  8694. # Clear pool to free memory
  8695. self.clear_pool()
  8696. def on_set_color_action_triggered(self):
  8697. """
  8698. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8699. :return:
  8700. """
  8701. new_color = self.defaults['gerber_plot_fill']
  8702. clicked_action = self.sender()
  8703. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8704. act_name = clicked_action.text()
  8705. sel_obj_list = self.collection.get_selected()
  8706. if not sel_obj_list:
  8707. return
  8708. # a default value, I just chose this one
  8709. alpha_level = 'BF'
  8710. for sel_obj in sel_obj_list:
  8711. if sel_obj.kind == 'excellon':
  8712. alpha_level = str(hex(
  8713. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8714. elif sel_obj.kind == 'gerber':
  8715. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8716. elif sel_obj.kind == 'geometry':
  8717. alpha_level = 'FF'
  8718. else:
  8719. log.debug(
  8720. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8721. continue
  8722. sel_obj.alpha_level = alpha_level
  8723. if act_name == _('Red'):
  8724. new_color = '#FF0000' + alpha_level
  8725. if act_name == _('Blue'):
  8726. new_color = '#0000FF' + alpha_level
  8727. if act_name == _('Yellow'):
  8728. new_color = '#FFDF00' + alpha_level
  8729. if act_name == _('Green'):
  8730. new_color = '#00FF00' + alpha_level
  8731. if act_name == _('Purple'):
  8732. new_color = '#FF00FF' + alpha_level
  8733. if act_name == _('Brown'):
  8734. new_color = '#A52A2A' + alpha_level
  8735. if act_name == _('White'):
  8736. new_color = '#FFFFFF' + alpha_level
  8737. if act_name == _('Black'):
  8738. new_color = '#000000' + alpha_level
  8739. if act_name == _('Custom'):
  8740. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8741. c_dialog = QtWidgets.QColorDialog()
  8742. plot_fill_color = c_dialog.getColor(initial=new_color)
  8743. if plot_fill_color.isValid() is False:
  8744. return
  8745. new_color = str(plot_fill_color.name()) + alpha_level
  8746. if act_name == _("Default"):
  8747. for sel_obj in sel_obj_list:
  8748. if sel_obj.kind == 'excellon':
  8749. new_color = self.defaults['excellon_plot_fill']
  8750. new_line_color = self.defaults['excellon_plot_line']
  8751. elif sel_obj.kind == 'gerber':
  8752. new_color = self.defaults['gerber_plot_fill']
  8753. new_line_color = self.defaults['gerber_plot_line']
  8754. elif sel_obj.kind == 'geometry':
  8755. new_color = self.defaults['geometry_plot_line']
  8756. new_line_color = self.defaults['geometry_plot_line']
  8757. else:
  8758. log.debug(
  8759. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8760. continue
  8761. sel_obj.fill_color = new_color
  8762. sel_obj.outline_color = new_line_color
  8763. sel_obj.shapes.redraw(
  8764. update_colors=(new_color, new_line_color)
  8765. )
  8766. return
  8767. if act_name == _("Opacity"):
  8768. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8769. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8770. if ok_button:
  8771. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8772. for sel_obj in sel_obj_list:
  8773. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8774. sel_obj.shapes.redraw(
  8775. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8776. )
  8777. return
  8778. new_line_color = color_variant(new_color[:7], 0.7)
  8779. if act_name == _("White"):
  8780. new_line_color = color_variant("#dedede", 0.7)
  8781. for sel_obj in sel_obj_list:
  8782. sel_obj.fill_color = new_color
  8783. sel_obj.outline_color = new_line_color
  8784. sel_obj.shapes.redraw(
  8785. update_colors=(new_color, new_line_color)
  8786. )
  8787. def generate_cnc_job(self, objects):
  8788. """
  8789. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8790. :param objects: Selected objects in the Project Tab
  8791. :return:
  8792. """
  8793. self.defaults.report_usage("generate_cnc_job()")
  8794. # for obj in objects:
  8795. # obj.generatecncjob()
  8796. for obj in objects:
  8797. obj.on_generatecnc_button_click()
  8798. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8799. """
  8800. Saves the current project to the specified file.
  8801. :param filename: Name of the file in which to save.
  8802. :type filename: str
  8803. :param quit_action: if the project saving will be followed by an app quit; boolean
  8804. :param silent: if True will not display status messages
  8805. :param from_tcl True is run from Tcl Shell
  8806. :return: None
  8807. """
  8808. self.log.debug("save_project()")
  8809. self.save_in_progress = True
  8810. with self.proc_container.new(_("Saving FlatCAM Project")):
  8811. # Capture the latest changes
  8812. # Current object
  8813. try:
  8814. current_object = self.collection.get_active()
  8815. if current_object:
  8816. current_object.read_form()
  8817. except Exception as e:
  8818. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8819. pass
  8820. # Serialize the whole project
  8821. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8822. "options": self.options,
  8823. "version": self.version}
  8824. if self.defaults["global_save_compressed"] is True:
  8825. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8826. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8827. # # Write
  8828. f.write(g)
  8829. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8830. else:
  8831. # Open file
  8832. try:
  8833. f = open(filename, 'w')
  8834. except IOError:
  8835. App.log.error("Failed to open file for saving: %s", filename)
  8836. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8837. return
  8838. # Write
  8839. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8840. f.close()
  8841. # verification of the saved project
  8842. # Open and parse
  8843. try:
  8844. saved_f = open(filename, 'r')
  8845. except IOError:
  8846. if silent is False:
  8847. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8848. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8849. return
  8850. try:
  8851. saved_d = json.load(saved_f, object_hook=dict2obj)
  8852. except Exception:
  8853. if silent is False:
  8854. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8855. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8856. f.close()
  8857. return
  8858. saved_f.close()
  8859. if silent is False:
  8860. if 'version' in saved_d:
  8861. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8862. else:
  8863. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8864. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8865. tb_settings = QSettings("Open Source", "FlatCAM")
  8866. lock_state = self.ui.lock_action.isChecked()
  8867. tb_settings.setValue('toolbar_lock', lock_state)
  8868. # This will write the setting to the platform specific storage.
  8869. del tb_settings
  8870. # if quit:
  8871. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8872. # t.start()
  8873. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8874. def start_delayed_quit(self, delay, filename, should_quit=None):
  8875. """
  8876. :param delay: period of checking if project file size is more than zero; in seconds
  8877. :param filename: the name of the project file to be checked periodically for size more than zero
  8878. :param should_quit: if the task finished will be followed by an app quit; boolean
  8879. :return:
  8880. """
  8881. to_quit = should_quit
  8882. self.save_timer = QtCore.QTimer()
  8883. self.save_timer.setInterval(delay)
  8884. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8885. self.save_timer.start()
  8886. def check_project_file_size(self, filename, should_quit=None):
  8887. """
  8888. :param filename: the name of the project file to be checked periodically for size more than zero
  8889. :param should_quit: will quit the app if True; boolean
  8890. :return:
  8891. """
  8892. try:
  8893. if os.stat(filename).st_size > 0:
  8894. self.save_in_progress = False
  8895. self.save_timer.stop()
  8896. if should_quit:
  8897. self.app_quit.emit()
  8898. except Exception:
  8899. traceback.print_exc()
  8900. def save_project_auto(self):
  8901. """
  8902. Called periodically to save the project.
  8903. 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
  8904. # progress.
  8905. :return:
  8906. """
  8907. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8908. self.on_file_saveproject()
  8909. def save_project_auto_update(self):
  8910. """
  8911. Update the auto save time interval value.
  8912. :return:
  8913. """
  8914. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8915. try:
  8916. if self.autosave_timer.isActive():
  8917. self.autosave_timer.stop()
  8918. except Exception:
  8919. pass
  8920. if self.defaults['global_autosave'] is True:
  8921. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8922. self.autosave_timer.start()
  8923. def on_options_app2project(self):
  8924. """
  8925. Callback for Options->Transfer Options->App=>Project. Copies options
  8926. from application defaults to project defaults.
  8927. :return: None
  8928. """
  8929. self.defaults.report_usage("on_options_app2project")
  8930. self.preferencesUiManager.defaults_read_form()
  8931. self.options.update(self.defaults)
  8932. def toggle_shell(self):
  8933. """
  8934. Toggle shell: if is visible close it, if it is closed then open it
  8935. :return: None
  8936. """
  8937. self.defaults.report_usage("toggle_shell()")
  8938. if self.ui.shell_dock.isVisible():
  8939. self.ui.shell_dock.hide()
  8940. self.plotcanvas.native.setFocus()
  8941. else:
  8942. self.ui.shell_dock.show()
  8943. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8944. # self.shell._edit.setFocus()
  8945. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8946. # HACK - simulate a mouse click - alternative
  8947. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8948. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8949. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8950. # no_km)
  8951. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8952. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8953. # no_km)
  8954. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8955. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8956. """
  8957. Shows a message on the FlatCAM Shell
  8958. :param msg: Message to display.
  8959. :param show: Opens the shell.
  8960. :param error: Shows the message as an error.
  8961. :param warning: Shows the message as an warning.
  8962. :param success: Shows the message as an success.
  8963. :param selected: Indicate that something was selected on canvas
  8964. :return: None
  8965. """
  8966. if show:
  8967. self.ui.shell_dock.show()
  8968. try:
  8969. if error:
  8970. self.shell.append_error(msg + "\n")
  8971. elif warning:
  8972. self.shell.append_warning(msg + "\n")
  8973. elif success:
  8974. self.shell.append_success(msg + "\n")
  8975. elif selected:
  8976. self.shell.append_selected(msg + "\n")
  8977. else:
  8978. self.shell.append_output(msg + "\n")
  8979. except AttributeError:
  8980. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8981. class ArgsThread(QtCore.QObject):
  8982. open_signal = pyqtSignal(list)
  8983. start = pyqtSignal()
  8984. if sys.platform == 'win32':
  8985. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8986. else:
  8987. address = ('/tmp/testipc', 'AF_UNIX')
  8988. def __init__(self):
  8989. super(ArgsThread, self).__init__()
  8990. self.listener = None
  8991. self.thread_exit = False
  8992. self.start.connect(self.run)
  8993. def my_loop(self, address):
  8994. try:
  8995. self.listener = Listener(*address)
  8996. while self.thread_exit is False:
  8997. conn = self.listener.accept()
  8998. self.serve(conn)
  8999. except socket.error:
  9000. try:
  9001. conn = Client(*address)
  9002. conn.send(sys.argv)
  9003. conn.send('close')
  9004. # close the current instance only if there are args
  9005. if len(sys.argv) > 1:
  9006. try:
  9007. self.listener.close()
  9008. except Exception:
  9009. pass
  9010. sys.exit()
  9011. except ConnectionRefusedError:
  9012. if sys.platform == 'win32':
  9013. pass
  9014. else:
  9015. os.system('rm /tmp/testipc')
  9016. self.listener = Listener(*address)
  9017. while True:
  9018. conn = self.listener.accept()
  9019. self.serve(conn)
  9020. def serve(self, conn):
  9021. while self.thread_exit is False:
  9022. msg = conn.recv()
  9023. if msg == 'close':
  9024. break
  9025. self.open_signal.emit(msg)
  9026. conn.close()
  9027. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9028. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9029. @pyqtSlot()
  9030. def run(self):
  9031. self.my_loop(self.address)
  9032. # end of file