App_Main.py 443 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896
  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. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  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 Common import LoudDict
  38. from Common import color_variant
  39. from Common import ExclusionAreas
  40. from Bookmark import BookmarkManager
  41. from AppDatabase import ToolsDB2
  42. from vispy.gloo.util import _screenshot
  43. from vispy.io import write_png
  44. # FlatCAM Objects
  45. from defaults import FlatCAMDefaults
  46. from AppGUI.preferences.OptionsGroupUI import OptionsGroupUI
  47. from AppGUI.preferences.PreferencesUIManager import PreferencesUIManager
  48. from AppObjects.ObjectCollection import *
  49. from AppObjects.FlatCAMObj import FlatCAMObj
  50. from AppObjects.AppObject import AppObject
  51. # FlatCAM Parsing files
  52. from AppParsers.ParseExcellon import Excellon
  53. from AppParsers.ParseGerber import Gerber
  54. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  55. # FlatCAM AppGUI
  56. from AppGUI.PlotCanvas import *
  57. from AppGUI.PlotCanvasLegacy import *
  58. from AppGUI.MainGUI import *
  59. from AppGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  60. # FlatCAM Pre-processors
  61. from AppPreProcessor import load_preprocessors
  62. # FlatCAM AppEditors
  63. from AppEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  64. from AppEditors.FlatCAMExcEditor import FlatCAMExcEditor
  65. from AppEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  66. from AppEditors.FlatCAMTextEditor import TextEditor
  67. from AppParsers.ParseHPGL2 import HPGL2
  68. # FlatCAM Workers
  69. from AppProcess import *
  70. from AppWorkerStack import WorkerStack
  71. # FlatCAM Tools
  72. from AppTools import *
  73. # FlatCAM Translation
  74. import gettext
  75. import AppTranslation as fcTranslate
  76. import builtins
  77. if sys.platform == 'win32':
  78. import winreg
  79. from win32comext.shell import shell, shellcon
  80. fcTranslate.apply_language('strings')
  81. if '_' not in builtins.__dict__:
  82. _ = gettext.gettext
  83. class App(QtCore.QObject):
  84. """
  85. The main application class. The constructor starts the AppGUI.
  86. """
  87. # ###############################################################################################################
  88. # ########################################## App ################################################################
  89. # ###############################################################################################################
  90. # ###############################################################################################################
  91. # ######################################### LOGGING #############################################################
  92. # ###############################################################################################################
  93. log = logging.getLogger('base')
  94. log.setLevel(logging.DEBUG)
  95. # log.setLevel(logging.WARNING)
  96. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  97. handler = logging.StreamHandler()
  98. handler.setFormatter(formatter)
  99. log.addHandler(handler)
  100. # ###############################################################################################################
  101. # #################################### Get Cmd Line Options #####################################################
  102. # ###############################################################################################################
  103. cmd_line_shellfile = ''
  104. cmd_line_shellvar = ''
  105. cmd_line_headless = None
  106. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  107. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  108. "FlatCam.py --headless=1"
  109. try:
  110. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  111. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  112. "shellvar=",
  113. "headless=",
  114. "multiprocessing-fork="])
  115. except getopt.GetoptError:
  116. print(cmd_line_help)
  117. sys.exit(2)
  118. for opt, arg in cmd_line_options:
  119. if opt == '-h':
  120. print(cmd_line_help)
  121. sys.exit()
  122. elif opt == '--shellfile':
  123. cmd_line_shellfile = arg
  124. elif opt == '--shellvar':
  125. cmd_line_shellvar = arg
  126. elif opt == '--headless':
  127. try:
  128. cmd_line_headless = eval(arg)
  129. except NameError:
  130. pass
  131. # ###############################################################################################################
  132. # ################################### Version and VERSION DATE ##################################################
  133. # ###############################################################################################################
  134. version = 8.993
  135. version_date = "2020/08/01"
  136. beta = True
  137. engine = '3D'
  138. # current date now
  139. date = str(datetime.today()).rpartition('.')[0]
  140. date = ''.join(c for c in date if c not in ':-')
  141. date = date.replace(' ', '_')
  142. # ###############################################################################################################
  143. # ############################################ URLS's ###########################################################
  144. # ###############################################################################################################
  145. # URL for update checks and statistics
  146. version_url = "http://flatcam.org/version"
  147. # App URL
  148. app_url = "http://flatcam.org"
  149. # Manual URL
  150. manual_url = "http://flatcam.org/manual/index.html"
  151. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  152. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  153. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  154. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  155. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  156. # this variable will hold the project status
  157. # if True it will mean that the project was modified and not saved
  158. should_we_save = False
  159. # flag is True if saving action has been triggered
  160. save_in_progress = False
  161. # ###############################################################################################################
  162. # ####################################### APP Signals ######################################################
  163. # ###############################################################################################################
  164. # Inform the user
  165. # Handled by:
  166. # * App.info() --> Print on the status bar
  167. inform = QtCore.pyqtSignal(str)
  168. app_quit = QtCore.pyqtSignal()
  169. # General purpose background task
  170. worker_task = QtCore.pyqtSignal(dict)
  171. # File opened
  172. # Handled by:
  173. # * register_folder()
  174. # * register_recent()
  175. # Note: Setting the parameters to unicode does not seem
  176. # to have an effect. Then are received as Qstring
  177. # anyway.
  178. # File type and filename
  179. file_opened = QtCore.pyqtSignal(str, str)
  180. # File type and filename
  181. file_saved = QtCore.pyqtSignal(str, str)
  182. # Percentage of progress
  183. progress = QtCore.pyqtSignal(int)
  184. # Emitted when a new object has been added or deleted from/to the collection
  185. object_status_changed = QtCore.pyqtSignal(object, str, str)
  186. message = QtCore.pyqtSignal(str, str, str)
  187. # Emmited when shell command is finished(one command only)
  188. shell_command_finished = QtCore.pyqtSignal(object)
  189. # Emitted when multiprocess pool has been recreated
  190. pool_recreated = QtCore.pyqtSignal(object)
  191. # Emitted when an unhandled exception happens
  192. # in the worker task.
  193. thread_exception = QtCore.pyqtSignal(object)
  194. # used to signal that there are arguments for the app
  195. args_at_startup = QtCore.pyqtSignal(list)
  196. # a reusable signal to replot a list of objects
  197. # should be disconnected after use so it can be reused
  198. replot_signal = pyqtSignal(list)
  199. # signal emitted when jumping
  200. jump_signal = pyqtSignal(tuple)
  201. # signal emitted when jumping
  202. locate_signal = pyqtSignal(tuple, str)
  203. # close app signal
  204. close_app_signal = pyqtSignal()
  205. # will perform the cleanup operation after a Graceful Exit
  206. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  207. # graphic residues behind
  208. cleanup = pyqtSignal()
  209. def __init__(self, user_defaults=True):
  210. """
  211. Starts the application.
  212. :return: app
  213. :rtype: App
  214. """
  215. super().__init__()
  216. App.log.info("FlatCAM Starting...")
  217. self.main_thread = QtWidgets.QApplication.instance().thread()
  218. # ############################################################################################################
  219. # ################# Setup the listening thread for another instance launching with args ######################
  220. # ############################################################################################################
  221. if sys.platform == 'win32' or sys.platform == 'linux':
  222. # make sure the thread is stored by using a self. otherwise it's garbage collected
  223. self.th = QtCore.QThread()
  224. self.th.start(priority=QtCore.QThread.LowestPriority)
  225. self.new_launch = ArgsThread()
  226. self.new_launch.open_signal[list].connect(self.on_startup_args)
  227. self.new_launch.moveToThread(self.th)
  228. self.new_launch.start.emit()
  229. # ############################################################################################################
  230. # # ######################################## OS-specific #####################################################
  231. # ############################################################################################################
  232. portable = False
  233. # Folder for user settings.
  234. if sys.platform == 'win32':
  235. if platform.architecture()[0] == '32bit':
  236. App.log.debug("Win32!")
  237. else:
  238. App.log.debug("Win64!")
  239. # #######################################################################################################
  240. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  241. # #######################################################################################################
  242. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  243. try:
  244. with open(config_file, 'r'):
  245. pass
  246. except FileNotFoundError:
  247. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  248. try:
  249. with open(config_file, 'r') as f:
  250. try:
  251. for line in f:
  252. param = str(line).replace('\n', '').rpartition('=')
  253. if param[0] == 'portable':
  254. try:
  255. portable = eval(param[2])
  256. except NameError:
  257. portable = False
  258. if param[0] == 'headless':
  259. if param[2].lower() == 'true':
  260. self.cmd_line_headless = 1
  261. else:
  262. self.cmd_line_headless = None
  263. except Exception as e:
  264. log.debug('App.__init__() -->%s' % str(e))
  265. return
  266. except FileNotFoundError as e:
  267. log.debug(str(e))
  268. pass
  269. if portable is False:
  270. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  271. else:
  272. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  273. self.os = 'windows'
  274. else: # Linux/Unix/MacOS
  275. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  276. self.os = 'unix'
  277. # ############################################################################################################
  278. # ################################# Setup folders and files ##################################################
  279. # ############################################################################################################
  280. if not os.path.exists(self.data_path):
  281. os.makedirs(self.data_path)
  282. App.log.debug('Created data folder: ' + self.data_path)
  283. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  284. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  285. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  286. if not os.path.exists(self.preprocessorpaths):
  287. os.makedirs(self.preprocessorpaths)
  288. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  289. # create geo_tools_db.FlatDB file if there is none
  290. try:
  291. f = open(self.data_path + '/geo_tools_db.FlatDB')
  292. f.close()
  293. except IOError:
  294. App.log.debug('Creating empty geo_tool_db.FlatDB')
  295. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  296. json.dump({}, f)
  297. f.close()
  298. # create current_defaults.FlatConfig file if there is none
  299. try:
  300. f = open(self.data_path + '/current_defaults.FlatConfig')
  301. f.close()
  302. except IOError:
  303. App.log.debug('Creating empty current_defaults.FlatConfig')
  304. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  305. json.dump({}, f)
  306. f.close()
  307. # Write factory_defaults.FlatConfig file to disk
  308. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  309. # create a recent files json file if there is none
  310. try:
  311. f = open(self.data_path + '/recent.json')
  312. f.close()
  313. except IOError:
  314. App.log.debug('Creating empty recent.json')
  315. f = open(self.data_path + '/recent.json', 'w')
  316. json.dump([], f)
  317. f.close()
  318. # create a recent projects json file if there is none
  319. try:
  320. fp = open(self.data_path + '/recent_projects.json')
  321. fp.close()
  322. except IOError:
  323. App.log.debug('Creating empty recent_projects.json')
  324. fp = open(self.data_path + '/recent_projects.json', 'w')
  325. json.dump([], fp)
  326. fp.close()
  327. # Application directory. CHDIR to it. Otherwise, trying to load
  328. # GUI icons will fail as their path is relative.
  329. # This will fail under cx_freeze ...
  330. self.app_home = os.path.dirname(os.path.realpath(__file__))
  331. App.log.debug("Application path is " + self.app_home)
  332. App.log.debug("Started in " + os.getcwd())
  333. # cx_freeze workaround
  334. if os.path.isfile(self.app_home):
  335. self.app_home = os.path.dirname(self.app_home)
  336. os.chdir(self.app_home)
  337. # ############################################################################################################
  338. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  339. # ############################################################################################################
  340. self.defaults = FlatCAMDefaults()
  341. self.defaults["root_folder_path"] = self.app_home
  342. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  343. if user_defaults:
  344. self.defaults.load(filename=current_defaults_path)
  345. if self.defaults['units'] == 'MM':
  346. self.decimals = int(self.defaults['decimals_metric'])
  347. else:
  348. self.decimals = int(self.defaults['decimals_inch'])
  349. if self.defaults["global_gray_icons"] is False:
  350. self.resource_location = 'assets/resources'
  351. else:
  352. self.resource_location = 'assets/resources/dark_resources'
  353. self.current_units = self.defaults['units']
  354. # ###########################################################################################################
  355. # #################################### SETUP OBJECT CLASSES #################################################
  356. # ###########################################################################################################
  357. self.setup_obj_classes()
  358. # ###########################################################################################################
  359. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  360. # ###########################################################################################################
  361. self.pool = Pool()
  362. # ###########################################################################################################
  363. # ###################################### Setting the Splash Screen ##########################################
  364. # ###########################################################################################################
  365. splash_settings = QSettings("Open Source", "FlatCAM")
  366. if splash_settings.contains("splash_screen"):
  367. show_splash = splash_settings.value("splash_screen")
  368. else:
  369. splash_settings.setValue('splash_screen', 1)
  370. # This will write the setting to the platform specific storage.
  371. del splash_settings
  372. show_splash = 1
  373. if show_splash and self.cmd_line_headless != 1:
  374. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  375. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  376. # self.splash.setMask(splash_pix.mask())
  377. # move splashscreen to the current monitor
  378. desktop = QtWidgets.QApplication.desktop()
  379. screen = desktop.screenNumber(QtGui.QCursor.pos())
  380. current_screen_center = desktop.availableGeometry(screen).center()
  381. self.splash.move(current_screen_center - self.splash.rect().center())
  382. self.splash.show()
  383. self.splash.showMessage(_("FlatCAM is initializing ..."),
  384. alignment=Qt.AlignBottom | Qt.AlignLeft,
  385. color=QtGui.QColor("gray"))
  386. else:
  387. show_splash = 0
  388. # ###########################################################################################################
  389. # ######################################### Initialize GUI ##################################################
  390. # ###########################################################################################################
  391. # FlatCAM colors used in plotting
  392. self.FC_light_green = '#BBF268BF'
  393. self.FC_dark_green = '#006E20BF'
  394. self.FC_light_blue = '#a5a5ffbf'
  395. self.FC_dark_blue = '#0000ffbf'
  396. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  397. if theme_settings.contains("theme"):
  398. theme = theme_settings.value('theme', type=str)
  399. else:
  400. theme = 'white'
  401. if self.defaults["global_cursor_color_enabled"]:
  402. self.cursor_color_3D = self.defaults["global_cursor_color"]
  403. else:
  404. if theme == 'white':
  405. self.cursor_color_3D = 'black'
  406. else:
  407. self.cursor_color_3D = 'gray'
  408. # update the defaults dict with the setting in QSetting
  409. self.defaults['global_theme'] = theme
  410. self.ui = MainGUI(self)
  411. # set FlatCAM units in the Status bar
  412. self.set_screen_units(self.defaults['units'])
  413. # ###########################################################################################################
  414. # ########################################### AUTOSAVE SETUP ################################################
  415. # ###########################################################################################################
  416. self.block_autosave = False
  417. self.autosave_timer = QtCore.QTimer(self)
  418. self.save_project_auto_update()
  419. self.autosave_timer.timeout.connect(self.save_project_auto)
  420. # ###########################################################################################################
  421. # #################################### LOAD PREPROCESSORS ###################################################
  422. # ###########################################################################################################
  423. # ----------------------------------------- WARNING --------------------------------------------------------
  424. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  425. # That's because the number of preprocessors can vary and here the comboboxes are populated
  426. # -----------------------------------------------------------------------------------------------------------
  427. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  428. # the preprocessor file
  429. self.preprocessors = load_preprocessors(self)
  430. # make sure that always the 'default' preprocessor is the first item in the dictionary
  431. if 'default' in self.preprocessors.keys():
  432. new_ppp_dict = {}
  433. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  434. default_pp = self.preprocessors.pop('default')
  435. new_ppp_dict['default'] = default_pp
  436. # then add the rest of the keys
  437. for name, val_class in self.preprocessors.items():
  438. new_ppp_dict[name] = val_class
  439. # and now put back the ordered dict with 'default' key first
  440. self.preprocessors = new_ppp_dict
  441. for name in list(self.preprocessors.keys()):
  442. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  443. if name.partition('_')[0] == 'Paste':
  444. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  445. continue
  446. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  447. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  448. if name == 'hpgl':
  449. continue
  450. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  451. # ###########################################################################################################
  452. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  453. # ###########################################################################################################
  454. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  455. inform=self.inform)
  456. self.preferencesUiManager.defaults_write_form()
  457. # When the self.defaults dictionary changes will update the Preferences GUI forms
  458. self.defaults.set_change_callback(self.on_defaults_dict_change)
  459. # ###########################################################################################################
  460. # ##################################### FIRST RUN SECTION ###################################################
  461. # ################################ It's done only once after install #####################################
  462. # ###########################################################################################################
  463. if self.defaults["first_run"] is True:
  464. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  465. initial_lay = 'minimal'
  466. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  467. # Set the combobox in Preferences to the current layout
  468. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  469. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  470. # after the first run, this object should be False
  471. self.defaults["first_run"] = False
  472. self.preferencesUiManager.save_defaults(silent=True)
  473. # ###########################################################################################################
  474. # ############################################ Data #########################################################
  475. # ###########################################################################################################
  476. self.recent = []
  477. self.recent_projects = []
  478. self.clipboard = QtWidgets.QApplication.clipboard()
  479. self.project_filename = None
  480. self.toggle_units_ignore = False
  481. # ###########################################################################################################
  482. # ########################################## LOAD LANGUAGES ################################################
  483. # ###########################################################################################################
  484. self.languages = fcTranslate.load_languages()
  485. for name in sorted(self.languages.values()):
  486. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  487. # ###########################################################################################################
  488. # ####################################### APPLY APP LANGUAGE ################################################
  489. # ###########################################################################################################
  490. ret_val = fcTranslate.apply_language('strings')
  491. if ret_val == "no language":
  492. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  493. log.debug("Could not find the Language files. The App strings are missing.")
  494. else:
  495. # make the current language the current selection on the language combobox
  496. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  497. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  498. # ###########################################################################################################
  499. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  500. # ###########################################################################################################
  501. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  502. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  503. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  504. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  505. self.defaults.propagate_defaults()
  506. # ###########################################################################################################
  507. # ######################################## UPDATE THE OPTIONS ###############################################
  508. # ###########################################################################################################
  509. self.options = LoudDict()
  510. # -----------------------------------------------------------------------------------------------------------
  511. # Update the self.options from the self.defaults
  512. # The self.defaults holds the application defaults while the self.options holds the object defaults
  513. # -----------------------------------------------------------------------------------------------------------
  514. # Copy app defaults to project options
  515. for def_key, def_val in self.defaults.items():
  516. self.options[def_key] = deepcopy(def_val)
  517. self.preferencesUiManager.show_preferences_gui()
  518. # ### End of Data ####
  519. # ###########################################################################################################
  520. # #################################### SETUP OBJECT COLLECTION ##############################################
  521. # ###########################################################################################################
  522. self.collection = ObjectCollection(app=self)
  523. self.ui.project_tab_layout.addWidget(self.collection.view)
  524. self.app_obj = AppObject(app=self)
  525. # ### Adjust tabs width ## ##
  526. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  527. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  528. self.collection.view.setMinimumWidth(290)
  529. self.log.debug("Finished creating Object Collection.")
  530. # ###########################################################################################################
  531. # ######################################## SETUP Plot Area ##################################################
  532. # ###########################################################################################################
  533. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  534. if self.defaults["global_graphic_engine"] == '3D':
  535. self.is_legacy = False
  536. else:
  537. self.is_legacy = True
  538. # Event signals disconnect id holders
  539. self.mp = None
  540. self.mm = None
  541. self.mr = None
  542. self.mdc = None
  543. self.mp_zc = None
  544. self.kp = None
  545. # Matplotlib axis
  546. self.axes = None
  547. if show_splash:
  548. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  549. "Canvas initialization started."),
  550. alignment=Qt.AlignBottom | Qt.AlignLeft,
  551. color=QtGui.QColor("gray"))
  552. start_plot_time = time.time() # debug
  553. self.plotcanvas = None
  554. self.app_cursor = None
  555. self.hover_shapes = None
  556. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  557. # setup the PlotCanvas
  558. self.on_plotcanvas_setup()
  559. end_plot_time = time.time()
  560. self.used_time = end_plot_time - start_plot_time
  561. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  562. if show_splash:
  563. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  564. "Canvas initialization started.\n"
  565. "Canvas initialization finished in"), '%.2f' % self.used_time),
  566. alignment=Qt.AlignBottom | Qt.AlignLeft,
  567. color=QtGui.QColor("gray"))
  568. self.ui.splitter.setStretchFactor(1, 2)
  569. # ###########################################################################################################
  570. # ############################################### SYS TRAY ##################################################
  571. # ###########################################################################################################
  572. if self.defaults["global_systray_icon"]:
  573. self.parent_w = QtWidgets.QWidget()
  574. if self.cmd_line_headless == 1:
  575. self.trayIcon = FlatCAMSystemTray(app=self,
  576. icon=QtGui.QIcon(self.resource_location +
  577. '/flatcam_icon32_green.png'),
  578. headless=True,
  579. parent=self.parent_w)
  580. else:
  581. self.trayIcon = FlatCAMSystemTray(app=self,
  582. icon=QtGui.QIcon(self.resource_location +
  583. '/flatcam_icon32_green.png'),
  584. parent=self.parent_w)
  585. # ###########################################################################################################
  586. # ############################################### Worker SETUP ##############################################
  587. # ###########################################################################################################
  588. if self.defaults["global_worker_number"]:
  589. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  590. else:
  591. self.workers = WorkerStack(workers_number=2)
  592. self.worker_task.connect(self.workers.add_task)
  593. self.log.debug("Finished creating Workers crew.")
  594. # ###########################################################################################################
  595. # ############################################# Activity Monitor ###########################################
  596. # ###########################################################################################################
  597. self.activity_view = FlatCAMActivityView(app=self)
  598. self.ui.infobar.addWidget(self.activity_view)
  599. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  600. # ###########################################################################################################
  601. # ############################################# Signal handling #############################################
  602. # ###########################################################################################################
  603. # ########################################## Custom signals ################################################
  604. # signal for displaying messages in status bar
  605. self.inform.connect(self.info)
  606. # signal to be called when the app is quiting
  607. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  608. self.message.connect(lambda: message_dialog(parent=self.ui))
  609. # self.progress.connect(self.set_progress_bar)
  610. # signals emitted when file state change
  611. self.file_opened.connect(self.register_recent)
  612. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  613. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  614. # ########################################## Standard signals ###############################################
  615. # ### Menu
  616. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  617. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  618. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  619. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  620. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  621. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  622. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  623. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  624. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  625. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  626. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  627. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  628. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  629. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  630. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  631. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  632. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  633. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  634. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  635. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  636. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  637. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  638. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  639. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  640. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  641. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  642. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  643. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  644. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  645. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  646. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  647. self.ui.menufile_exit.triggered.connect(self.final_save)
  648. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  649. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  650. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  651. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  652. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  653. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  654. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  655. self.ui.menueditdelete.triggered.connect(self.on_delete)
  656. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  657. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  658. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  659. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  660. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  661. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  662. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  663. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  664. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  665. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  666. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  667. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  668. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  669. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  670. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  671. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  672. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  673. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  674. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  675. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  676. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  677. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  678. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  679. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  680. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  681. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  682. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  683. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  684. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  685. self.ui.menuview_replot.triggered.connect(self.plot_all)
  686. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  687. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  688. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  689. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  690. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  691. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  692. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  693. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  694. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  695. self.ui.menuview_toggle_hud.triggered.connect(self.on_toggle_hud)
  696. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  697. self.ui.menuhelp_about.triggered.connect(self.on_about)
  698. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  699. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  700. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  701. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  702. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  703. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  704. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  705. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  706. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  707. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  708. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  709. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  710. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  711. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  712. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  713. # ToolBar signals
  714. self.connect_toolbar_signals()
  715. # Notebook and Plot Tab Area signals
  716. # make the right click on the notebook tab and plot tab area tab raise a menu
  717. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  718. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  719. self.on_tab_setup_context_menu()
  720. # activate initial state
  721. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  722. # Context Menu
  723. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  724. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  725. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  726. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  727. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  728. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  729. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  730. self.ui.clearplot.triggered.connect(self.clear_plots)
  731. self.ui.replot.triggered.connect(self.plot_all)
  732. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  733. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  734. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  735. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  736. self.ui.popmenu_move.triggered.connect(self.obj_move)
  737. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  738. # Project Context Menu -> Color Setting
  739. for act in self.ui.menuprojectcolor.actions():
  740. act.triggered.connect(self.on_set_color_action_triggered)
  741. # ###########################################################################################################
  742. # #################################### GUI PREFERENCES SIGNALS ##############################################
  743. # ###########################################################################################################
  744. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  745. lambda: self.on_toggle_units(no_pref=False))
  746. # ##################################### Workspace Setting Signals ###########################################
  747. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  748. self.on_workspace_modified)
  749. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  750. self.on_workspace_modified
  751. )
  752. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  753. # ###########################################################################################################
  754. # ######################################## GUI SETTINGS SIGNALS #############################################
  755. # ###########################################################################################################
  756. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  757. # ######################################## Tools related signals ############################################
  758. # portability changed signal
  759. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  760. # Object list
  761. self.object_status_changed.connect(self.collection.on_collection_updated)
  762. # when there are arguments at application startup this get launched
  763. self.args_at_startup[list].connect(self.on_startup_args)
  764. # ###########################################################################################################
  765. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  766. # ###########################################################################################################
  767. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  768. lambda: self.restore_extensions(ext_type='excellon'))
  769. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  770. lambda: self.restore_extensions(ext_type='gcode'))
  771. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  772. lambda: self.restore_extensions(ext_type='gerber'))
  773. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  774. lambda: self.delete_all_extensions(ext_type='excellon'))
  775. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  776. lambda: self.delete_all_extensions(ext_type='gcode'))
  777. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  778. lambda: self.delete_all_extensions(ext_type='gerber'))
  779. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  780. lambda: self.add_extension(ext_type='excellon'))
  781. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  782. lambda: self.add_extension(ext_type='gcode'))
  783. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  784. lambda: self.add_extension(ext_type='gerber'))
  785. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  786. lambda: self.del_extension(ext_type='excellon'))
  787. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  788. lambda: self.del_extension(ext_type='gcode'))
  789. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  790. lambda: self.del_extension(ext_type='gerber'))
  791. # connect the 'Apply' buttons from the Preferences/File Associations
  792. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  793. lambda: self.on_register_files(obj_type='excellon'))
  794. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  795. lambda: self.on_register_files(obj_type='gcode'))
  796. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  797. lambda: self.on_register_files(obj_type='gerber'))
  798. # ###########################################################################################################
  799. # ########################################### KEYWORDS SIGNALS ##############################################
  800. # ###########################################################################################################
  801. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  802. lambda: self.restore_extensions(ext_type='keyword'))
  803. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  804. lambda: self.delete_all_extensions(ext_type='keyword'))
  805. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  806. lambda: self.add_extension(ext_type='keyword'))
  807. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  808. lambda: self.del_extension(ext_type='keyword'))
  809. # connect the abort_all_tasks related slots to the related signals
  810. self.proc_container.idle_flag.connect(self.app_is_idle)
  811. # signal emitted when a tab is closed in the Plot Area
  812. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  813. # signal to close the application
  814. self.close_app_signal.connect(self.kill_app)
  815. # ################################# FINISHED CONNECTING SIGNALS #############################################
  816. # ###########################################################################################################
  817. # ###########################################################################################################
  818. # ###########################################################################################################
  819. self.log.debug("Finished connecting Signals.")
  820. # ###########################################################################################################
  821. # ########################################## Other setups ###################################################
  822. # ###########################################################################################################
  823. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  824. # depending on from where those tools are called different actions can be done
  825. self.call_source = 'app'
  826. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  827. self.tool_tab_locked = False
  828. # decide if to show or hide the Notebook side of the screen at startup
  829. if self.defaults["global_project_at_startup"] is True:
  830. self.ui.splitter.setSizes([1, 1])
  831. else:
  832. self.ui.splitter.setSizes([0, 1])
  833. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  834. self.setup_component_editor()
  835. # ###########################################################################################################
  836. # ####################################### Auto-complete KEYWORDS ############################################
  837. # ###########################################################################################################
  838. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  839. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  840. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  841. 'export_exc',
  842. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  843. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  844. 'interiors', 'isolate', 'join_excellon',
  845. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  846. 'mirror', 'ncc',
  847. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  848. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  849. 'options', 'origin',
  850. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  851. 'save', 'save_project',
  852. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  853. 'skew', 'subtract_poly', 'subtract_rectangle',
  854. 'version', 'write_gcode'
  855. ]
  856. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  857. 'Paste_1',
  858. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  859. 'Toolchange_manual', 'True', 'Users',
  860. 'all', 'auto', 'axis',
  861. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  862. 'contour', 'default',
  863. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  864. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  865. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  866. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  867. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  868. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  869. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  870. 'spacing_columns',
  871. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  872. 'toolchange_xy', 'toolchangez', 'travelz',
  873. 'tooldia', 'use_threads', 'value',
  874. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  875. ]
  876. self.tcl_keywords = [
  877. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  878. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  879. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  880. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  881. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  882. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  883. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  884. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  885. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  886. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  887. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  888. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  889. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  890. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  891. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  892. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  893. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  894. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  895. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  896. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  897. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  898. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  899. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  900. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  901. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  902. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  903. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  904. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  905. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  906. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  907. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  908. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  909. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  910. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  911. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  912. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  913. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  914. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  915. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  916. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  917. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  918. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  919. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  920. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  921. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  922. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  923. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  924. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  925. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  926. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  927. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  928. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  929. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  930. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  931. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  932. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  933. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  934. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  935. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  936. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  937. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  938. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  939. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  940. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  941. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  942. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  943. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  944. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  945. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  946. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  947. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  948. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  949. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  950. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  951. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  952. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  953. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  954. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  955. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  956. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  957. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  958. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  959. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  960. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  961. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  962. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  963. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  964. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  965. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  966. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  967. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  968. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  969. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  970. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  971. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  972. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  973. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  974. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  975. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  976. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  977. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  978. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  979. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  980. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  981. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  982. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  983. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  984. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  985. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  986. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  987. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  988. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  989. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  990. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  991. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  992. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  993. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  994. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  995. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  996. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  997. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  998. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  999. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1000. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1001. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1002. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1003. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1004. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1005. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1006. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1007. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1008. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1009. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1010. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1011. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1012. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1013. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1014. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1015. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1016. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1017. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1018. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1019. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1020. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1021. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1022. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1023. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1024. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1025. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1026. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1027. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1028. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1029. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1030. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1031. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1032. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1033. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1034. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1035. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1036. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1037. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1038. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1039. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1040. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1041. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1042. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1043. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1044. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1045. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1046. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1047. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1048. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1049. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1050. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1051. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1052. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1053. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1054. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1055. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1056. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1057. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1058. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1059. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1060. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1061. ]
  1062. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1063. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1064. # ###########################################################################################################
  1065. # ############################################## Shell SETUP ################################################
  1066. # ###########################################################################################################
  1067. self.shell = FCShell(app=self, version=self.version)
  1068. self.ui.shell_dock.setWidget(self.shell)
  1069. self.log.debug("TCL Shell has been initialized.")
  1070. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1071. if self.defaults["global_shell_at_startup"]:
  1072. self.ui.shell_dock.show()
  1073. else:
  1074. self.ui.shell_dock.hide()
  1075. # ###########################################################################################################
  1076. # ########################################## Tools and Plugins ##############################################
  1077. # ###########################################################################################################
  1078. self.dblsidedtool = None
  1079. self.distance_tool = None
  1080. self.distance_min_tool = None
  1081. self.panelize_tool = None
  1082. self.film_tool = None
  1083. self.paste_tool = None
  1084. self.calculator_tool = None
  1085. self.rules_tool = None
  1086. self.sub_tool = None
  1087. self.move_tool = None
  1088. self.cutout_tool = None
  1089. self.ncclear_tool = None
  1090. self.optimal_tool = None
  1091. self.paint_tool = None
  1092. self.transform_tool = None
  1093. self.properties_tool = None
  1094. self.pdf_tool = None
  1095. self.image_tool = None
  1096. self.pcb_wizard_tool = None
  1097. self.cal_exc_tool = None
  1098. self.qrcode_tool = None
  1099. self.copper_thieving_tool = None
  1100. self.fiducial_tool = None
  1101. self.edrills_tool = None
  1102. self.align_objects_tool = None
  1103. self.punch_tool = None
  1104. self.invert_tool = None
  1105. self.corners_tool = None
  1106. self.etch_tool = None
  1107. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1108. try:
  1109. self.install_tools()
  1110. except AttributeError as e:
  1111. log.debug("App.__init__() install tools() --> %s" % str(e))
  1112. # ###########################################################################################################
  1113. # ############################################ SETUP RECENT ITEMS ###########################################
  1114. # ###########################################################################################################
  1115. self.setup_recent_items()
  1116. # ###########################################################################################################
  1117. # ######################################### BookMarks Manager ###############################################
  1118. # ###########################################################################################################
  1119. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1120. self.install_bookmarks()
  1121. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1122. # ###########################################################################################################
  1123. # ########################################### Tools Database ################################################
  1124. # ###########################################################################################################
  1125. self.tools_db_tab = None
  1126. # ### System Font Parsing ###
  1127. # self.f_parse = ParseFont(self)
  1128. # self.parse_system_fonts()
  1129. # ###########################################################################################################
  1130. # ######################################### Check for updates ###############################################
  1131. # ###########################################################################################################
  1132. # Separate thread (Not worker)
  1133. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1134. if (self.beta is False or self.beta is None) and \
  1135. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1136. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1137. # self.thr2 = QtCore.QThread()
  1138. self.worker_task.emit({'fcn': self.version_check,
  1139. 'params': []})
  1140. # self.thr2.start(QtCore.QThread.LowPriority)
  1141. # ###########################################################################################################
  1142. # ##################################### Register files with FlatCAM; #######################################
  1143. # ################################### It works only for Windows for now ####################################
  1144. # ###########################################################################################################
  1145. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1146. self.on_register_files()
  1147. # ###########################################################################################################
  1148. # ######################################## Variables for global usage #######################################
  1149. # ###########################################################################################################
  1150. # hold the App units
  1151. self.units = 'MM'
  1152. # coordinates for relative position display
  1153. self.rel_point1 = (0, 0)
  1154. self.rel_point2 = (0, 0)
  1155. # variable to store coordinates
  1156. self.pos = (0, 0)
  1157. self.pos_canvas = (0, 0)
  1158. self.pos_jump = (0, 0)
  1159. # variable to store mouse coordinates
  1160. self.mouse = [0, 0]
  1161. # variable to store the delta positions on cavnas
  1162. self.dx = 0
  1163. self.dy = 0
  1164. # decide if we have a double click or single click
  1165. self.doubleclick = False
  1166. # store here the is_dragging value
  1167. self.event_is_dragging = False
  1168. # variable to store if a command is active (then the var is not None) and which one it is
  1169. self.command_active = None
  1170. # variable to store the status of moving selection action
  1171. # None value means that it's not an selection action
  1172. # True value = a selection from left to right
  1173. # False value = a selection from right to left
  1174. self.selection_type = None
  1175. # List to store the objects that are currently loaded in FlatCAM
  1176. # This list is updated on each object creation or object delete
  1177. self.all_objects_list = []
  1178. self.objects_under_the_click_list = []
  1179. # List to store the objects that are selected
  1180. self.sel_objects_list = []
  1181. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1182. self.key_modifiers = None
  1183. # Variable to hold the status of the axis
  1184. self.toggle_axis = True
  1185. # Variable to hold the status of the grid lines
  1186. self.toggle_grid_lines = True
  1187. # Variable to store the status of the code editor
  1188. self.toggle_codeeditor = False
  1189. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1190. self.click_noproject = False
  1191. self.cursor = None
  1192. # Variable to store the GCODE that was edited
  1193. self.gcode_edited = ""
  1194. self.text_editor_tab = None
  1195. # reference for the self.ui.code_editor
  1196. self.reference_code_editor = None
  1197. self.script_code = ''
  1198. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1199. self.tools_db_changed_flag = False
  1200. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1201. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1202. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1203. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1204. 'tsm']
  1205. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1206. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1207. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1208. 'sbp', 'tap', 'xpi']
  1209. self.svg_list = ['svg']
  1210. self.dxf_list = ['dxf']
  1211. self.pdf_list = ['pdf']
  1212. self.prj_list = ['flatprj']
  1213. self.conf_list = ['flatconfig']
  1214. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1215. # flag for polygons not cleared
  1216. self.poly_not_cleared = False
  1217. # VisPy visuals
  1218. self.isHovering = False
  1219. self.notHovering = True
  1220. # Window geometry
  1221. self.x_pos = None
  1222. self.y_pos = None
  1223. self.width = None
  1224. self.height = None
  1225. # when True, the app has to return from any thread
  1226. self.abort_flag = False
  1227. # set the value used in the Windows Title
  1228. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1229. # this holds a widget that is installed in the Plot Area when View Source option is used
  1230. self.source_editor_tab = None
  1231. self.pagesize = {}
  1232. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1233. # VisPy visuals
  1234. if self.is_legacy is False:
  1235. try:
  1236. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1237. except AttributeError:
  1238. self.tool_shapes = None
  1239. else:
  1240. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1241. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1242. # used in the delayed shutdown self.start_delayed_quit() method
  1243. self.save_timer = None
  1244. # ###########################################################################################################
  1245. # ################################## ADDING FlatCAM EDITORS section #########################################
  1246. # ###########################################################################################################
  1247. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1248. # at the first launch of the App , the editors will not be functional.
  1249. try:
  1250. self.geo_editor = FlatCAMGeoEditor(self)
  1251. except AttributeError:
  1252. pass
  1253. try:
  1254. self.exc_editor = FlatCAMExcEditor(self)
  1255. except AttributeError:
  1256. pass
  1257. try:
  1258. self.grb_editor = FlatCAMGrbEditor(self)
  1259. except AttributeError:
  1260. pass
  1261. self.log.debug("Finished adding FlatCAM Editor's.")
  1262. self.set_ui_title(name=_("New Project - Not saved"))
  1263. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1264. current_platform = platform.architecture()[0]
  1265. if current_platform != '64bit':
  1266. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1267. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1268. # ###########################################################################################################
  1269. # ########################################### EXCLUSION AREAS ###############################################
  1270. # ###########################################################################################################
  1271. self.exc_areas = ExclusionAreas(app=self)
  1272. # ###########################################################################################################
  1273. # ##################################### Finished the CONSTRUCTOR ############################################
  1274. # ###########################################################################################################
  1275. App.log.debug("END of constructor. Releasing control.")
  1276. # ###########################################################################################################
  1277. # ########################################## SHOW GUI #######################################################
  1278. # ###########################################################################################################
  1279. # if the app is not started as headless, show it
  1280. if self.cmd_line_headless != 1:
  1281. if show_splash:
  1282. # finish the splash
  1283. self.splash.finish(self.ui)
  1284. mgui_settings = QSettings("Open Source", "FlatCAM")
  1285. if mgui_settings.contains("maximized_gui"):
  1286. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1287. if maximized_ui is True:
  1288. self.ui.showMaximized()
  1289. else:
  1290. self.ui.show()
  1291. else:
  1292. self.ui.show()
  1293. if self.defaults["global_systray_icon"]:
  1294. self.trayIcon.show()
  1295. else:
  1296. log.warning("******************* RUNNING HEADLESS *******************")
  1297. # ###########################################################################################################
  1298. # ######################################## START-UP ARGUMENTS ###############################################
  1299. # ###########################################################################################################
  1300. # test if the program was started with a script as parameter
  1301. if self.cmd_line_shellvar:
  1302. try:
  1303. cnt = 0
  1304. command_tcl = 0
  1305. for i in self.cmd_line_shellvar.split(','):
  1306. if i is not None:
  1307. # noinspection PyBroadException
  1308. try:
  1309. command_tcl = eval(i)
  1310. except Exception:
  1311. command_tcl = i
  1312. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1313. cnt += 1
  1314. # if there are Windows paths then replace the path separator with a Unix like one
  1315. if sys.platform == 'win32':
  1316. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1317. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1318. except Exception as ext:
  1319. print("ERROR: ", ext)
  1320. sys.exit(2)
  1321. if self.cmd_line_shellfile:
  1322. if self.cmd_line_headless != 1:
  1323. if self.ui.shell_dock.isHidden():
  1324. self.ui.shell_dock.show()
  1325. try:
  1326. with open(self.cmd_line_shellfile, "r") as myfile:
  1327. # if show_splash:
  1328. # self.splash.showMessage('%s: %ssec\n%s' % (
  1329. # _("Canvas initialization started.\n"
  1330. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1331. # _("Executing Tcl Script ...")),
  1332. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1333. # color=QtGui.QColor("gray"))
  1334. cmd_line_shellfile_text = myfile.read()
  1335. if self.cmd_line_headless != 1:
  1336. self.shell.exec_command(cmd_line_shellfile_text)
  1337. else:
  1338. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1339. except Exception as ext:
  1340. print("ERROR: ", ext)
  1341. sys.exit(2)
  1342. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1343. # the path/file_name must be enclosed in quotes if it contain spaces
  1344. if App.args:
  1345. self.args_at_startup.emit(App.args)
  1346. if self.defaults.old_defaults_found is True:
  1347. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1348. "Please reboot the application to update."))
  1349. self.defaults.old_defaults_found = False
  1350. # ######################################### INIT FINISHED #######################################################
  1351. # #################################################################################################################
  1352. # #################################################################################################################
  1353. # #################################################################################################################
  1354. # #################################################################################################################
  1355. # #################################################################################################################
  1356. @staticmethod
  1357. def copy_and_overwrite(from_path, to_path):
  1358. """
  1359. From here:
  1360. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1361. :param from_path: source path
  1362. :param to_path: destination path
  1363. :return: None
  1364. """
  1365. if os.path.exists(to_path):
  1366. shutil.rmtree(to_path)
  1367. try:
  1368. shutil.copytree(from_path, to_path)
  1369. except FileNotFoundError:
  1370. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1371. shutil.copytree(from_new_path, to_path)
  1372. def on_startup_args(self, args, silent=False):
  1373. """
  1374. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1375. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1376. :param args: a list containing the application args at startup
  1377. :return: None
  1378. """
  1379. if args is not None:
  1380. args_to_process = args
  1381. else:
  1382. args_to_process = App.args
  1383. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1384. for argument in args_to_process:
  1385. if '.FlatPrj'.lower() in argument.lower():
  1386. try:
  1387. project_name = str(argument)
  1388. if project_name == "":
  1389. if silent is False:
  1390. self.inform.emit(_("Cancelled."))
  1391. else:
  1392. # self.open_project(project_name)
  1393. run_from_arg = True
  1394. # self.worker_task.emit({'fcn': self.open_project,
  1395. # 'params': [project_name, run_from_arg]})
  1396. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1397. except Exception as e:
  1398. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1399. elif '.FlatConfig'.lower() in argument.lower():
  1400. try:
  1401. file_name = str(argument)
  1402. if file_name == "":
  1403. if silent is False:
  1404. self.inform.emit(_("Open Config file failed."))
  1405. else:
  1406. run_from_arg = True
  1407. # self.worker_task.emit({'fcn': self.open_config_file,
  1408. # 'params': [file_name, run_from_arg]})
  1409. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1410. except Exception as e:
  1411. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1412. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1413. try:
  1414. file_name = str(argument)
  1415. if file_name == "":
  1416. if silent is False:
  1417. self.inform.emit(_("Open Script file failed."))
  1418. else:
  1419. if silent is False:
  1420. self.on_fileopenscript(name=file_name)
  1421. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1422. self.on_filerunscript(name=file_name)
  1423. except Exception as e:
  1424. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1425. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1426. log.debug("App.on_startup_args() --> Quit event.")
  1427. sys.exit()
  1428. elif 'save'.lower() in argument.lower():
  1429. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1430. self.preferencesUiManager.save_defaults()
  1431. else:
  1432. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1433. proc_arg = argument.lower()
  1434. for ext in exc_list:
  1435. proc_ext = ext.replace(' ', '')
  1436. proc_ext = '.%s' % proc_ext
  1437. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1438. file_name = str(argument)
  1439. if file_name == "":
  1440. if silent is False:
  1441. self.inform.emit(_("Open Excellon file failed."))
  1442. else:
  1443. self.on_fileopenexcellon(name=file_name, signal=None)
  1444. return
  1445. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1446. for ext in gco_list:
  1447. proc_ext = ext.replace(' ', '')
  1448. proc_ext = '.%s' % proc_ext
  1449. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1450. file_name = str(argument)
  1451. if file_name == "":
  1452. if silent is False:
  1453. self.inform.emit(_("Open GCode file failed."))
  1454. else:
  1455. self.on_fileopengcode(name=file_name, signal=None)
  1456. return
  1457. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1458. for ext in grb_list:
  1459. proc_ext = ext.replace(' ', '')
  1460. proc_ext = '.%s' % proc_ext
  1461. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1462. file_name = str(argument)
  1463. if file_name == "":
  1464. if silent is False:
  1465. self.inform.emit(_("Open Gerber file failed."))
  1466. else:
  1467. self.on_fileopengerber(name=file_name, signal=None)
  1468. return
  1469. # if it reached here without already returning then the app was registered with a file that it does not
  1470. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1471. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1472. # for arg in args_to_process:
  1473. # if 'FlatCAM.exe' in arg:
  1474. # continue
  1475. # else:
  1476. # sys.exit(2)
  1477. def set_ui_title(self, name):
  1478. """
  1479. Sets the title of the main window.
  1480. :param name: String that store the project path and project name
  1481. :return: None
  1482. """
  1483. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1484. (self.version,
  1485. ('BETA' if self.beta else ''),
  1486. platform.architecture()[0],
  1487. self.engine,
  1488. name)
  1489. )
  1490. def on_app_restart(self):
  1491. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1492. # be left in the SySTray
  1493. try:
  1494. self.trayIcon.hide()
  1495. except Exception:
  1496. pass
  1497. fcTranslate.restart_program(app=self)
  1498. def clear_pool(self):
  1499. """
  1500. Clear the multiprocessing pool and calls garbage collector.
  1501. :return: None
  1502. """
  1503. self.pool.close()
  1504. self.pool = Pool()
  1505. self.pool_recreated.emit(self.pool)
  1506. gc.collect()
  1507. def install_tools(self):
  1508. """
  1509. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1510. Instantiation of the Tools classes.
  1511. The order that the tools are installed is important as they can depend on each other install position.
  1512. :return: None
  1513. """
  1514. self.distance_tool = Distance(self)
  1515. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1516. before=self.ui.menueditorigin,
  1517. separator=False)
  1518. self.distance_min_tool = DistanceMin(self)
  1519. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1520. pos=self.ui.menuedit,
  1521. before=self.ui.menueditorigin,
  1522. separator=True)
  1523. self.dblsidedtool = DblSidedTool(self)
  1524. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1525. self.cal_exc_tool = ToolCalibration(self)
  1526. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1527. before=self.dblsidedtool.menuAction,
  1528. separator=False)
  1529. self.align_objects_tool = AlignObjects(self)
  1530. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1531. self.edrills_tool = ToolExtractDrills(self)
  1532. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1533. self.panelize_tool = Panelize(self)
  1534. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1535. self.film_tool = Film(self)
  1536. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1537. self.paste_tool = SolderPaste(self)
  1538. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1539. self.calculator_tool = ToolCalculator(self)
  1540. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1541. self.sub_tool = ToolSub(self)
  1542. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1543. pos=self.ui.menutool, separator=True)
  1544. self.rules_tool = RulesCheck(self)
  1545. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1546. pos=self.ui.menutool, separator=False)
  1547. self.optimal_tool = ToolOptimal(self)
  1548. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1549. pos=self.ui.menutool, separator=True)
  1550. self.move_tool = ToolMove(self)
  1551. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1552. before=self.ui.menueditorigin, separator=True)
  1553. self.cutout_tool = CutOut(self)
  1554. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1555. before=self.sub_tool.menuAction)
  1556. self.ncclear_tool = NonCopperClear(self)
  1557. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1558. before=self.sub_tool.menuAction, separator=True)
  1559. self.paint_tool = ToolPaint(self)
  1560. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1561. before=self.sub_tool.menuAction, separator=True)
  1562. self.copper_thieving_tool = ToolCopperThieving(self)
  1563. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1564. pos=self.ui.menutool)
  1565. self.fiducial_tool = ToolFiducials(self)
  1566. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1567. pos=self.ui.menutool)
  1568. self.qrcode_tool = QRCode(self)
  1569. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1570. pos=self.ui.menutool)
  1571. self.punch_tool = ToolPunchGerber(self)
  1572. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1573. self.invert_tool = ToolInvertGerber(self)
  1574. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1575. self.corners_tool = ToolCorners(self)
  1576. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1577. self.etch_tool = ToolEtchCompensation(self)
  1578. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etcg_32.png'), pos=self.ui.menutool)
  1579. self.transform_tool = ToolTransform(self)
  1580. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1581. pos=self.ui.menuoptions, separator=True)
  1582. self.properties_tool = Properties(self)
  1583. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1584. pos=self.ui.menuoptions)
  1585. self.pdf_tool = ToolPDF(self)
  1586. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1587. pos=self.ui.menufileimport,
  1588. separator=True)
  1589. self.image_tool = ToolImage(self)
  1590. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1591. pos=self.ui.menufileimport,
  1592. separator=True)
  1593. self.pcb_wizard_tool = PcbWizard(self)
  1594. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1595. pos=self.ui.menufileimport)
  1596. self.log.debug("Tools are installed.")
  1597. def remove_tools(self):
  1598. """
  1599. Will remove all the actions in the Tool menu.
  1600. :return: None
  1601. """
  1602. for act in self.ui.menutool.actions():
  1603. self.ui.menutool.removeAction(act)
  1604. def init_tools(self):
  1605. """
  1606. Initialize the Tool tab in the notebook side of the central widget.
  1607. Remove the actions in the Tools menu.
  1608. Instantiate again the FlatCAM tools (plugins).
  1609. All this is required when changing the layout: standard, compact etc.
  1610. :return: None
  1611. """
  1612. log.debug("init_tools()")
  1613. # delete the data currently in the Tools Tab and the Tab itself
  1614. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1615. if widget is not None:
  1616. widget.deleteLater()
  1617. self.ui.notebook.removeTab(2)
  1618. # rebuild the Tools Tab
  1619. self.ui.tool_tab = QtWidgets.QWidget()
  1620. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1621. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1622. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1623. self.ui.tool_scroll_area = VerticalScrollArea()
  1624. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1625. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1626. # first remove all of them
  1627. self.remove_tools()
  1628. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1629. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1630. '&Command Line\tS')
  1631. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1632. # third install all of them
  1633. try:
  1634. self.install_tools()
  1635. except AttributeError:
  1636. pass
  1637. self.log.debug("Tools are initialized.")
  1638. # def parse_system_fonts(self):
  1639. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1640. # 'params': []})
  1641. def connect_toolbar_signals(self):
  1642. """
  1643. Reconnect the signals to the actions in the toolbar.
  1644. This has to be done each time after the FlatCAM tools are removed/installed.
  1645. :return: None
  1646. """
  1647. # Toolbar
  1648. # File Toolbar Signals
  1649. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1650. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1651. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1652. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1653. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1654. # View Toolbar Signals
  1655. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1656. self.ui.replot_btn.triggered.connect(self.plot_all)
  1657. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1658. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1659. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1660. # Edit Toolbar Signals
  1661. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1662. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1663. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1664. self.ui.delete_btn.triggered.connect(self.on_delete)
  1665. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1666. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1667. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1668. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1669. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1670. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1671. # Scripting Toolbar Signals
  1672. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1673. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1674. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1675. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1676. # Tools Toolbar Signals
  1677. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1678. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1679. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1680. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1681. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1682. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1683. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1684. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1685. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1686. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1687. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1688. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1689. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1690. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1691. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1692. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1693. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1694. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1695. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1696. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1697. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1698. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1699. def object2editor(self):
  1700. """
  1701. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1702. :return: None
  1703. """
  1704. self.defaults.report_usage("object2editor()")
  1705. # disable the objects menu as it may interfere with the AppEditors
  1706. self.ui.menuobjects.setDisabled(True)
  1707. edited_object = self.collection.get_active()
  1708. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1709. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1710. pass
  1711. else:
  1712. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1713. return
  1714. if isinstance(edited_object, GeometryObject):
  1715. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1716. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1717. # we set the notebook to hidden
  1718. # self.ui.splitter.setSizes([0, 1])
  1719. if edited_object.multigeo is True:
  1720. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1721. if len(sel_rows) > 1:
  1722. self.inform.emit('[WARNING_NOTCL] %s' %
  1723. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1724. "is not possible.\n"
  1725. "Edit only one geometry at a time."))
  1726. # determine the tool dia of the selected tool
  1727. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1728. # now find the key in the edited_object.tools that has this tooldia
  1729. multi_tool = 1
  1730. for tool in edited_object.tools:
  1731. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1732. multi_tool = tool
  1733. break
  1734. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1735. else:
  1736. self.geo_editor.edit_fcgeometry(edited_object)
  1737. # set call source to the Editor we go into
  1738. self.call_source = 'geo_editor'
  1739. elif isinstance(edited_object, ExcellonObject):
  1740. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1741. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1742. if self.ui.splitter.sizes()[0] == 0:
  1743. self.ui.splitter.setSizes([1, 1])
  1744. self.exc_editor.edit_fcexcellon(edited_object)
  1745. # set call source to the Editor we go into
  1746. self.call_source = 'exc_editor'
  1747. elif isinstance(edited_object, GerberObject):
  1748. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1749. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1750. if self.ui.splitter.sizes()[0] == 0:
  1751. self.ui.splitter.setSizes([1, 1])
  1752. self.grb_editor.edit_fcgerber(edited_object)
  1753. # set call source to the Editor we go into
  1754. self.call_source = 'grb_editor'
  1755. # reset the following variables so the UI is built again after edit
  1756. edited_object.ui_build = False
  1757. edited_object.build_aperture_storage = False
  1758. elif isinstance(edited_object, CNCJobObject):
  1759. if self.ui.splitter.sizes()[0] == 0:
  1760. self.ui.splitter.setSizes([1, 1])
  1761. edited_object.on_edit_code_click()
  1762. return
  1763. # make sure that we can't select another object while in Editor Mode:
  1764. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1765. self.ui.project_frame.setDisabled(True)
  1766. # delete any selection shape that might be active as they are not relevant in Editor
  1767. self.delete_selection_shape()
  1768. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1769. self.ui.plot_tab_area.protectTab(0)
  1770. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1771. self.should_we_save = True
  1772. def editor2object(self, cleanup=None):
  1773. """
  1774. Transfers the Geometry or Excellon from it's editor to the current object.
  1775. :return: None
  1776. """
  1777. self.defaults.report_usage("editor2object()")
  1778. # re-enable the objects menu that was disabled on entry in Editor mode
  1779. self.ui.menuobjects.setDisabled(False)
  1780. # do not update a geometry or excellon object unless it comes out of an editor
  1781. if self.call_source != 'app':
  1782. edited_obj = self.collection.get_active()
  1783. if cleanup is None:
  1784. msgbox = QtWidgets.QMessageBox()
  1785. msgbox.setText(_("Do you want to save the edited object?"))
  1786. msgbox.setWindowTitle(_("Close Editor"))
  1787. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1788. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1789. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1790. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1791. msgbox.setDefaultButton(bt_yes)
  1792. msgbox.exec_()
  1793. response = msgbox.clickedButton()
  1794. if response == bt_yes:
  1795. # clean the Tools Tab
  1796. self.ui.tool_scroll_area.takeWidget()
  1797. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1798. self.ui.notebook.setTabText(2, "Tool")
  1799. if isinstance(edited_obj, GeometryObject):
  1800. obj_type = "Geometry"
  1801. if cleanup is None:
  1802. self.geo_editor.update_fcgeometry(edited_obj)
  1803. # self.geo_editor.update_options(edited_obj)
  1804. self.geo_editor.deactivate()
  1805. # restore GUI to the Selected TAB
  1806. # Remove anything else in the AppGUI
  1807. self.ui.tool_scroll_area.takeWidget()
  1808. # update the geo object options so it is including the bounding box values
  1809. try:
  1810. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1811. edited_obj.options['xmin'] = xmin
  1812. edited_obj.options['ymin'] = ymin
  1813. edited_obj.options['xmax'] = xmax
  1814. edited_obj.options['ymax'] = ymax
  1815. except AttributeError as e:
  1816. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1817. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1818. edited_obj.build_ui()
  1819. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1820. elif isinstance(edited_obj, GerberObject):
  1821. obj_type = "Gerber"
  1822. if cleanup is None:
  1823. self.grb_editor.update_fcgerber()
  1824. self.grb_editor.update_options(edited_obj)
  1825. self.grb_editor.deactivate_grb_editor()
  1826. # delete the old object (the source object) if it was an empty one
  1827. try:
  1828. if len(edited_obj.solid_geometry) == 0:
  1829. old_name = edited_obj.options['name']
  1830. self.collection.set_active(old_name)
  1831. self.collection.delete_active()
  1832. except TypeError:
  1833. # if the solid_geometry is a single Polygon the len() will not work
  1834. # in any case, falling here means that we have something in the solid_geometry, even if only
  1835. # a single Polygon, therefore we pass this
  1836. pass
  1837. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1838. # restore GUI to the Selected TAB
  1839. # Remove anything else in the AppGUI
  1840. self.ui.selected_scroll_area.takeWidget()
  1841. elif isinstance(edited_obj, ExcellonObject):
  1842. obj_type = "Excellon"
  1843. if cleanup is None:
  1844. self.exc_editor.update_fcexcellon(edited_obj)
  1845. # self.exc_editor.update_options(edited_obj)
  1846. self.exc_editor.deactivate()
  1847. # restore GUI to the Selected TAB
  1848. # Remove anything else in the AppGUI
  1849. self.ui.tool_scroll_area.takeWidget()
  1850. # delete the old object (the source object) if it was an empty one
  1851. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1852. old_name = edited_obj.options['name']
  1853. self.collection.delete_by_name(name=old_name)
  1854. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1855. else:
  1856. self.inform.emit('[WARNING_NOTCL] %s' %
  1857. _("Select a Gerber, Geometry or Excellon Object to update."))
  1858. return
  1859. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1860. elif response == bt_no:
  1861. # clean the Tools Tab
  1862. self.ui.tool_scroll_area.takeWidget()
  1863. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1864. self.ui.notebook.setTabText(2, "Tool")
  1865. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1866. if isinstance(edited_obj, GeometryObject):
  1867. self.geo_editor.deactivate()
  1868. edited_obj.build_ui()
  1869. elif isinstance(edited_obj, GerberObject):
  1870. self.grb_editor.deactivate_grb_editor()
  1871. edited_obj.build_ui()
  1872. elif isinstance(edited_obj, ExcellonObject):
  1873. self.exc_editor.deactivate()
  1874. edited_obj.build_ui()
  1875. else:
  1876. self.inform.emit('[WARNING_NOTCL] %s' %
  1877. _("Select a Gerber, Geometry or Excellon Object to update."))
  1878. return
  1879. elif response == bt_cancel:
  1880. return
  1881. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1882. # edited_obj.build_ui()
  1883. # Switch notebook to Selected page
  1884. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1885. else:
  1886. if isinstance(edited_obj, GeometryObject):
  1887. self.geo_editor.deactivate()
  1888. elif isinstance(edited_obj, GerberObject):
  1889. self.grb_editor.deactivate_grb_editor()
  1890. elif isinstance(edited_obj, ExcellonObject):
  1891. self.exc_editor.deactivate()
  1892. else:
  1893. self.inform.emit('[WARNING_NOTCL] %s' %
  1894. _("Select a Gerber, Geometry or Excellon Object to update."))
  1895. return
  1896. # if notebook is hidden we show it
  1897. if self.ui.splitter.sizes()[0] == 0:
  1898. self.ui.splitter.setSizes([1, 1])
  1899. # restore the call_source to app
  1900. self.call_source = 'app'
  1901. edited_obj.plot()
  1902. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1903. self.ui.plot_tab_area.protectTab(0)
  1904. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1905. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1906. self.ui.project_frame.setDisabled(False)
  1907. def get_last_folder(self):
  1908. """
  1909. Get the folder path from where the last file was opened.
  1910. :return: String, last opened folder path
  1911. """
  1912. return self.defaults["global_last_folder"]
  1913. def get_last_save_folder(self):
  1914. """
  1915. Get the folder path from where the last file was saved.
  1916. :return: String, last saved folder path
  1917. """
  1918. loc = self.defaults["global_last_save_folder"]
  1919. if loc is None:
  1920. loc = self.defaults["global_last_folder"]
  1921. if loc is None:
  1922. loc = os.path.dirname(__file__)
  1923. return loc
  1924. def info(self, msg):
  1925. """
  1926. Informs the user. Normally on the status bar, optionally
  1927. also on the shell.
  1928. :param msg: Text to write.
  1929. :return: None
  1930. """
  1931. # Type of message in brackets at the beginning of the message.
  1932. match = re.search(r"\[(.*)\](.*)", msg)
  1933. if match:
  1934. level = match.group(1)
  1935. msg_ = match.group(2)
  1936. self.ui.fcinfo.set_status(str(msg_), level=level)
  1937. if level.lower() == "error":
  1938. self.shell_message(msg, error=True, show=True)
  1939. elif level.lower() == "warning":
  1940. self.shell_message(msg, warning=True, show=True)
  1941. elif level.lower() == "error_notcl":
  1942. self.shell_message(msg, error=True, show=False)
  1943. elif level.lower() == "warning_notcl":
  1944. self.shell_message(msg, warning=True, show=False)
  1945. elif level.lower() == "success":
  1946. self.shell_message(msg, success=True, show=False)
  1947. elif level.lower() == "selected":
  1948. self.shell_message(msg, selected=True, show=False)
  1949. else:
  1950. self.shell_message(msg, show=False)
  1951. else:
  1952. self.ui.fcinfo.set_status(str(msg), level="info")
  1953. # make sure that if the message is to clear the infobar with a space
  1954. # is not printed over and over on the shell
  1955. if msg != '':
  1956. self.shell_message(msg)
  1957. def on_import_preferences(self):
  1958. """
  1959. Loads the application default settings from a saved file into
  1960. ``self.defaults`` dictionary.
  1961. :return: None
  1962. """
  1963. self.defaults.report_usage("on_import_preferences")
  1964. App.log.debug("App.on_import_preferences()")
  1965. # Show file chooser
  1966. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1967. try:
  1968. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1969. directory=self.data_path,
  1970. filter=filter_)
  1971. except TypeError:
  1972. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1973. filter=filter_)
  1974. filename = str(filename)
  1975. if filename == "":
  1976. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1977. return
  1978. # Load in the defaults from the chosen file
  1979. self.defaults.load(filename=filename)
  1980. self.preferencesUiManager.on_preferences_edited()
  1981. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  1982. def on_export_preferences(self):
  1983. """
  1984. Save the defaults dictionary to a file.
  1985. :return: None
  1986. """
  1987. self.defaults.report_usage("on_export_preferences")
  1988. App.log.debug("on_export_preferences()")
  1989. # defaults_file_content = None
  1990. # Show file chooser
  1991. date = str(datetime.today()).rpartition('.')[0]
  1992. date = ''.join(c for c in date if c not in ':-')
  1993. date = date.replace(' ', '_')
  1994. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  1995. try:
  1996. filename, _f = FCFileSaveDialog.get_saved_filename(
  1997. caption=_("Export FlatCAM Preferences"),
  1998. directory=self.data_path + '/preferences_' + date,
  1999. filter=filter__
  2000. )
  2001. except TypeError:
  2002. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2003. filename = str(filename)
  2004. if filename == "":
  2005. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2006. return
  2007. # Update options
  2008. self.preferencesUiManager.defaults_read_form()
  2009. self.defaults.propagate_defaults()
  2010. # Save update options
  2011. try:
  2012. self.defaults.write(filename=filename)
  2013. except Exception:
  2014. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2015. return
  2016. if self.defaults["global_open_style"] is False:
  2017. self.file_opened.emit("preferences", filename)
  2018. self.file_saved.emit("preferences", filename)
  2019. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2020. def save_to_file(self, content_to_save, txt_content):
  2021. """
  2022. Save something to a file.
  2023. :return: None
  2024. """
  2025. self.defaults.report_usage("save_to_file")
  2026. App.log.debug("save_to_file()")
  2027. self.date = str(datetime.today()).rpartition('.')[0]
  2028. self.date = ''.join(c for c in self.date if c not in ':-')
  2029. self.date = self.date.replace(' ', '_')
  2030. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2031. path_to_save = self.defaults["global_last_save_folder"] if \
  2032. self.defaults["global_last_save_folder"] is not None else self.data_path
  2033. try:
  2034. filename, _f = FCFileSaveDialog.get_saved_filename(
  2035. caption=_("Save to file"),
  2036. directory=path_to_save + '/file_' + self.date,
  2037. filter=filter__
  2038. )
  2039. except TypeError:
  2040. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2041. filename = str(filename)
  2042. if filename == "":
  2043. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2044. return
  2045. else:
  2046. try:
  2047. with open(filename, 'w') as f:
  2048. ___ = f.read()
  2049. except PermissionError:
  2050. self.inform.emit('[WARNING] %s' %
  2051. _("Permission denied, saving not possible.\n"
  2052. "Most likely another app is holding the file open and not accessible."))
  2053. return
  2054. except IOError:
  2055. App.log.debug('Creating a new file ...')
  2056. f = open(filename, 'w')
  2057. f.close()
  2058. except Exception:
  2059. e = sys.exc_info()[0]
  2060. App.log.error("Could not load the file.")
  2061. App.log.error(str(e))
  2062. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2063. return
  2064. # Save content
  2065. if filename.rpartition('.')[2].lower() == 'html':
  2066. file_content = content_to_save
  2067. else:
  2068. file_content = txt_content
  2069. try:
  2070. with open(filename, "w") as f:
  2071. f.write(file_content)
  2072. except Exception:
  2073. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2074. return
  2075. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2076. def register_recent(self, kind, filename):
  2077. """
  2078. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2079. dictionary.
  2080. :param kind: type of file that was opened
  2081. :param filename: the path and file name for the file that was opened
  2082. :return:
  2083. """
  2084. self.log.debug("register_recent()")
  2085. self.log.debug(" %s" % kind)
  2086. self.log.debug(" %s" % filename)
  2087. record = {'kind': str(kind), 'filename': str(filename)}
  2088. if record in self.recent:
  2089. return
  2090. if record in self.recent_projects:
  2091. return
  2092. if record['kind'] == 'project':
  2093. self.recent_projects.insert(0, record)
  2094. else:
  2095. self.recent.insert(0, record)
  2096. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2097. self.recent.pop()
  2098. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2099. self.recent_projects.pop()
  2100. try:
  2101. f = open(self.data_path + '/recent.json', 'w')
  2102. except IOError:
  2103. App.log.error("Failed to open recent items file for writing.")
  2104. self.inform.emit('[ERROR_NOTCL] %s' %
  2105. _('Failed to open recent files file for writing.'))
  2106. return
  2107. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2108. f.close()
  2109. try:
  2110. fp = open(self.data_path + '/recent_projects.json', 'w')
  2111. except IOError:
  2112. App.log.error("Failed to open recent items file for writing.")
  2113. self.inform.emit('[ERROR_NOTCL] %s' %
  2114. _('Failed to open recent projects file for writing.'))
  2115. return
  2116. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2117. fp.close()
  2118. # Re-build the recent items menu
  2119. self.setup_recent_items()
  2120. def on_about(self):
  2121. """
  2122. Displays the "about" dialog found in the Menu --> Help.
  2123. :return: None
  2124. """
  2125. self.defaults.report_usage("on_about")
  2126. version = self.version
  2127. version_date = self.version_date
  2128. beta = self.beta
  2129. class AboutDialog(QtWidgets.QDialog):
  2130. def __init__(self, app, parent=None):
  2131. QtWidgets.QDialog.__init__(self, parent)
  2132. self.app = app
  2133. # Icon and title
  2134. self.setWindowIcon(parent.app_icon)
  2135. self.setWindowTitle(_("About FlatCAM"))
  2136. self.resize(600, 200)
  2137. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2138. # self.setStyleSheet(
  2139. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2140. # "background-attachment: fixed"
  2141. # )
  2142. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2143. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2144. # palette = QtGui.QPalette()
  2145. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2146. # self.setPalette(palette)
  2147. logo = QtWidgets.QLabel()
  2148. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2149. title = QtWidgets.QLabel(
  2150. "<font size=8><B>FlatCAM</B></font><BR>"
  2151. "{title}<BR>"
  2152. "<BR>"
  2153. "<BR>"
  2154. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2155. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2156. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2157. "<B>{issue}</B></a><BR>".format(
  2158. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2159. devel=_("Development"),
  2160. down=_("DOWNLOAD"),
  2161. issue=_("Issue tracker"))
  2162. )
  2163. title.setOpenExternalLinks(True)
  2164. closebtn = QtWidgets.QPushButton(_("Close"))
  2165. tab_widget = QtWidgets.QTabWidget()
  2166. description_label = QtWidgets.QLabel(
  2167. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2168. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2169. version=version,
  2170. beta=('BETA' if beta else ''),
  2171. date=version_date,
  2172. arch=platform.architecture()[0])
  2173. )
  2174. description_label.setOpenExternalLinks(True)
  2175. lic_lbl_header = QtWidgets.QLabel(
  2176. '%s:<br>%s<br>' % (
  2177. _('Licensed under the MIT license'),
  2178. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2179. "http://www.opensource.org/licenses/mit-license.php</a>"
  2180. )
  2181. )
  2182. lic_lbl_header.setOpenExternalLinks(True)
  2183. lic_lbl_body = QtWidgets.QLabel(
  2184. _(
  2185. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2186. 'of this software and associated documentation files (the "Software"), to deal\n'
  2187. 'in the Software without restriction, including without limitation the rights\n'
  2188. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2189. 'copies of the Software, and to permit persons to whom the Software is\n'
  2190. 'furnished to do so, subject to the following conditions:\n\n'
  2191. 'The above copyright notice and this permission notice shall be included in\n'
  2192. 'all copies or substantial portions of the Software.\n\n'
  2193. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2194. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2195. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2196. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2197. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2198. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2199. 'THE SOFTWARE.'
  2200. )
  2201. )
  2202. attributions_label = QtWidgets.QLabel(
  2203. _(
  2204. 'Some of the icons used are from the following sources:<br>'
  2205. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2206. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2207. 'title="Flaticon">www.flaticon.com</a></div>'
  2208. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2209. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2210. )
  2211. )
  2212. attributions_label.setOpenExternalLinks(True)
  2213. # layouts
  2214. layout1 = QtWidgets.QVBoxLayout()
  2215. layout1_1 = QtWidgets.QHBoxLayout()
  2216. layout1_2 = QtWidgets.QHBoxLayout()
  2217. layout2 = QtWidgets.QHBoxLayout()
  2218. layout3 = QtWidgets.QHBoxLayout()
  2219. self.setLayout(layout1)
  2220. layout1.addLayout(layout1_1)
  2221. layout1.addLayout(layout1_2)
  2222. layout1.addLayout(layout2)
  2223. layout1.addLayout(layout3)
  2224. layout1_1.addStretch()
  2225. layout1_1.addWidget(description_label)
  2226. layout1_2.addWidget(tab_widget)
  2227. self.splash_tab = QtWidgets.QWidget()
  2228. self.splash_tab.setObjectName("splash_about")
  2229. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2230. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2231. tab_widget.addTab(self.splash_tab, _("Splash"))
  2232. self.programmmers_tab = QtWidgets.QWidget()
  2233. self.programmmers_tab.setObjectName("programmers_about")
  2234. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2235. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2236. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2237. self.translators_tab = QtWidgets.QWidget()
  2238. self.translators_tab.setObjectName("translators_about")
  2239. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2240. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2241. tab_widget.addTab(self.translators_tab, _("Translators"))
  2242. self.license_tab = QtWidgets.QWidget()
  2243. self.license_tab.setObjectName("license_about")
  2244. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2245. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2246. tab_widget.addTab(self.license_tab, _("License"))
  2247. self.attributions_tab = QtWidgets.QWidget()
  2248. self.attributions_tab.setObjectName("attributions_about")
  2249. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2250. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2251. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2252. self.splash_tab_layout.addWidget(logo, stretch=0)
  2253. self.splash_tab_layout.addWidget(title, stretch=1)
  2254. pal = QtGui.QPalette()
  2255. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2256. self.prog_grid_lay = QtWidgets.QGridLayout()
  2257. self.prog_grid_lay.setHorizontalSpacing(20)
  2258. self.prog_grid_lay.setColumnStretch(0, 0)
  2259. self.prog_grid_lay.setColumnStretch(2, 1)
  2260. prog_widget = QtWidgets.QWidget()
  2261. prog_widget.setLayout(self.prog_grid_lay)
  2262. prog_scroll = QtWidgets.QScrollArea()
  2263. prog_scroll.setWidget(prog_widget)
  2264. prog_scroll.setWidgetResizable(True)
  2265. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2266. prog_scroll.setPalette(pal)
  2267. self.programmmers_tab_layout.addWidget(prog_scroll)
  2268. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2269. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2270. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2271. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2272. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2273. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2274. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2275. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2276. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2277. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2278. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2279. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2280. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2281. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2282. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2283. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2284. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2285. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2286. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2287. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2288. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2289. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2290. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2291. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2292. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2293. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2294. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2295. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2296. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2297. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2298. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2299. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2300. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2301. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2302. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2303. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2304. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2315. self.translator_grid_lay = QtWidgets.QGridLayout()
  2316. self.translator_grid_lay.setColumnStretch(0, 0)
  2317. self.translator_grid_lay.setColumnStretch(1, 0)
  2318. self.translator_grid_lay.setColumnStretch(2, 1)
  2319. self.translator_grid_lay.setColumnStretch(3, 0)
  2320. # trans_widget = QtWidgets.QWidget()
  2321. # trans_widget.setLayout(self.translator_grid_lay)
  2322. # self.translators_tab_layout.addWidget(trans_widget)
  2323. # self.translators_tab_layout.addStretch()
  2324. trans_widget = QtWidgets.QWidget()
  2325. trans_widget.setLayout(self.translator_grid_lay)
  2326. trans_scroll = QtWidgets.QScrollArea()
  2327. trans_scroll.setWidget(trans_widget)
  2328. trans_scroll.setWidgetResizable(True)
  2329. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2330. trans_scroll.setPalette(pal)
  2331. self.translators_tab_layout.addWidget(trans_scroll)
  2332. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2333. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2334. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2335. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2336. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2337. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2338. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2339. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2340. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2341. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2342. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2343. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2344. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2345. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2346. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2347. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2348. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2349. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2350. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2351. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2352. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2353. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2354. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2355. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2356. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2357. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2358. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2359. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2360. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2361. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2362. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2363. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2364. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2365. self.translator_grid_lay.setColumnStretch(0, 0)
  2366. self.translators_tab_layout.addStretch()
  2367. self.license_tab_layout.addWidget(lic_lbl_header)
  2368. self.license_tab_layout.addWidget(lic_lbl_body)
  2369. self.license_tab_layout.addStretch()
  2370. self.attributions_tab_layout.addWidget(attributions_label)
  2371. self.attributions_tab_layout.addStretch()
  2372. layout3.addStretch()
  2373. layout3.addWidget(closebtn)
  2374. closebtn.clicked.connect(self.accept)
  2375. AboutDialog(app=self, parent=self.ui).exec_()
  2376. def install_bookmarks(self, book_dict=None):
  2377. """
  2378. Install the bookmarks actions in the Help menu -> Bookmarks
  2379. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2380. :return: None
  2381. """
  2382. if book_dict is None:
  2383. self.defaults["global_bookmarks"].update(
  2384. {
  2385. '1': ['FlatCAM', "http://flatcam.org"],
  2386. '2': ['Backup Site', ""]
  2387. }
  2388. )
  2389. else:
  2390. self.defaults["global_bookmarks"].clear()
  2391. self.defaults["global_bookmarks"].update(book_dict)
  2392. # first try to disconnect if somehow they get connected from elsewhere
  2393. for act in self.ui.menuhelp_bookmarks.actions():
  2394. try:
  2395. act.triggered.disconnect()
  2396. except TypeError:
  2397. pass
  2398. # clear all actions except the last one who is the Bookmark manager
  2399. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2400. pass
  2401. else:
  2402. self.ui.menuhelp_bookmarks.removeAction(act)
  2403. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2404. if self.defaults["global_bookmarks"]:
  2405. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2406. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2407. # the JSON is first making the keys as strings (therefore I have to use strings too
  2408. # or do the conversion :(
  2409. # )
  2410. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2411. # the '10' entry jsut after '1' therefore ordering as strings
  2412. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2413. key=lambda x: int(x[0]))
  2414. for entry, bookmark in sorted_bookmarks:
  2415. title = bookmark[0]
  2416. weblink = bookmark[1]
  2417. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2418. act.setText(title)
  2419. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2420. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2421. if title == 'Backup Site' and weblink == "":
  2422. act.triggered.connect(self.on_backup_site)
  2423. else:
  2424. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2425. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2426. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2427. def on_bookmarks_manager(self):
  2428. """
  2429. Adds the bookmark manager in a Tab in Plot Area
  2430. :return:
  2431. """
  2432. for idx in range(self.ui.plot_tab_area.count()):
  2433. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2434. # there can be only one instance of Bookmark Manager at one time
  2435. return
  2436. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2437. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2438. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2439. # add the tab if it was closed
  2440. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2441. # delete the absolute and relative position and messages in the infobar
  2442. self.ui.position_label.setText("")
  2443. # self.ui.rel_position_label.setText("")
  2444. # Switch plot_area to preferences page
  2445. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2446. def on_backup_site(self):
  2447. msgbox = QtWidgets.QMessageBox()
  2448. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2449. "1. FlatCAM.org website is down\n"
  2450. "2. Someone forked FlatCAM project and wants to point\n"
  2451. "to his own website\n\n"
  2452. "If you can't get any informations about FlatCAM beta\n"
  2453. "use the YouTube channel link from the Help menu."))
  2454. msgbox.setWindowTitle(_("Alternative website"))
  2455. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2456. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2457. msgbox.setDefaultButton(bt_yes)
  2458. msgbox.exec_()
  2459. # response = msgbox.clickedButton()
  2460. def on_file_savedefaults(self):
  2461. """
  2462. Callback for menu item File->Save Defaults. Saves application default options
  2463. ``self.defaults`` to current_defaults.FlatConfig.
  2464. :return: None
  2465. """
  2466. self.preferencesUiManager.save_defaults()
  2467. def final_save(self):
  2468. """
  2469. Callback for doing a preferences save to file whenever the application is about to quit.
  2470. If the project has changes, it will ask the user to save the project.
  2471. :return: None
  2472. """
  2473. if self.save_in_progress:
  2474. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2475. return
  2476. if self.should_we_save and self.collection.get_list():
  2477. msgbox = QtWidgets.QMessageBox()
  2478. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2479. "\n"
  2480. "Do you want to Save the project?"))
  2481. msgbox.setWindowTitle(_("Save changes"))
  2482. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2483. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2484. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2485. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2486. msgbox.setDefaultButton(bt_yes)
  2487. msgbox.exec_()
  2488. response = msgbox.clickedButton()
  2489. if response == bt_yes:
  2490. try:
  2491. self.trayIcon.hide()
  2492. except Exception:
  2493. pass
  2494. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2495. elif response == bt_no:
  2496. try:
  2497. self.trayIcon.hide()
  2498. except Exception:
  2499. pass
  2500. self.quit_application()
  2501. elif response == bt_cancel:
  2502. return
  2503. else:
  2504. try:
  2505. self.trayIcon.hide()
  2506. except Exception:
  2507. pass
  2508. self.quit_application()
  2509. def quit_application(self):
  2510. """
  2511. Called (as a pyslot or not) when the application is quit.
  2512. :return: None
  2513. """
  2514. self.preferencesUiManager.save_defaults(silent=True)
  2515. log.debug("App.quit_application() --> App Defaults saved.")
  2516. if self.cmd_line_headless != 1:
  2517. # save app state to file
  2518. stgs = QSettings("Open Source", "FlatCAM")
  2519. stgs.setValue('saved_gui_state', self.ui.saveState())
  2520. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2521. stgs.setValue(
  2522. 'language',
  2523. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2524. )
  2525. stgs.setValue(
  2526. 'notebook_font_size',
  2527. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2528. )
  2529. stgs.setValue(
  2530. 'axis_font_size',
  2531. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2532. )
  2533. stgs.setValue(
  2534. 'textbox_font_size',
  2535. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2536. )
  2537. stgs.setValue(
  2538. 'hud_font_size',
  2539. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2540. )
  2541. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2542. stgs.setValue(
  2543. 'machinist',
  2544. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2545. )
  2546. # This will write the setting to the platform specific storage.
  2547. del stgs
  2548. log.debug("App.quit_application() --> App UI state saved.")
  2549. # try to quit the Socket opened by ArgsThread class
  2550. try:
  2551. self.new_launch.stop.emit()
  2552. except Exception as err:
  2553. log.debug("App.quit_application() --> %s" % str(err))
  2554. # try to quit the QThread that run ArgsThread class
  2555. try:
  2556. self.th.quit()
  2557. except Exception as e:
  2558. log.debug("App.quit_application() --> %s" % str(e))
  2559. # terminate workers
  2560. self.workers.__del__()
  2561. # quit app by signalling for self.kill_app() method
  2562. # self.close_app_signal.emit()
  2563. QtWidgets.qApp.quit()
  2564. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2565. # we use the following command
  2566. minor_v = sys.version_info.minor
  2567. if minor_v < 8:
  2568. sys.exit(0)
  2569. else:
  2570. os._exit(0) # fix to work with Python 3.8
  2571. @staticmethod
  2572. def kill_app():
  2573. QtWidgets.qApp.quit()
  2574. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2575. # we use the following command
  2576. sys.exit(0)
  2577. def on_portable_checked(self, state):
  2578. """
  2579. Callback called when the checkbox in Preferences GUI is checked.
  2580. It will set the application as portable by creating the preferences and recent files in the
  2581. 'config' folder found in the FlatCAM installation folder.
  2582. :param state: boolean, the state of the checkbox when clicked/checked
  2583. :return:
  2584. """
  2585. line_no = 0
  2586. data = None
  2587. if sys.platform != 'win32':
  2588. # this won't work in Linux or MacOS
  2589. return
  2590. # test if the app was frozen and choose the path for the configuration file
  2591. if getattr(sys, "frozen", False) is True:
  2592. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2593. else:
  2594. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2595. config_file = current_data_path + '\\configuration.txt'
  2596. try:
  2597. with open(config_file, 'r') as f:
  2598. try:
  2599. data = f.readlines()
  2600. except Exception as e:
  2601. log.debug('App.__init__() -->%s' % str(e))
  2602. return
  2603. except FileNotFoundError:
  2604. pass
  2605. for line in data:
  2606. line = line.strip('\n')
  2607. param = str(line).rpartition('=')
  2608. if param[0] == 'portable':
  2609. break
  2610. line_no += 1
  2611. if state:
  2612. data[line_no] = 'portable=True\n'
  2613. # create the new defauults files
  2614. # create current_defaults.FlatConfig file if there is none
  2615. try:
  2616. f = open(current_data_path + '/current_defaults.FlatConfig')
  2617. f.close()
  2618. except IOError:
  2619. App.log.debug('Creating empty current_defaults.FlatConfig')
  2620. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2621. json.dump({}, f)
  2622. f.close()
  2623. # create factory_defaults.FlatConfig file if there is none
  2624. try:
  2625. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2626. f.close()
  2627. except IOError:
  2628. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2629. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2630. json.dump({}, f)
  2631. f.close()
  2632. try:
  2633. f = open(current_data_path + '/recent.json')
  2634. f.close()
  2635. except IOError:
  2636. App.log.debug('Creating empty recent.json')
  2637. f = open(current_data_path + '/recent.json', 'w')
  2638. json.dump([], f)
  2639. f.close()
  2640. try:
  2641. fp = open(current_data_path + '/recent_projects.json')
  2642. fp.close()
  2643. except IOError:
  2644. App.log.debug('Creating empty recent_projects.json')
  2645. fp = open(current_data_path + '/recent_projects.json', 'w')
  2646. json.dump([], fp)
  2647. fp.close()
  2648. # save the current defaults to the new defaults file
  2649. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2650. else:
  2651. data[line_no] = 'portable=False\n'
  2652. with open(config_file, 'w') as f:
  2653. f.writelines(data)
  2654. def on_register_files(self, obj_type=None):
  2655. """
  2656. Called whenever there is a need to register file extensions with FlatCAM.
  2657. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2658. :param obj_type: the type of object to be register for.
  2659. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2660. :return: None
  2661. """
  2662. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2663. new_reg_path = 'Software\\Classes\\'
  2664. # find if the current user is admin
  2665. try:
  2666. is_admin = os.getuid() == 0
  2667. except AttributeError:
  2668. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2669. if is_admin is True:
  2670. root_path = winreg.HKEY_LOCAL_MACHINE
  2671. else:
  2672. root_path = winreg.HKEY_CURRENT_USER
  2673. # create the keys
  2674. def set_reg(name, root_pth, new_reg_path, value):
  2675. try:
  2676. winreg.CreateKey(root_pth, new_reg_path)
  2677. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2678. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2679. return True
  2680. except WindowsError:
  2681. return False
  2682. # delete key in registry
  2683. def delete_reg(root_pth, reg_path, key_to_del):
  2684. key_to_del_path = reg_path + key_to_del
  2685. try:
  2686. winreg.DeleteKey(root_pth, key_to_del_path)
  2687. return True
  2688. except WindowsError:
  2689. return False
  2690. if obj_type is None or obj_type == 'excellon':
  2691. exc_list = \
  2692. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2693. exc_list = [x for x in exc_list if x != '']
  2694. # register all keys in the Preferences window
  2695. for ext in exc_list:
  2696. new_k = new_reg_path + '.%s' % ext
  2697. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2698. # and unregister those that are no longer in the Preferences windows but are in the file
  2699. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2700. if ext not in exc_list:
  2701. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2702. # now write the updated extensions to the self.defaults
  2703. # new_ext = ''
  2704. # for ext in exc_list:
  2705. # new_ext = new_ext + ext + ', '
  2706. # self.defaults["fa_excellon"] = new_ext
  2707. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2708. if obj_type is None or obj_type == 'gcode':
  2709. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2710. gco_list = [x for x in gco_list if x != '']
  2711. # register all keys in the Preferences window
  2712. for ext in gco_list:
  2713. new_k = new_reg_path + '.%s' % ext
  2714. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2715. # and unregister those that are no longer in the Preferences windows but are in the file
  2716. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2717. if ext not in gco_list:
  2718. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2719. # now write the updated extensions to the self.defaults
  2720. # new_ext = ''
  2721. # for ext in gco_list:
  2722. # new_ext = new_ext + ext + ', '
  2723. # self.defaults["fa_gcode"] = new_ext
  2724. self.inform.emit('[success] %s' %
  2725. _("Selected GCode file extensions registered with FlatCAM."))
  2726. if obj_type is None or obj_type == 'gerber':
  2727. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2728. grb_list = [x for x in grb_list if x != '']
  2729. # register all keys in the Preferences window
  2730. for ext in grb_list:
  2731. new_k = new_reg_path + '.%s' % ext
  2732. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2733. # and unregister those that are no longer in the Preferences windows but are in the file
  2734. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2735. if ext not in grb_list:
  2736. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2737. # now write the updated extensions to the self.defaults
  2738. # new_ext = ''
  2739. # for ext in grb_list:
  2740. # new_ext = new_ext + ext + ', '
  2741. # self.defaults["fa_gerber"] = new_ext
  2742. self.inform.emit('[success] %s' %
  2743. _("Selected Gerber file extensions registered with FlatCAM."))
  2744. def add_extension(self, ext_type):
  2745. """
  2746. Add a file extension to the list for a specific object
  2747. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2748. :return:
  2749. """
  2750. if ext_type == 'excellon':
  2751. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2752. if new_ext == '':
  2753. return
  2754. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2755. if new_ext in old_val:
  2756. return
  2757. old_val.append(new_ext)
  2758. old_val.sort()
  2759. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2760. if ext_type == 'gcode':
  2761. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2762. if new_ext == '':
  2763. return
  2764. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2765. if new_ext in old_val:
  2766. return
  2767. old_val.append(new_ext)
  2768. old_val.sort()
  2769. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2770. if ext_type == 'gerber':
  2771. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2772. if new_ext == '':
  2773. return
  2774. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2775. if new_ext in old_val:
  2776. return
  2777. old_val.append(new_ext)
  2778. old_val.sort()
  2779. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2780. if ext_type == 'keyword':
  2781. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2782. if new_kw == '':
  2783. return
  2784. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2785. if new_kw in old_val:
  2786. return
  2787. old_val.append(new_kw)
  2788. old_val.sort()
  2789. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2790. # update the self.myKeywords so the model is updated
  2791. self.autocomplete_kw_list = \
  2792. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2793. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2794. self.shell._edit.set_model_data(self.myKeywords)
  2795. def del_extension(self, ext_type):
  2796. """
  2797. Remove a file extension from the list for a specific object
  2798. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2799. :return:
  2800. """
  2801. if ext_type == 'excellon':
  2802. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2803. if new_ext == '':
  2804. return
  2805. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2806. if new_ext not in old_val:
  2807. return
  2808. old_val.remove(new_ext)
  2809. old_val.sort()
  2810. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2811. if ext_type == 'gcode':
  2812. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2813. if new_ext == '':
  2814. return
  2815. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2816. if new_ext not in old_val:
  2817. return
  2818. old_val.remove(new_ext)
  2819. old_val.sort()
  2820. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2821. if ext_type == 'gerber':
  2822. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2823. if new_ext == '':
  2824. return
  2825. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2826. if new_ext not in old_val:
  2827. return
  2828. old_val.remove(new_ext)
  2829. old_val.sort()
  2830. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2831. if ext_type == 'keyword':
  2832. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2833. if new_kw == '':
  2834. return
  2835. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2836. if new_kw not in old_val:
  2837. return
  2838. old_val.remove(new_kw)
  2839. old_val.sort()
  2840. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2841. # update the self.myKeywords so the model is updated
  2842. self.autocomplete_kw_list = \
  2843. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2844. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2845. self.shell._edit.set_model_data(self.myKeywords)
  2846. def restore_extensions(self, ext_type):
  2847. """
  2848. Restore all file extensions associations with FlatCAM, for a specific object
  2849. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2850. :return:
  2851. """
  2852. if ext_type == 'excellon':
  2853. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  2854. # for the ability to open Excellon files with .txt extension
  2855. new_exc_list = deepcopy(self.exc_list)
  2856. try:
  2857. new_exc_list.remove('txt')
  2858. except ValueError:
  2859. pass
  2860. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  2861. if ext_type == 'gcode':
  2862. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  2863. if ext_type == 'gerber':
  2864. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  2865. if ext_type == 'keyword':
  2866. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  2867. # update the self.myKeywords so the model is updated
  2868. self.autocomplete_kw_list = self.default_keywords
  2869. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2870. self.shell._edit.set_model_data(self.myKeywords)
  2871. def delete_all_extensions(self, ext_type):
  2872. """
  2873. Delete all file extensions associations with FlatCAM, for a specific object
  2874. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2875. :return:
  2876. """
  2877. if ext_type == 'excellon':
  2878. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  2879. if ext_type == 'gcode':
  2880. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  2881. if ext_type == 'gerber':
  2882. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  2883. if ext_type == 'keyword':
  2884. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  2885. # update the self.myKeywords so the model is updated
  2886. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  2887. self.shell._edit.set_model_data(self.myKeywords)
  2888. def on_edit_join(self, name=None):
  2889. """
  2890. Callback for Edit->Join. Joins the selected geometry objects into
  2891. a new one.
  2892. :return: None
  2893. """
  2894. self.defaults.report_usage("on_edit_join()")
  2895. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2896. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2897. geo_type_set = set()
  2898. objs = self.collection.get_selected()
  2899. if len(objs) < 2:
  2900. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2901. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2902. return 'fail'
  2903. for obj in objs:
  2904. geo_type_set.add(obj.multigeo)
  2905. # if len(geo_type_list) == 1 means that all list elements are the same
  2906. if len(geo_type_set) != 1:
  2907. self.inform.emit('[ERROR] %s' %
  2908. _("Failed join. The Geometry objects are of different types.\n"
  2909. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2910. "convert from one to another and retry joining \n"
  2911. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2912. "the result may not be what was expected. \n"
  2913. "Check the generated GCODE."))
  2914. return
  2915. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2916. if True in geo_type_set:
  2917. def initialize(geo_obj, app):
  2918. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  2919. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2920. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2921. for v in geo_obj.tools.values():
  2922. v['data']['name'] = obj_name_multi
  2923. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  2924. else:
  2925. def initialize(geo_obj, app):
  2926. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  2927. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2928. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2929. for v in geo_obj.tools.values():
  2930. v['data']['name'] = obj_name_single
  2931. self.app_obj.new_object("geometry", obj_name_single, initialize)
  2932. self.should_we_save = True
  2933. def on_edit_join_exc(self):
  2934. """
  2935. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  2936. a new Excellon.
  2937. :return: None
  2938. """
  2939. self.defaults.report_usage("on_edit_join_exc()")
  2940. objs = self.collection.get_selected()
  2941. for obj in objs:
  2942. if not isinstance(obj, ExcellonObject):
  2943. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  2944. return
  2945. if len(objs) < 2:
  2946. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2947. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2948. return 'fail'
  2949. def initialize(exc_obj, app):
  2950. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  2951. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  2952. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  2953. self.should_we_save = True
  2954. def on_edit_join_grb(self):
  2955. """
  2956. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2957. a new Gerber object.
  2958. :return: None
  2959. """
  2960. self.defaults.report_usage("on_edit_join_grb()")
  2961. objs = self.collection.get_selected()
  2962. for obj in objs:
  2963. if not isinstance(obj, GerberObject):
  2964. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  2965. return
  2966. if len(objs) < 2:
  2967. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2968. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2969. return 'fail'
  2970. def initialize(grb_obj, app):
  2971. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  2972. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  2973. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  2974. self.should_we_save = True
  2975. def on_convert_singlegeo_to_multigeo(self):
  2976. """
  2977. Called for converting a Geometry object from single-geo to multi-geo.
  2978. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  2979. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  2980. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  2981. the solid-geometry of that tool.
  2982. :return: None
  2983. """
  2984. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  2985. obj = self.collection.get_active()
  2986. if obj is None:
  2987. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  2988. return
  2989. if not isinstance(obj, GeometryObject):
  2990. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  2991. return
  2992. obj.multigeo = True
  2993. for tooluid, dict_value in obj.tools.items():
  2994. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2995. if not isinstance(obj.solid_geometry, list):
  2996. obj.solid_geometry = [obj.solid_geometry]
  2997. # obj.solid_geometry[:] = []
  2998. obj.plot()
  2999. self.should_we_save = True
  3000. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3001. def on_convert_multigeo_to_singlegeo(self):
  3002. """
  3003. Called for converting a Geometry object from multi-geo to single-geo.
  3004. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3005. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3006. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3007. the solid-geometry of that tool.
  3008. :return: None
  3009. """
  3010. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3011. obj = self.collection.get_active()
  3012. if obj is None:
  3013. self.inform.emit('[ERROR_NOTCL] %s' %
  3014. _("Failed. Select a Geometry Object and try again."))
  3015. return
  3016. if not isinstance(obj, GeometryObject):
  3017. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3018. (_("Expected a GeometryObject, got"), type(obj)))
  3019. return
  3020. obj.multigeo = False
  3021. total_solid_geometry = []
  3022. for tooluid, dict_value in obj.tools.items():
  3023. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3024. # clear the original geometry
  3025. dict_value['solid_geometry'][:] = []
  3026. obj.solid_geometry = deepcopy(total_solid_geometry)
  3027. obj.plot()
  3028. self.should_we_save = True
  3029. self.inform.emit('[success] %s' %
  3030. _("A Geometry object was converted to SingleGeo type."))
  3031. def on_defaults_dict_change(self, field):
  3032. """
  3033. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3034. Edit -> Preferences tab window.
  3035. :param field: the key of the self.defaults dictionary that was changed.
  3036. :return: None
  3037. """
  3038. self.preferencesUiManager.defaults_write_form_field(field=field)
  3039. if field == "units":
  3040. self.set_screen_units(self.defaults['units'])
  3041. def set_screen_units(self, units):
  3042. """
  3043. Set the FlatCAM units on the status bar.
  3044. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3045. :return: None
  3046. """
  3047. self.ui.units_label.setText("[" + units.lower() + "]")
  3048. def on_toggle_units_click(self):
  3049. try:
  3050. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3051. except (TypeError, AttributeError):
  3052. pass
  3053. if self.defaults["units"] == 'MM':
  3054. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3055. else:
  3056. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3057. self.on_toggle_units(no_pref=True)
  3058. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3059. lambda: self.on_toggle_units(no_pref=False))
  3060. def on_toggle_units(self, no_pref=False):
  3061. """
  3062. Callback for the Units radio-button change in the Preferences tab.
  3063. Changes the application's default units adn for the project too.
  3064. If changing the project's units, the change propagates to all of
  3065. the objects in the project.
  3066. :return: None
  3067. """
  3068. self.defaults.report_usage("on_toggle_units")
  3069. if self.toggle_units_ignore:
  3070. return
  3071. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3072. # If option is the same, then ignore
  3073. if new_units == self.defaults["units"].upper():
  3074. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3075. return
  3076. # Keys in self.defaults for which to scale their values
  3077. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3078. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3079. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3080. "gerber_editor_ma_high",
  3081. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3082. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3083. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3084. "excellon_feedrate_probe", "excellon_milling_dia",
  3085. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3086. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3087. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3088. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3089. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3090. "geometry_extracut_length", "geometry_z_pdepth",
  3091. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3092. 'cncjob_tooldia',
  3093. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3094. "tools_paintnewdia",
  3095. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3096. "tools_nccnewdia", "tools_ncc_offset_value",
  3097. "tools_2sided_drilldia",
  3098. "tools_film_boundary", "tools_film_scale_stroke",
  3099. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3100. "tools_cutout_depthperpass",
  3101. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3102. "tools_panelize_spacing_rows",
  3103. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3104. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3105. "tools_transform_buffer_dis",
  3106. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3107. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3108. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3109. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3110. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3111. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3112. "tools_cr_h2h_val", "tools_cr_dh_val",
  3113. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3114. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3115. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3116. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3117. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3118. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3119. "tools_copper_thieving_mask_clearance",
  3120. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3121. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3122. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3123. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3124. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3125. "tools_invert_margin",
  3126. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3127. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3128. def scale_defaults(sfactor):
  3129. for dim in dimensions:
  3130. if dim in [
  3131. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3132. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3133. 'tools_transform_mirror_point'
  3134. ]:
  3135. if self.defaults[dim] is None or self.defaults[dim] == '':
  3136. continue
  3137. try:
  3138. coordinates = self.defaults[dim].split(",")
  3139. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3140. coords_xy[0] *= sfactor
  3141. coords_xy[1] *= sfactor
  3142. self.defaults[dim] = "%.*f, %.*f" % (
  3143. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3144. except Exception as e:
  3145. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3146. elif dim in [
  3147. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3148. ]:
  3149. if self.defaults[dim] is None or self.defaults[dim] == '':
  3150. continue
  3151. try:
  3152. self.defaults[dim] = float(self.defaults[dim])
  3153. tools_diameters = [self.defaults[dim]]
  3154. except ValueError:
  3155. try:
  3156. tools_string = self.defaults[dim].split(",")
  3157. tools_diameters = [eval(a) for a in tools_string if a != '']
  3158. except Exception as e:
  3159. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3160. continue
  3161. self.defaults[dim] = ''
  3162. td_len = len(tools_diameters)
  3163. if td_len > 1:
  3164. for t in range(td_len):
  3165. tools_diameters[t] *= sfactor
  3166. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3167. else:
  3168. tools_diameters[0] *= sfactor
  3169. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3170. elif dim in ['global_gridx', 'global_gridy']:
  3171. # format the number of decimals to the one specified in self.decimals
  3172. try:
  3173. val = float(self.defaults[dim]) * sfactor
  3174. except Exception as e:
  3175. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3176. continue
  3177. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3178. else:
  3179. # the number of decimals for the rest is kept unchanged
  3180. if self.defaults[dim]:
  3181. try:
  3182. val = float(self.defaults[dim]) * sfactor
  3183. except Exception as e:
  3184. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3185. continue
  3186. self.defaults[dim] = val
  3187. # The scaling factor depending on choice of units.
  3188. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3189. # Changing project units. Warn user.
  3190. msgbox = QtWidgets.QMessageBox()
  3191. msgbox.setWindowTitle(_("Toggle Units"))
  3192. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3193. msgbox.setText(_("Changing the units of the project\n"
  3194. "will scale all objects.\n\n"
  3195. "Do you want to continue?"))
  3196. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3197. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3198. msgbox.setDefaultButton(bt_ok)
  3199. msgbox.exec_()
  3200. response = msgbox.clickedButton()
  3201. if response == bt_ok:
  3202. if no_pref is False:
  3203. self.preferencesUiManager.defaults_read_form()
  3204. scale_defaults(factor)
  3205. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3206. self.defaults["units"] = new_units
  3207. # update the defaults from form, some may assume that the conversion is enough and it's not
  3208. self.on_options_app2project()
  3209. # update the objects
  3210. for obj in self.collection.get_list():
  3211. obj.convert_units(new_units)
  3212. # make that the properties stored in the object are also updated
  3213. self.app_obj.object_changed.emit(obj)
  3214. # rebuild the object UI
  3215. obj.build_ui()
  3216. # change this only if the workspace is active
  3217. if self.defaults['global_workspace'] is True:
  3218. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3219. # adjust the grid values on the main toolbar
  3220. val_x = float(self.defaults['global_gridx']) * factor
  3221. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3222. current = self.collection.get_active()
  3223. if current is not None:
  3224. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3225. if not isinstance(current, GeometryObject):
  3226. current.to_form()
  3227. # replot all objects
  3228. self.plot_all()
  3229. # set the status labels to reflect the current FlatCAM units
  3230. self.set_screen_units(new_units)
  3231. # signal to the app that we changed the object properties and it should save the project
  3232. self.should_we_save = True
  3233. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3234. else:
  3235. # Undo toggling
  3236. self.toggle_units_ignore = True
  3237. if self.defaults['units'].upper() == 'MM':
  3238. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3239. else:
  3240. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3241. self.toggle_units_ignore = False
  3242. # store the grid values so they are not changed in the next step
  3243. val_x = float(self.defaults['global_gridx'])
  3244. val_y = float(self.defaults['global_gridy'])
  3245. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3246. self.preferencesUiManager.defaults_read_form()
  3247. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3248. # in self.defaults from the GUI elements but
  3249. # I don't want it for the grid values, so I update them here
  3250. self.defaults['global_gridx'] = val_x
  3251. self.defaults['global_gridy'] = val_y
  3252. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3253. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3254. def on_toggle_axis(self):
  3255. self.defaults.report_usage("on_toggle_axis()")
  3256. if self.toggle_axis is False:
  3257. if self.is_legacy is False:
  3258. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3259. parent=self.plotcanvas.view.scene)
  3260. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3261. parent=self.plotcanvas.view.scene)
  3262. else:
  3263. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3264. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3265. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3266. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3267. self.plotcanvas.canvas.draw()
  3268. self.inform.emit(_("Axis enabled."))
  3269. self.toggle_axis = True
  3270. else:
  3271. if self.is_legacy is False:
  3272. self.plotcanvas.v_line.parent = None
  3273. self.plotcanvas.h_line.parent = None
  3274. else:
  3275. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3276. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3277. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3278. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3279. self.plotcanvas.canvas.draw()
  3280. self.inform.emit(_("Axis disabled."))
  3281. self.toggle_axis = False
  3282. def on_toggle_hud(self):
  3283. new_state = False if self.plotcanvas.hud_enabled else True
  3284. self.plotcanvas.on_toggle_hud(state=new_state)
  3285. if new_state is False:
  3286. self.inform.emit(_("HUD disabled."))
  3287. else:
  3288. self.inform.emit(_("HUD enabled."))
  3289. def on_toggle_grid_lines(self):
  3290. self.defaults.report_usage("on_toggle_grd_lines()")
  3291. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3292. if tt_settings.contains("theme"):
  3293. theme = tt_settings.value('theme', type=str)
  3294. else:
  3295. theme = 'white'
  3296. if self.toggle_grid_lines is False:
  3297. if self.is_legacy is False:
  3298. if theme == 'white':
  3299. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3300. else:
  3301. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3302. else:
  3303. self.plotcanvas.axes.grid(True)
  3304. try:
  3305. self.plotcanvas.canvas.draw()
  3306. except IndexError:
  3307. pass
  3308. pass
  3309. self.inform.emit(_("Grid enabled."))
  3310. self.toggle_grid_lines = True
  3311. else:
  3312. if self.is_legacy is False:
  3313. if theme == 'white':
  3314. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3315. else:
  3316. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3317. else:
  3318. self.plotcanvas.axes.grid(False)
  3319. try:
  3320. self.plotcanvas.canvas.draw()
  3321. except IndexError:
  3322. pass
  3323. self.toggle_grid_lines = False
  3324. self.inform.emit(_("Grid disabled."))
  3325. if self.is_legacy is False:
  3326. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3327. # - perhaps is a bug in VisPy implementation
  3328. if self.grid_status():
  3329. self.app_cursor.enabled = False
  3330. self.app_cursor.enabled = True
  3331. else:
  3332. self.app_cursor.enabled = True
  3333. self.app_cursor.enabled = False
  3334. def on_tab_rmb_click(self, checked):
  3335. self.ui.notebook.set_detachable(val=checked)
  3336. self.defaults["global_tabs_detachable"] = checked
  3337. self.ui.plot_tab_area.set_detachable(val=checked)
  3338. self.defaults["global_tabs_detachable"] = checked
  3339. def on_tab_setup_context_menu(self):
  3340. initial_checked = self.defaults["global_tabs_detachable"]
  3341. action_name = str(_("Detachable Tabs"))
  3342. action = QtWidgets.QAction(self)
  3343. action.setCheckable(True)
  3344. action.setText(action_name)
  3345. action.setChecked(initial_checked)
  3346. self.ui.notebook.tabBar.addAction(action)
  3347. self.ui.plot_tab_area.tabBar.addAction(action)
  3348. try:
  3349. action.triggered.disconnect()
  3350. except TypeError:
  3351. pass
  3352. action.triggered.connect(self.on_tab_rmb_click)
  3353. def on_deselect_all(self):
  3354. self.collection.set_all_inactive()
  3355. self.delete_selection_shape()
  3356. def on_workspace_modified(self):
  3357. # self.save_defaults(silent=True)
  3358. self.plotcanvas.delete_workspace()
  3359. self.preferencesUiManager.defaults_read_form()
  3360. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3361. def on_workspace(self):
  3362. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3363. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3364. self.inform.emit(_("Workspace enabled."))
  3365. else:
  3366. self.plotcanvas.delete_workspace()
  3367. self.inform.emit(_("Workspace disabled."))
  3368. self.preferencesUiManager.defaults_read_form()
  3369. # self.save_defaults(silent=True)
  3370. def on_workspace_toggle(self):
  3371. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3372. try:
  3373. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3374. except TypeError:
  3375. pass
  3376. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3377. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3378. self.on_workspace()
  3379. def on_cursor_type(self, val):
  3380. """
  3381. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3382. :return: None
  3383. """
  3384. self.app_cursor.enabled = False
  3385. if val == 'small':
  3386. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3387. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3388. self.app_cursor = self.plotcanvas.new_cursor()
  3389. else:
  3390. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3391. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3392. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3393. if self.ui.grid_snap_btn.isChecked():
  3394. self.app_cursor.enabled = True
  3395. else:
  3396. self.app_cursor.enabled = False
  3397. def on_tool_add_keypress(self):
  3398. # ## Current application units in Upper Case
  3399. self.units = self.defaults['units'].upper()
  3400. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3401. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3402. if notebook_widget_name == 'selected_tab':
  3403. if self.collection.get_active().kind == 'geometry':
  3404. # Tool add works for Geometry only if Advanced is True in Preferences
  3405. if self.defaults["global_app_level"] == 'a':
  3406. tool_add_popup = FCInputDialog(title="New Tool ...",
  3407. text='Enter a Tool Diameter:',
  3408. min=0.0000, max=99.9999, decimals=4)
  3409. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3410. val, ok = tool_add_popup.get_value()
  3411. if ok:
  3412. if float(val) == 0:
  3413. self.inform.emit('[WARNING_NOTCL] %s' %
  3414. _("Please enter a tool diameter with non-zero value, in Float format."))
  3415. return
  3416. self.collection.get_active().on_tool_add(dia=float(val))
  3417. else:
  3418. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3419. else:
  3420. msgbox = QtWidgets.QMessageBox()
  3421. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3422. "Go to Preferences -> General - Show Advanced Options."))
  3423. msgbox.setWindowTitle("Tool adding ...")
  3424. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3425. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3426. msgbox.setDefaultButton(bt_ok)
  3427. msgbox.exec_()
  3428. # work only if the notebook tab on focus is the Tools_Tab
  3429. if notebook_widget_name == 'tool_tab':
  3430. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3431. # and only if the tool is NCC Tool
  3432. if tool_widget == self.ncclear_tool.toolName:
  3433. self.ncclear_tool.on_add_tool_by_key()
  3434. # and only if the tool is Paint Area Tool
  3435. elif tool_widget == self.paint_tool.toolName:
  3436. self.paint_tool.on_add_tool_by_key()
  3437. # and only if the tool is Solder Paste Dispensing Tool
  3438. elif tool_widget == self.paste_tool.toolName:
  3439. self.paste_tool.on_add_tool_by_key()
  3440. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3441. # See description below.
  3442. def on_delete_keypress(self):
  3443. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3444. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3445. if notebook_widget_name == 'selected_tab':
  3446. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3447. self.collection.get_active().on_tool_delete()
  3448. # work only if the notebook tab on focus is the Tools_Tab
  3449. elif notebook_widget_name == 'tool_tab':
  3450. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3451. # and only if the tool is NCC Tool
  3452. if tool_widget == self.ncclear_tool.toolName:
  3453. self.ncclear_tool.on_tool_delete()
  3454. # and only if the tool is Paint Tool
  3455. elif tool_widget == self.paint_tool.toolName:
  3456. self.paint_tool.on_tool_delete()
  3457. # and only if the tool is Solder Paste Dispensing Tool
  3458. elif tool_widget == self.paste_tool.toolName:
  3459. self.paste_tool.on_tool_delete()
  3460. else:
  3461. self.on_delete()
  3462. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3463. # some screens you have to be careful where you hover with your mouse.
  3464. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3465. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3466. # Complicated, I know :)
  3467. def on_delete(self, force_deletion=False):
  3468. """
  3469. Delete the currently selected FlatCAMObjs.
  3470. :param force_deletion: used by Tcl command
  3471. :return: None
  3472. """
  3473. self.defaults.report_usage("on_delete()")
  3474. response = None
  3475. bt_ok = None
  3476. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3477. # a geometry object before we update it.
  3478. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3479. and self.grb_editor.editor_active is False:
  3480. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3481. msgbox = QtWidgets.QMessageBox()
  3482. msgbox.setWindowTitle(_("Delete objects"))
  3483. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3484. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3485. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3486. "the selected objects?"))
  3487. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3488. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3489. msgbox.setDefaultButton(bt_ok)
  3490. msgbox.exec_()
  3491. response = msgbox.clickedButton()
  3492. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3493. response = bt_ok
  3494. if response == bt_ok:
  3495. if self.collection.get_active():
  3496. self.log.debug("App.on_delete()")
  3497. for obj_active in self.collection.get_selected():
  3498. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3499. if obj_active.kind == 'gerber':
  3500. for el in obj_active.mark_shapes:
  3501. obj_active.mark_shapes[el].clear(update=True)
  3502. obj_active.mark_shapes[el].enabled = False
  3503. # obj_active.mark_shapes[el] = None
  3504. del el
  3505. elif isinstance(obj_active, CNCJobObject):
  3506. try:
  3507. obj_active.text_col.enabled = False
  3508. del obj_active.text_col
  3509. obj_active.annotation.clear(update=True)
  3510. del obj_active.annotation
  3511. except AttributeError as e:
  3512. log.debug(
  3513. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3514. )
  3515. while self.collection.get_selected():
  3516. self.delete_first_selected()
  3517. self.inform.emit('%s...' % _("Object(s) deleted"))
  3518. # make sure that the selection shape is deleted, too
  3519. self.delete_selection_shape()
  3520. # if there are no longer objects delete also the exclusion areas shapes
  3521. if not self.collection.get_list():
  3522. self.exc_areas.clear_shapes()
  3523. else:
  3524. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3525. else:
  3526. self.inform.emit(_("Save the work in Editor and try again ..."))
  3527. def delete_first_selected(self):
  3528. # Keep this for later
  3529. try:
  3530. sel_obj = self.collection.get_active()
  3531. name = sel_obj.options["name"]
  3532. isPlotted = sel_obj.options["plot"]
  3533. except AttributeError:
  3534. self.log.debug("Nothing selected for deletion")
  3535. return
  3536. if self.is_legacy is True:
  3537. # Remove plot only if the object was plotted otherwise delaxes will fail
  3538. if isPlotted:
  3539. try:
  3540. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3541. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3542. except Exception as e:
  3543. log.debug("App.delete_first_selected() --> %s" % str(e))
  3544. self.plotcanvas.auto_adjust_axes()
  3545. # Remove from dictionary
  3546. self.collection.delete_active()
  3547. # Clear form
  3548. self.setup_component_editor()
  3549. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3550. def on_set_origin(self):
  3551. """
  3552. Set the origin to the left mouse click position
  3553. :return: None
  3554. """
  3555. # display the message for the user
  3556. # and ask him to click on the desired position
  3557. self.defaults.report_usage("on_set_origin()")
  3558. def origin_replot():
  3559. def worker_task():
  3560. with self.proc_container.new('%s...' % _("Plotting")):
  3561. for obj in self.collection.get_list():
  3562. obj.plot()
  3563. self.plotcanvas.fit_view()
  3564. if self.is_legacy:
  3565. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3566. else:
  3567. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3568. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3569. self.inform.emit(_('Click to set the origin ...'))
  3570. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3571. # first disconnect it as it may have been used by something else
  3572. try:
  3573. self.replot_signal.disconnect()
  3574. except TypeError:
  3575. pass
  3576. self.replot_signal[list].connect(origin_replot)
  3577. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3578. """
  3579. :param event:
  3580. :param location:
  3581. :param noplot:
  3582. :param use_thread:
  3583. :return:
  3584. """
  3585. noplot_sig = noplot
  3586. def worker_task():
  3587. with self.proc_container.new(_("Setting Origin...")):
  3588. obj_list = self.collection.get_list()
  3589. for obj in obj_list:
  3590. obj.offset((x, y))
  3591. self.app_obj.object_changed.emit(obj)
  3592. # Update the object bounding box options
  3593. a, b, c, d = obj.bounds()
  3594. obj.options['xmin'] = a
  3595. obj.options['ymin'] = b
  3596. obj.options['xmax'] = c
  3597. obj.options['ymax'] = d
  3598. self.inform.emit('[success] %s...' % _('Origin set'))
  3599. for obj in obj_list:
  3600. out_name = obj.options["name"]
  3601. if obj.kind == 'gerber':
  3602. obj.source_file = self.export_gerber(
  3603. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3604. elif obj.kind == 'excellon':
  3605. obj.source_file = self.export_excellon(
  3606. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3607. if noplot_sig is False:
  3608. self.replot_signal.emit([])
  3609. if location is not None:
  3610. if len(location) != 2:
  3611. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3612. return 'fail'
  3613. x, y = location
  3614. if use_thread is True:
  3615. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3616. else:
  3617. worker_task()
  3618. self.should_we_save = True
  3619. return
  3620. if event is not None and event.button == 1:
  3621. if self.is_legacy is False:
  3622. event_pos = event.pos
  3623. else:
  3624. event_pos = (event.xdata, event.ydata)
  3625. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3626. if self.grid_status():
  3627. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3628. else:
  3629. pos = pos_canvas
  3630. x = 0 - pos[0]
  3631. y = 0 - pos[1]
  3632. if use_thread is True:
  3633. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3634. else:
  3635. worker_task()
  3636. self.should_we_save = True
  3637. def on_move2origin(self, use_thread=True):
  3638. """
  3639. Move selected objects to origin.
  3640. :param use_thread: Control if to use threaded operation. Boolean.
  3641. :return:
  3642. """
  3643. def worker_task():
  3644. with self.proc_container.new(_("Moving to Origin...")):
  3645. obj_list = self.collection.get_selected()
  3646. if not obj_list:
  3647. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3648. return
  3649. xminlist = []
  3650. yminlist = []
  3651. # first get a bounding box to fit all
  3652. for obj in obj_list:
  3653. xmin, ymin, xmax, ymax = obj.bounds()
  3654. xminlist.append(xmin)
  3655. yminlist.append(ymin)
  3656. # get the minimum x,y for all objects selected
  3657. x = min(xminlist)
  3658. y = min(yminlist)
  3659. for obj in obj_list:
  3660. obj.offset((-x, -y))
  3661. self.app_obj.object_changed.emit(obj)
  3662. # Update the object bounding box options
  3663. a, b, c, d = obj.bounds()
  3664. obj.options['xmin'] = a
  3665. obj.options['ymin'] = b
  3666. obj.options['xmax'] = c
  3667. obj.options['ymax'] = d
  3668. for obj in obj_list:
  3669. obj.plot()
  3670. for obj in obj_list:
  3671. out_name = obj.options["name"]
  3672. if obj.kind == 'gerber':
  3673. obj.source_file = self.export_gerber(
  3674. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3675. elif obj.kind == 'excellon':
  3676. obj.source_file = self.export_excellon(
  3677. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3678. self.inform.emit('[success] %s...' % _('Origin set'))
  3679. if use_thread is True:
  3680. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3681. else:
  3682. worker_task()
  3683. self.should_we_save = True
  3684. def on_jump_to(self, custom_location=None, fit_center=True):
  3685. """
  3686. Jump to a location by setting the mouse cursor location.
  3687. :param custom_location: Jump to a specified point. (x, y) tuple.
  3688. :param fit_center: If to fit view. Boolean.
  3689. :return:
  3690. """
  3691. self.defaults.report_usage("on_jump_to()")
  3692. if not custom_location:
  3693. dia_box_location = None
  3694. try:
  3695. dia_box_location = eval(self.clipboard.text())
  3696. except Exception:
  3697. pass
  3698. if type(dia_box_location) == tuple:
  3699. dia_box_location = str(dia_box_location)
  3700. else:
  3701. dia_box_location = None
  3702. # dia_box = Dialog_box(title=_("Jump to ..."),
  3703. # label=_("Enter the coordinates in format X,Y:"),
  3704. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3705. # initial_text=dia_box_location)
  3706. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3707. label=_("Enter the coordinates in format X,Y:"),
  3708. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3709. initial_text=dia_box_location,
  3710. reference=self.defaults['global_jump_ref'])
  3711. if dia_box.ok is True:
  3712. try:
  3713. location = eval(dia_box.location)
  3714. if not isinstance(location, tuple):
  3715. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3716. return
  3717. if dia_box.reference == 'rel':
  3718. rel_x = self.mouse[0] + location[0]
  3719. rel_y = self.mouse[1] + location[1]
  3720. location = (rel_x, rel_y)
  3721. self.defaults['global_jump_ref'] = dia_box.reference
  3722. except Exception:
  3723. return
  3724. else:
  3725. return
  3726. else:
  3727. location = custom_location
  3728. self.jump_signal.emit(location)
  3729. if fit_center:
  3730. self.plotcanvas.fit_center(loc=location)
  3731. cursor = QtGui.QCursor()
  3732. if self.is_legacy is False:
  3733. # I don't know where those differences come from but they are constant for the current
  3734. # execution of the application and they are multiples of a value around 0.0263mm.
  3735. # In a random way sometimes they are more sometimes they are less
  3736. # if units == 'MM':
  3737. # cal_factor = 0.0263
  3738. # else:
  3739. # cal_factor = 0.0263 / 25.4
  3740. cal_location = (location[0], location[1])
  3741. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3742. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3743. j_pos = (
  3744. int(canvas_origin.x() + round(jump_loc[0])),
  3745. int(canvas_origin.y() + round(jump_loc[1]))
  3746. )
  3747. cursor.setPos(j_pos[0], j_pos[1])
  3748. else:
  3749. # find the canvas origin which is in the top left corner
  3750. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3751. # determine the coordinates for the lowest left point of the canvas
  3752. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3753. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3754. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3755. # canvas) and the point (width, height) is in the top-right location
  3756. loc = self.plotcanvas.axes.transData.transform_point(location)
  3757. j_pos = (
  3758. int(x0 + loc[0]),
  3759. int(y0 - loc[1])
  3760. )
  3761. cursor.setPos(j_pos[0], j_pos[1])
  3762. self.plotcanvas.mouse = [location[0], location[1]]
  3763. if self.defaults["global_cursor_color_enabled"] is True:
  3764. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3765. else:
  3766. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3767. if self.grid_status():
  3768. # Update cursor
  3769. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3770. symbol='++', edge_color=self.cursor_color_3D,
  3771. edge_width=self.defaults["global_cursor_width"],
  3772. size=self.defaults["global_cursor_size"])
  3773. # Set the relative position label
  3774. dx = location[0] - float(self.rel_point1[0])
  3775. dy = location[1] - float(self.rel_point1[1])
  3776. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3777. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3778. # # Set the position label
  3779. #
  3780. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3781. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3782. units = self.defaults["units"].lower()
  3783. self.plotcanvas.text_hud.text = \
  3784. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3785. dx, units, dy, units, location[0], units, location[1], units)
  3786. self.inform.emit('[success] %s' % _("Done."))
  3787. return location
  3788. def on_locate(self, obj, fit_center=True):
  3789. """
  3790. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3791. :param obj: The object on which to locate certain points
  3792. :param fit_center: If to fit view. Boolean.
  3793. :return: A point location. (x, y) tuple.
  3794. """
  3795. self.defaults.report_usage("on_locate()")
  3796. if obj is None:
  3797. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3798. return 'fail'
  3799. class DialogBoxChoice(QtWidgets.QDialog):
  3800. def __init__(self, title=None, icon=None, choice='bl'):
  3801. """
  3802. :param title: string with the window title
  3803. """
  3804. super(DialogBoxChoice, self).__init__()
  3805. self.ok = False
  3806. self.setWindowIcon(icon)
  3807. self.setWindowTitle(str(title))
  3808. self.form = QtWidgets.QFormLayout(self)
  3809. self.ref_radio = RadioSet([
  3810. {"label": _("Bottom-Left"), "value": "bl"},
  3811. {"label": _("Top-Left"), "value": "tl"},
  3812. {"label": _("Bottom-Right"), "value": "br"},
  3813. {"label": _("Top-Right"), "value": "tr"},
  3814. {"label": _("Center"), "value": "c"}
  3815. ], orientation='vertical', stretch=False)
  3816. self.ref_radio.set_value(choice)
  3817. self.form.addRow(self.ref_radio)
  3818. self.button_box = QtWidgets.QDialogButtonBox(
  3819. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3820. Qt.Horizontal, parent=self)
  3821. self.form.addRow(self.button_box)
  3822. self.button_box.accepted.connect(self.accept)
  3823. self.button_box.rejected.connect(self.reject)
  3824. if self.exec_() == QtWidgets.QDialog.Accepted:
  3825. self.ok = True
  3826. self.location_point = self.ref_radio.get_value()
  3827. else:
  3828. self.ok = False
  3829. self.location_point = None
  3830. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3831. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3832. choice=self.defaults['global_locate_pt'])
  3833. if dia_box.ok is True:
  3834. try:
  3835. location_point = dia_box.location_point
  3836. self.defaults['global_locate_pt'] = dia_box.location_point
  3837. except Exception:
  3838. return
  3839. else:
  3840. return
  3841. loc_b = obj.bounds()
  3842. if location_point == 'bl':
  3843. location = (loc_b[0], loc_b[1])
  3844. elif location_point == 'tl':
  3845. location = (loc_b[0], loc_b[3])
  3846. elif location_point == 'br':
  3847. location = (loc_b[2], loc_b[1])
  3848. elif location_point == 'tr':
  3849. location = (loc_b[2], loc_b[3])
  3850. else:
  3851. # center
  3852. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3853. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3854. location = (cx, cy)
  3855. self.locate_signal.emit(location, location_point)
  3856. if fit_center:
  3857. self.plotcanvas.fit_center(loc=location)
  3858. cursor = QtGui.QCursor()
  3859. if self.is_legacy is False:
  3860. # I don't know where those differences come from but they are constant for the current
  3861. # execution of the application and they are multiples of a value around 0.0263mm.
  3862. # In a random way sometimes they are more sometimes they are less
  3863. # if units == 'MM':
  3864. # cal_factor = 0.0263
  3865. # else:
  3866. # cal_factor = 0.0263 / 25.4
  3867. cal_location = (location[0], location[1])
  3868. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3869. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3870. j_pos = (
  3871. int(canvas_origin.x() + round(jump_loc[0])),
  3872. int(canvas_origin.y() + round(jump_loc[1]))
  3873. )
  3874. cursor.setPos(j_pos[0], j_pos[1])
  3875. else:
  3876. # find the canvas origin which is in the top left corner
  3877. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3878. # determine the coordinates for the lowest left point of the canvas
  3879. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3880. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3881. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3882. # canvas) and the point (width, height) is in the top-right location
  3883. loc = self.plotcanvas.axes.transData.transform_point(location)
  3884. j_pos = (
  3885. int(x0 + loc[0]),
  3886. int(y0 - loc[1])
  3887. )
  3888. cursor.setPos(j_pos[0], j_pos[1])
  3889. self.plotcanvas.mouse = [location[0], location[1]]
  3890. if self.defaults["global_cursor_color_enabled"] is True:
  3891. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3892. else:
  3893. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3894. if self.grid_status():
  3895. # Update cursor
  3896. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3897. symbol='++', edge_color=self.cursor_color_3D,
  3898. edge_width=self.defaults["global_cursor_width"],
  3899. size=self.defaults["global_cursor_size"])
  3900. # Set the relative position label
  3901. self.dx = location[0] - float(self.rel_point1[0])
  3902. self.dy = location[1] - float(self.rel_point1[1])
  3903. # Set the position label
  3904. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3905. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3906. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3907. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  3908. units = self.defaults["units"].lower()
  3909. self.plotcanvas.text_hud.text = \
  3910. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3911. self.dx, units, self.dy, units, location[0], units, location[1], units)
  3912. self.inform.emit('[success] %s' % _("Done."))
  3913. return location
  3914. def on_copy_command(self):
  3915. """
  3916. Will copy a selection of objects, creating new objects.
  3917. :return:
  3918. """
  3919. self.defaults.report_usage("on_copy_command()")
  3920. def initialize(obj_init, app):
  3921. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3922. try:
  3923. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3924. except AttributeError:
  3925. pass
  3926. try:
  3927. obj_init.apertures = deepcopy(obj.apertures)
  3928. except AttributeError:
  3929. pass
  3930. try:
  3931. if obj.tools:
  3932. obj_init.tools = deepcopy(obj.tools)
  3933. except Exception as err:
  3934. log.debug("App.on_copy_command() --> %s" % str(err))
  3935. try:
  3936. obj_init.source_file = deepcopy(obj.source_file)
  3937. except (AttributeError, TypeError):
  3938. pass
  3939. def initialize_excellon(obj_init, app):
  3940. obj_init.source_file = deepcopy(obj.source_file)
  3941. obj_init.tools = deepcopy(obj.tools)
  3942. # drills are offset, so they need to be deep copied
  3943. obj_init.drills = deepcopy(obj.drills)
  3944. # slots are offset, so they need to be deep copied
  3945. obj_init.slots = deepcopy(obj.slots)
  3946. obj_init.create_geometry()
  3947. def initialize_script(obj_init, app_obj):
  3948. obj_init.source_file = deepcopy(obj.source_file)
  3949. def initialize_document(obj_init, app_obj):
  3950. obj_init.source_file = deepcopy(obj.source_file)
  3951. for obj in self.collection.get_selected():
  3952. obj_name = obj.options["name"]
  3953. try:
  3954. if isinstance(obj, ExcellonObject):
  3955. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3956. elif isinstance(obj, GerberObject):
  3957. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  3958. elif isinstance(obj, GeometryObject):
  3959. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  3960. elif isinstance(obj, ScriptObject):
  3961. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  3962. elif isinstance(obj, DocumentObject):
  3963. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  3964. except Exception as e:
  3965. return "Operation failed: %s" % str(e)
  3966. def on_copy_object2(self, custom_name):
  3967. def initialize_geometry(obj_init, app):
  3968. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3969. try:
  3970. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3971. except AttributeError:
  3972. pass
  3973. try:
  3974. obj_init.apertures = deepcopy(obj.apertures)
  3975. except AttributeError:
  3976. pass
  3977. try:
  3978. if obj.tools:
  3979. obj_init.tools = deepcopy(obj.tools)
  3980. except Exception as ee:
  3981. log.debug("on_copy_object2() --> %s" % str(ee))
  3982. def initialize_gerber(obj_init, app):
  3983. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3984. obj_init.apertures = deepcopy(obj.apertures)
  3985. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3986. def initialize_excellon(obj_init, app):
  3987. obj_init.tools = deepcopy(obj.tools)
  3988. # drills are offset, so they need to be deep copied
  3989. obj_init.drills = deepcopy(obj.drills)
  3990. # slots are offset, so they need to be deep copied
  3991. obj_init.slots = deepcopy(obj.slots)
  3992. obj_init.create_geometry()
  3993. for obj in self.collection.get_selected():
  3994. obj_name = obj.options["name"]
  3995. try:
  3996. if isinstance(obj, ExcellonObject):
  3997. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3998. elif isinstance(obj, GerberObject):
  3999. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4000. elif isinstance(obj, GeometryObject):
  4001. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4002. except Exception as er:
  4003. return "Operation failed: %s" % str(er)
  4004. def on_rename_object(self, text):
  4005. """
  4006. Will rename an object.
  4007. :param text: New name for the object.
  4008. :return:
  4009. """
  4010. self.defaults.report_usage("on_rename_object()")
  4011. named_obj = self.collection.get_active()
  4012. for obj in named_obj:
  4013. if obj is list:
  4014. self.on_rename_object(text)
  4015. else:
  4016. try:
  4017. obj.options['name'] = text
  4018. except Exception as e:
  4019. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4020. def convert_any2geo(self):
  4021. """
  4022. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4023. :return:
  4024. """
  4025. self.defaults.report_usage("convert_any2geo()")
  4026. def initialize(obj_init, app):
  4027. obj_init.solid_geometry = obj.solid_geometry
  4028. try:
  4029. obj_init.follow_geometry = obj.follow_geometry
  4030. except AttributeError:
  4031. pass
  4032. try:
  4033. obj_init.apertures = obj.apertures
  4034. except AttributeError:
  4035. pass
  4036. try:
  4037. if obj.tools:
  4038. obj_init.tools = obj.tools
  4039. except AttributeError:
  4040. pass
  4041. def initialize_excellon(obj_init, app):
  4042. # objs = self.collection.get_selected()
  4043. # GeometryObject.merge(objs, obj)
  4044. solid_geo = []
  4045. for tool in obj.tools:
  4046. for geo in obj.tools[tool]['solid_geometry']:
  4047. solid_geo.append(geo)
  4048. obj_init.solid_geometry = deepcopy(solid_geo)
  4049. if not self.collection.get_selected():
  4050. log.warning("App.convert_any2geo --> No object selected")
  4051. self.inform.emit('[WARNING_NOTCL] %s' %
  4052. _("No object is selected. Select an object and try again."))
  4053. return
  4054. for obj in self.collection.get_selected():
  4055. obj_name = obj.options["name"]
  4056. try:
  4057. if isinstance(obj, ExcellonObject):
  4058. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4059. else:
  4060. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4061. except Exception as e:
  4062. return "Operation failed: %s" % str(e)
  4063. def convert_any2gerber(self):
  4064. """
  4065. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4066. :return:
  4067. """
  4068. self.defaults.report_usage("convert_any2gerber()")
  4069. def initialize_geometry(obj_init, app):
  4070. apertures = {}
  4071. apid = 0
  4072. apertures[str(apid)] = {}
  4073. apertures[str(apid)]['geometry'] = []
  4074. for obj_orig in obj.solid_geometry:
  4075. new_elem = {}
  4076. new_elem['solid'] = obj_orig
  4077. try:
  4078. new_elem['follow'] = obj_orig.exterior
  4079. except AttributeError:
  4080. pass
  4081. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4082. apertures[str(apid)]['size'] = 0.0
  4083. apertures[str(apid)]['type'] = 'C'
  4084. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4085. obj_init.apertures = deepcopy(apertures)
  4086. def initialize_excellon(obj_init, app):
  4087. apertures = {}
  4088. apid = 10
  4089. for tool in obj.tools:
  4090. apertures[str(apid)] = {}
  4091. apertures[str(apid)]['geometry'] = []
  4092. for geo in obj.tools[tool]['solid_geometry']:
  4093. new_el = {}
  4094. new_el['solid'] = geo
  4095. new_el['follow'] = geo.exterior
  4096. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4097. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4098. apertures[str(apid)]['type'] = 'C'
  4099. apid += 1
  4100. # create solid_geometry
  4101. solid_geometry = []
  4102. for apid in apertures:
  4103. for geo_el in apertures[apid]['geometry']:
  4104. solid_geometry.append(geo_el['solid'])
  4105. solid_geometry = MultiPolygon(solid_geometry)
  4106. solid_geometry = solid_geometry.buffer(0.0000001)
  4107. obj_init.solid_geometry = deepcopy(solid_geometry)
  4108. obj_init.apertures = deepcopy(apertures)
  4109. # clear the working objects (perhaps not necessary due of Python GC)
  4110. apertures.clear()
  4111. if not self.collection.get_selected():
  4112. log.warning("App.convert_any2gerber --> No object selected")
  4113. self.inform.emit('[WARNING_NOTCL] %s' %
  4114. _("No object is selected. Select an object and try again."))
  4115. return
  4116. for obj in self.collection.get_selected():
  4117. obj_name = obj.options["name"]
  4118. try:
  4119. if isinstance(obj, ExcellonObject):
  4120. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4121. elif isinstance(obj, GeometryObject):
  4122. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4123. else:
  4124. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4125. except Exception as e:
  4126. return "Operation failed: %s" % str(e)
  4127. def abort_all_tasks(self):
  4128. """
  4129. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4130. on the first possible occasion.
  4131. :return:
  4132. """
  4133. if self.abort_flag is False:
  4134. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4135. self.abort_flag = True
  4136. self.cleanup.emit()
  4137. def app_is_idle(self):
  4138. if self.abort_flag:
  4139. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4140. self.abort_flag = False
  4141. def on_selectall(self):
  4142. """
  4143. Will draw a selection box shape around the selected objects.
  4144. :return:
  4145. """
  4146. self.defaults.report_usage("on_selectall()")
  4147. # delete the possible selection box around a possible selected object
  4148. self.delete_selection_shape()
  4149. for name in self.collection.get_names():
  4150. self.collection.set_active(name)
  4151. curr_sel_obj = self.collection.get_by_name(name)
  4152. # create the selection box around the selected object
  4153. if self.defaults['global_selection_shape'] is True:
  4154. self.draw_selection_shape(curr_sel_obj)
  4155. def on_preferences(self):
  4156. """
  4157. Adds the Preferences in a Tab in Plot Area
  4158. :return:
  4159. """
  4160. # add the tab if it was closed
  4161. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4162. # delete the absolute and relative position and messages in the infobar
  4163. self.ui.position_label.setText("")
  4164. # self.ui.rel_position_label.setText("")
  4165. # Switch plot_area to preferences page
  4166. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4167. # self.ui.show()
  4168. # detect changes in the preferences
  4169. for idx in range(self.ui.pref_tab_area.count()):
  4170. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4171. try:
  4172. try:
  4173. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4174. except (TypeError, AttributeError):
  4175. pass
  4176. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4177. except AttributeError:
  4178. pass
  4179. try:
  4180. try:
  4181. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4182. except (TypeError, AttributeError):
  4183. pass
  4184. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4185. except AttributeError:
  4186. pass
  4187. try:
  4188. try:
  4189. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4190. except (TypeError, AttributeError):
  4191. pass
  4192. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4193. except AttributeError:
  4194. pass
  4195. try:
  4196. try:
  4197. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4198. except (TypeError, AttributeError):
  4199. pass
  4200. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4201. except AttributeError:
  4202. pass
  4203. try:
  4204. try:
  4205. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4206. except (TypeError, AttributeError):
  4207. pass
  4208. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4209. except AttributeError:
  4210. pass
  4211. def on_tools_database(self, source='app'):
  4212. """
  4213. Adds the Tools Database in a Tab in Plot Area.
  4214. :return:
  4215. """
  4216. for idx in range(self.ui.plot_tab_area.count()):
  4217. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4218. # there can be only one instance of Tools Database at one time
  4219. return
  4220. if source == 'app':
  4221. self.tools_db_tab = ToolsDB2(
  4222. app=self,
  4223. parent=self.ui,
  4224. callback_on_edited=self.on_tools_db_edited,
  4225. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4226. )
  4227. elif source == 'ncc':
  4228. self.tools_db_tab = ToolsDB2(
  4229. app=self,
  4230. parent=self.ui,
  4231. callback_on_edited=self.on_tools_db_edited,
  4232. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4233. )
  4234. elif source == 'paint':
  4235. self.tools_db_tab = ToolsDB2(
  4236. app=self,
  4237. parent=self.ui,
  4238. callback_on_edited=self.on_tools_db_edited,
  4239. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4240. )
  4241. # add the tab if it was closed
  4242. try:
  4243. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4244. self.tools_db_tab.setObjectName("database_tab")
  4245. except Exception as e:
  4246. log.debug("App.on_tools_database() --> %s" % str(e))
  4247. return
  4248. # delete the absolute and relative position and messages in the infobar
  4249. self.ui.position_label.setText("")
  4250. # self.ui.rel_position_label.setText("")
  4251. # Switch plot_area to preferences page
  4252. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4253. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4254. self.tools_db_tab.ui_connect()
  4255. def on_tools_db_edited(self):
  4256. """
  4257. Executed whenever a tool is edited in Tools Database.
  4258. Will color the text of the Tools Database tab to Red color.
  4259. :return:
  4260. """
  4261. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4262. for idx in range(self.ui.plot_tab_area.count()):
  4263. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4264. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4265. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4266. self.tools_db_changed_flag = True
  4267. def on_geometry_tool_add_from_db_executed(self, tool):
  4268. """
  4269. Here add the tool from DB in the selected geometry object.
  4270. :return:
  4271. """
  4272. tool_from_db = deepcopy(tool)
  4273. obj = self.collection.get_active()
  4274. if isinstance(obj, GeometryObject):
  4275. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4276. # close the tab and delete it
  4277. for idx in range(self.ui.plot_tab_area.count()):
  4278. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4279. wdg = self.ui.plot_tab_area.widget(idx)
  4280. wdg.deleteLater()
  4281. self.ui.plot_tab_area.removeTab(idx)
  4282. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4283. else:
  4284. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4285. def on_plot_area_tab_closed(self, tab_obj_name):
  4286. """
  4287. Executed whenever a QTab is closed in the Plot Area.
  4288. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4289. :return:
  4290. """
  4291. if tab_obj_name == "preferences_tab":
  4292. self.preferencesUiManager.on_close_preferences_tab()
  4293. elif tab_obj_name == "database_tab":
  4294. # disconnect the signals from the table widget in tab
  4295. self.tools_db_tab.ui_disconnect()
  4296. if self.tools_db_changed_flag is True:
  4297. msgbox = QtWidgets.QMessageBox()
  4298. msgbox.setText(_("One or more Tools are edited.\n"
  4299. "Do you want to update the Tools Database?"))
  4300. msgbox.setWindowTitle(_("Save Tools Database"))
  4301. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4302. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4303. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4304. msgbox.setDefaultButton(bt_yes)
  4305. msgbox.exec_()
  4306. response = msgbox.clickedButton()
  4307. if response == bt_yes:
  4308. self.tools_db_tab.on_save_tools_db()
  4309. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4310. else:
  4311. self.tools_db_changed_flag = False
  4312. self.inform.emit('')
  4313. return
  4314. self.tools_db_tab.deleteLater()
  4315. elif tab_obj_name == "text_editor_tab":
  4316. self.toggle_codeeditor = False
  4317. elif tab_obj_name == "bookmarks_tab":
  4318. self.book_dialog_tab.rebuild_actions()
  4319. self.book_dialog_tab.deleteLater()
  4320. else:
  4321. return
  4322. # def on_plotarea_tab_closed(self, tab_idx):
  4323. # """
  4324. #
  4325. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4326. # :return:
  4327. # """
  4328. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4329. #
  4330. # if widget is not None:
  4331. # widget.deleteLater()
  4332. # self.ui.plot_tab_area.removeTab(tab_idx)
  4333. def on_flipy(self):
  4334. """
  4335. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4336. :return:
  4337. """
  4338. self.defaults.report_usage("on_flipy()")
  4339. obj_list = self.collection.get_selected()
  4340. xminlist = []
  4341. yminlist = []
  4342. xmaxlist = []
  4343. ymaxlist = []
  4344. if not obj_list:
  4345. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4346. else:
  4347. try:
  4348. # first get a bounding box to fit all
  4349. for obj in obj_list:
  4350. xmin, ymin, xmax, ymax = obj.bounds()
  4351. xminlist.append(xmin)
  4352. yminlist.append(ymin)
  4353. xmaxlist.append(xmax)
  4354. ymaxlist.append(ymax)
  4355. # get the minimum x,y and maximum x,y for all objects selected
  4356. xminimal = min(xminlist)
  4357. yminimal = min(yminlist)
  4358. xmaximal = max(xmaxlist)
  4359. ymaximal = max(ymaxlist)
  4360. px = 0.5 * (xminimal + xmaximal)
  4361. py = 0.5 * (yminimal + ymaximal)
  4362. # execute mirroring
  4363. for obj in obj_list:
  4364. obj.mirror('X', [px, py])
  4365. obj.plot()
  4366. self.app_obj.object_changed.emit(obj)
  4367. self.inform.emit('[success] %s' %
  4368. _("Flip on Y axis done."))
  4369. except Exception as e:
  4370. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4371. return
  4372. def on_flipx(self):
  4373. """
  4374. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4375. :return:
  4376. """
  4377. self.defaults.report_usage("on_flipx()")
  4378. obj_list = self.collection.get_selected()
  4379. xminlist = []
  4380. yminlist = []
  4381. xmaxlist = []
  4382. ymaxlist = []
  4383. if not obj_list:
  4384. self.inform.emit('[WARNING_NOTCL] %s' %
  4385. _("No object selected to Flip on X axis."))
  4386. else:
  4387. try:
  4388. # first get a bounding box to fit all
  4389. for obj in obj_list:
  4390. xmin, ymin, xmax, ymax = obj.bounds()
  4391. xminlist.append(xmin)
  4392. yminlist.append(ymin)
  4393. xmaxlist.append(xmax)
  4394. ymaxlist.append(ymax)
  4395. # get the minimum x,y and maximum x,y for all objects selected
  4396. xminimal = min(xminlist)
  4397. yminimal = min(yminlist)
  4398. xmaximal = max(xmaxlist)
  4399. ymaximal = max(ymaxlist)
  4400. px = 0.5 * (xminimal + xmaximal)
  4401. py = 0.5 * (yminimal + ymaximal)
  4402. # execute mirroring
  4403. for obj in obj_list:
  4404. obj.mirror('Y', [px, py])
  4405. obj.plot()
  4406. self.app_obj.object_changed.emit(obj)
  4407. self.inform.emit('[success] %s' %
  4408. _("Flip on X axis done."))
  4409. except Exception as e:
  4410. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4411. return
  4412. def on_rotate(self, silent=False, preset=None):
  4413. """
  4414. Executed when Options -> Rotate Selection menu entry is clicked.
  4415. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4416. :param preset: A value to be used as predefined angle for rotation.
  4417. :return:
  4418. """
  4419. self.defaults.report_usage("on_rotate()")
  4420. obj_list = self.collection.get_selected()
  4421. xminlist = []
  4422. yminlist = []
  4423. xmaxlist = []
  4424. ymaxlist = []
  4425. if not obj_list:
  4426. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4427. else:
  4428. if silent is False:
  4429. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4430. min=-360, max=360, decimals=4,
  4431. init_val=float(self.defaults['tools_transform_rotate']))
  4432. num, ok = rotatebox.get_value()
  4433. else:
  4434. num = preset
  4435. ok = True
  4436. if ok:
  4437. try:
  4438. # first get a bounding box to fit all
  4439. for obj in obj_list:
  4440. xmin, ymin, xmax, ymax = obj.bounds()
  4441. xminlist.append(xmin)
  4442. yminlist.append(ymin)
  4443. xmaxlist.append(xmax)
  4444. ymaxlist.append(ymax)
  4445. # get the minimum x,y and maximum x,y for all objects selected
  4446. xminimal = min(xminlist)
  4447. yminimal = min(yminlist)
  4448. xmaximal = max(xmaxlist)
  4449. ymaximal = max(ymaxlist)
  4450. px = 0.5 * (xminimal + xmaximal)
  4451. py = 0.5 * (yminimal + ymaximal)
  4452. for sel_obj in obj_list:
  4453. sel_obj.rotate(-float(num), point=(px, py))
  4454. sel_obj.plot()
  4455. self.app_obj.object_changed.emit(sel_obj)
  4456. self.inform.emit('[success] %s' % _("Rotation done."))
  4457. except Exception as e:
  4458. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4459. return
  4460. def on_skewx(self):
  4461. """
  4462. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4463. :return:
  4464. """
  4465. self.defaults.report_usage("on_skewx()")
  4466. obj_list = self.collection.get_selected()
  4467. xminlist = []
  4468. yminlist = []
  4469. if not obj_list:
  4470. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4471. else:
  4472. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4473. min=-360, max=360, decimals=4,
  4474. init_val=float(self.defaults['tools_transform_skew_x']))
  4475. num, ok = skewxbox.get_value()
  4476. if ok:
  4477. # first get a bounding box to fit all
  4478. for obj in obj_list:
  4479. xmin, ymin, xmax, ymax = obj.bounds()
  4480. xminlist.append(xmin)
  4481. yminlist.append(ymin)
  4482. # get the minimum x,y and maximum x,y for all objects selected
  4483. xminimal = min(xminlist)
  4484. yminimal = min(yminlist)
  4485. for obj in obj_list:
  4486. obj.skew(num, 0, point=(xminimal, yminimal))
  4487. obj.plot()
  4488. self.app_obj.object_changed.emit(obj)
  4489. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4490. def on_skewy(self):
  4491. """
  4492. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4493. :return:
  4494. """
  4495. self.defaults.report_usage("on_skewy()")
  4496. obj_list = self.collection.get_selected()
  4497. xminlist = []
  4498. yminlist = []
  4499. if not obj_list:
  4500. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4501. else:
  4502. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4503. min=-360, max=360, decimals=4,
  4504. init_val=float(self.defaults['tools_transform_skew_y']))
  4505. num, ok = skewybox.get_value()
  4506. if ok:
  4507. # first get a bounding box to fit all
  4508. for obj in obj_list:
  4509. xmin, ymin, xmax, ymax = obj.bounds()
  4510. xminlist.append(xmin)
  4511. yminlist.append(ymin)
  4512. # get the minimum x,y and maximum x,y for all objects selected
  4513. xminimal = min(xminlist)
  4514. yminimal = min(yminlist)
  4515. for obj in obj_list:
  4516. obj.skew(0, num, point=(xminimal, yminimal))
  4517. obj.plot()
  4518. self.app_obj.object_changed.emit(obj)
  4519. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4520. def on_plots_updated(self):
  4521. """
  4522. Callback used to report when the plots have changed.
  4523. Adjust axes and zooms to fit.
  4524. :return: None
  4525. """
  4526. if self.is_legacy is False:
  4527. self.plotcanvas.update()
  4528. else:
  4529. self.plotcanvas.auto_adjust_axes()
  4530. self.on_zoom_fit()
  4531. self.collection.update_view()
  4532. # self.inform.emit(_("Plots updated ..."))
  4533. def on_toolbar_replot(self):
  4534. """
  4535. Callback for toolbar button. Re-plots all objects.
  4536. :return: None
  4537. """
  4538. self.defaults.report_usage("on_toolbar_replot")
  4539. self.log.debug("on_toolbar_replot()")
  4540. try:
  4541. self.collection.get_active().read_form()
  4542. except AttributeError:
  4543. self.log.debug("on_toolbar_replot(): AttributeError")
  4544. pass
  4545. self.plot_all()
  4546. def grid_status(self):
  4547. return True if self.ui.grid_snap_btn.isChecked() else False
  4548. def populate_cmenu_grids(self):
  4549. units = self.defaults['units'].lower()
  4550. # for act in self.ui.cmenu_gridmenu.actions():
  4551. # act.triggered.disconnect()
  4552. self.ui.cmenu_gridmenu.clear()
  4553. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4554. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4555. _("Grid On/Off"))
  4556. grid_toggle.setCheckable(True)
  4557. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4558. self.ui.cmenu_gridmenu.addSeparator()
  4559. for grid in sorted_list:
  4560. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4561. "%s" % str(grid))
  4562. action.triggered.connect(self.set_grid)
  4563. self.ui.cmenu_gridmenu.addSeparator()
  4564. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4565. _("Add"))
  4566. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4567. _("Delete"))
  4568. grid_add.triggered.connect(self.on_grid_add)
  4569. grid_delete.triggered.connect(self.on_grid_delete)
  4570. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4571. def set_grid(self):
  4572. menu_action = self.sender()
  4573. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4574. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4575. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4576. def on_grid_add(self):
  4577. # ## Current application units in lower Case
  4578. units = self.defaults['units'].lower()
  4579. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4580. text=_('Enter a Grid Value:'),
  4581. min=0.0000, max=99.9999, decimals=4)
  4582. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4583. val, ok = grid_add_popup.get_value()
  4584. if ok:
  4585. if float(val) == 0:
  4586. self.inform.emit('[WARNING_NOTCL] %s' %
  4587. _("Please enter a grid value with non-zero value, in Float format."))
  4588. return
  4589. else:
  4590. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4591. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4592. self.inform.emit('[success] %s...' % _("New Grid added"))
  4593. else:
  4594. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4595. else:
  4596. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4597. def on_grid_delete(self):
  4598. # ## Current application units in lower Case
  4599. units = self.defaults['units'].lower()
  4600. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4601. text='Enter a Grid Value:',
  4602. min=0.0000, max=99.9999, decimals=4)
  4603. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4604. val, ok = grid_del_popup.get_value()
  4605. if ok:
  4606. if float(val) == 0:
  4607. self.inform.emit('[WARNING_NOTCL] %s' %
  4608. _("Please enter a grid value with non-zero value, in Float format."))
  4609. return
  4610. else:
  4611. try:
  4612. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4613. except ValueError:
  4614. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4615. return
  4616. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4617. else:
  4618. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4619. def on_shortcut_list(self):
  4620. self.defaults.report_usage("on_shortcut_list()")
  4621. # add the tab if it was closed
  4622. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4623. # delete the absolute and relative position and messages in the infobar
  4624. self.ui.position_label.setText("")
  4625. # self.ui.rel_position_label.setText("")
  4626. # Switch plot_area to preferences page
  4627. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4628. # self.ui.show()
  4629. def on_select_tab(self, name):
  4630. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4631. if self.ui.splitter.sizes()[0] == 0:
  4632. self.ui.splitter.setSizes([1, 1])
  4633. else:
  4634. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4635. self.ui.splitter.setSizes([0, 1])
  4636. if name == 'project':
  4637. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4638. elif name == 'selected':
  4639. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4640. elif name == 'tool':
  4641. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4642. def on_copy_name(self):
  4643. self.defaults.report_usage("on_copy_name()")
  4644. obj = self.collection.get_active()
  4645. try:
  4646. name = obj.options["name"]
  4647. except AttributeError:
  4648. log.debug("on_copy_name() --> No object selected to copy it's name")
  4649. self.inform.emit('[WARNING_NOTCL]%s' %
  4650. _(" No object selected to copy it's name"))
  4651. return
  4652. self.clipboard.setText(name)
  4653. self.inform.emit(_("Name copied on clipboard ..."))
  4654. def on_mouse_click_over_plot(self, event):
  4655. """
  4656. Default actions are:
  4657. :param event: Contains information about the event, like which button
  4658. was clicked, the pixel coordinates and the axes coordinates.
  4659. :return: None
  4660. """
  4661. self.pos = []
  4662. if self.is_legacy is False:
  4663. event_pos = event.pos
  4664. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4665. # # Set the mouse button for panning
  4666. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4667. else:
  4668. event_pos = (event.xdata, event.ydata)
  4669. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4670. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4671. # So it can receive key presses
  4672. self.plotcanvas.native.setFocus()
  4673. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4674. if self.grid_status():
  4675. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4676. else:
  4677. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4678. try:
  4679. if event.button == 1:
  4680. # Reset here the relative coordinates so there is a new reference on the click position
  4681. if self.rel_point1 is None:
  4682. self.rel_point1 = self.pos
  4683. else:
  4684. self.rel_point2 = copy(self.rel_point1)
  4685. self.rel_point1 = self.pos
  4686. self.on_mouse_move_over_plot(event, origin_click=True)
  4687. except Exception as e:
  4688. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4689. def on_mouse_double_click_over_plot(self, event):
  4690. if event.button == 1:
  4691. self.doubleclick = True
  4692. def on_mouse_move_over_plot(self, event, origin_click=None):
  4693. """
  4694. Callback for the mouse motion event over the plot.
  4695. :param event: Contains information about the event.
  4696. :param origin_click
  4697. :return: None
  4698. """
  4699. if self.is_legacy is False:
  4700. event_pos = event.pos
  4701. if self.defaults["global_pan_button"] == '2':
  4702. pan_button = 2
  4703. else:
  4704. pan_button = 3
  4705. self.event_is_dragging = event.is_dragging
  4706. else:
  4707. event_pos = (event.xdata, event.ydata)
  4708. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4709. if self.defaults["global_pan_button"] == '2':
  4710. pan_button = 3
  4711. else:
  4712. pan_button = 2
  4713. self.event_is_dragging = self.plotcanvas.is_dragging
  4714. # So it can receive key presses but not when the Tcl Shell is active
  4715. if not self.ui.shell_dock.isVisible():
  4716. if not self.plotcanvas.native.hasFocus():
  4717. self.plotcanvas.native.setFocus()
  4718. self.pos_jump = event_pos
  4719. self.ui.popMenu.mouse_is_panning = False
  4720. if origin_click is None:
  4721. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4722. if event.button == pan_button and self.event_is_dragging == 1:
  4723. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4724. if self.ui.popMenu.popup_active:
  4725. self.ui.popMenu.popup_active = False
  4726. return
  4727. self.ui.popMenu.mouse_is_panning = True
  4728. return
  4729. if self.rel_point1 is not None:
  4730. try: # May fail in case mouse not within axes
  4731. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4732. if pos_canvas[0] is None or pos_canvas[1] is None:
  4733. return
  4734. if self.grid_status():
  4735. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4736. # Update cursor
  4737. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4738. symbol='++', edge_color=self.cursor_color_3D,
  4739. edge_width=self.defaults["global_cursor_width"],
  4740. size=self.defaults["global_cursor_size"])
  4741. else:
  4742. pos = (pos_canvas[0], pos_canvas[1])
  4743. self.dx = pos[0] - float(self.rel_point1[0])
  4744. self.dy = pos[1] - float(self.rel_point1[1])
  4745. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4746. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4747. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4748. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4749. units = self.defaults["units"].lower()
  4750. self.plotcanvas.text_hud.text = \
  4751. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4752. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4753. self.mouse = [pos[0], pos[1]]
  4754. # if the mouse is moved and the LMB is clicked then the action is a selection
  4755. if self.event_is_dragging == 1 and event.button == 1:
  4756. self.delete_selection_shape()
  4757. if self.dx < 0:
  4758. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4759. face_color=self.defaults['global_alt_sel_fill'])
  4760. self.selection_type = False
  4761. elif self.dx >= 0:
  4762. self.draw_moving_selection_shape(self.pos, pos)
  4763. self.selection_type = True
  4764. else:
  4765. self.selection_type = None
  4766. else:
  4767. self.selection_type = None
  4768. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  4769. if self.defaults['global_hover']:
  4770. for obj in self.collection.get_list():
  4771. try:
  4772. # select the object(s) only if it is enabled (plotted)
  4773. if obj.options['plot']:
  4774. if obj not in self.collection.get_selected():
  4775. poly_obj = Polygon(
  4776. [(obj.options['xmin'], obj.options['ymin']),
  4777. (obj.options['xmax'], obj.options['ymin']),
  4778. (obj.options['xmax'], obj.options['ymax']),
  4779. (obj.options['xmin'], obj.options['ymax'])]
  4780. )
  4781. if Point(pos).within(poly_obj):
  4782. if obj.isHovering is False:
  4783. obj.isHovering = True
  4784. obj.notHovering = True
  4785. # create the selection box around the selected object
  4786. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4787. else:
  4788. if obj.notHovering is True:
  4789. obj.notHovering = False
  4790. obj.isHovering = False
  4791. self.delete_hover_shape()
  4792. except Exception:
  4793. # the Exception here will happen if we try to select on screen and we have an
  4794. # newly (and empty) just created Geometry or Excellon object that do not have the
  4795. # xmin, xmax, ymin, ymax options.
  4796. # In this case poly_obj creation (see above) will fail
  4797. pass
  4798. except Exception as e:
  4799. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4800. self.ui.position_label.setText("")
  4801. # self.ui.rel_position_label.setText("")
  4802. self.mouse = None
  4803. def on_mouse_click_release_over_plot(self, event):
  4804. """
  4805. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4806. and has been registered in ''self.__init__()''.
  4807. :param event: contains information about the event.
  4808. :return:
  4809. """
  4810. if self.is_legacy is False:
  4811. event_pos = event.pos
  4812. right_button = 2
  4813. else:
  4814. event_pos = (event.xdata, event.ydata)
  4815. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4816. right_button = 3
  4817. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4818. if self.grid_status():
  4819. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4820. else:
  4821. pos = (pos_canvas[0], pos_canvas[1])
  4822. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4823. # canvas menu
  4824. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  4825. self.ui.popMenu.mouse_is_panning = False
  4826. self.cursor = QtGui.QCursor()
  4827. self.populate_cmenu_grids()
  4828. self.ui.popMenu.popup(self.cursor.pos())
  4829. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4830. # selection and then select a type of selection ("enclosing" or "touching")
  4831. if event.button == 1: # left click
  4832. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4833. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4834. if modifiers == QtCore.Qt.ShiftModifier:
  4835. # do not auto open the Project Tab
  4836. self.click_noproject = True
  4837. self.clipboard.setText(
  4838. self.defaults["global_point_clipboard_format"] %
  4839. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  4840. )
  4841. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  4842. return
  4843. if self.doubleclick is True:
  4844. self.doubleclick = False
  4845. if self.collection.get_selected():
  4846. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4847. if self.ui.splitter.sizes()[0] == 0:
  4848. self.ui.splitter.setSizes([1, 1])
  4849. try:
  4850. # delete the selection shape(S) as it may be in the way
  4851. self.delete_selection_shape()
  4852. self.delete_hover_shape()
  4853. except Exception as e:
  4854. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  4855. return
  4856. else:
  4857. # WORKAROUND for LEGACY MODE
  4858. if self.is_legacy is True:
  4859. # if there is no move on canvas then we have no dragging selection
  4860. if self.dx == 0 or self.dy == 0:
  4861. self.selection_type = None
  4862. if self.selection_type is not None:
  4863. try:
  4864. self.selection_area_handler(self.pos, pos, self.selection_type)
  4865. self.selection_type = None
  4866. except Exception as e:
  4867. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  4868. return
  4869. else:
  4870. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4871. if key_modifier == QtCore.Qt.ShiftModifier:
  4872. mod_key = 'Shift'
  4873. elif key_modifier == QtCore.Qt.ControlModifier:
  4874. mod_key = 'Control'
  4875. else:
  4876. mod_key = None
  4877. try:
  4878. if self.command_active is None:
  4879. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4880. # deselect, and if it's not selected then it will be selected
  4881. # If there is no active command (self.command_active is None) then we check if we clicked
  4882. # on a object by checking the bounding limits against mouse click position
  4883. if mod_key == self.defaults["global_mselect_key"]:
  4884. self.select_objects(key='multisel')
  4885. else:
  4886. # If there is no active command (self.command_active is None) then we check if
  4887. # we clicked on a object by checking the bounding limits against mouse click position
  4888. self.select_objects()
  4889. self.delete_hover_shape()
  4890. except Exception as e:
  4891. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  4892. return
  4893. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4894. """
  4895. :param start_pos: mouse position when the selection LMB click was done
  4896. :param end_pos: mouse position when the left mouse button is released
  4897. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4898. :return:
  4899. """
  4900. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4901. # delete previous selection shape
  4902. self.delete_selection_shape()
  4903. # make all objects inactive
  4904. self.collection.set_all_inactive()
  4905. for obj in self.collection.get_list():
  4906. try:
  4907. # select the object(s) only if it is enabled (plotted)
  4908. if obj.options['plot']:
  4909. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4910. (obj.options['xmax'], obj.options['ymin']),
  4911. (obj.options['xmax'], obj.options['ymax']),
  4912. (obj.options['xmin'], obj.options['ymax'])])
  4913. if sel_type is True:
  4914. if poly_obj.within(poly_selection):
  4915. # create the selection box around the selected object
  4916. if self.defaults['global_selection_shape'] is True:
  4917. self.draw_selection_shape(obj)
  4918. self.collection.set_active(obj.options['name'])
  4919. else:
  4920. if poly_selection.intersects(poly_obj):
  4921. # create the selection box around the selected object
  4922. if self.defaults['global_selection_shape'] is True:
  4923. self.draw_selection_shape(obj)
  4924. self.collection.set_active(obj.options['name'])
  4925. obj.selection_shape_drawn = True
  4926. except Exception as e:
  4927. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4928. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4929. # In this case poly_obj creation (see above) will fail
  4930. log.debug("App.selection_area_handler() --> %s" % str(e))
  4931. def select_objects(self, key=None):
  4932. """
  4933. Will select objects clicked on canvas
  4934. :param key: for future use in cumulative selection
  4935. :return:
  4936. """
  4937. # list where we store the overlapped objects under our mouse left click position
  4938. if key is None:
  4939. self.objects_under_the_click_list = []
  4940. # Populate the list with the overlapped objects on the click position
  4941. curr_x, curr_y = self.pos
  4942. for obj in self.all_objects_list:
  4943. # ScriptObject and DocumentObject objects can't be selected
  4944. if obj.kind == 'script' or obj.kind == 'document':
  4945. continue
  4946. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  4947. continue
  4948. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4949. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4950. if obj.options['name'] not in self.objects_under_the_click_list:
  4951. if obj.options['plot']:
  4952. # add objects to the objects_under_the_click list only if the object is plotted
  4953. # (active and not disabled)
  4954. self.objects_under_the_click_list.append(obj.options['name'])
  4955. try:
  4956. if self.objects_under_the_click_list:
  4957. curr_sel_obj = self.collection.get_active()
  4958. # case when there is only an object under the click and we toggle it
  4959. if len(self.objects_under_the_click_list) == 1:
  4960. if curr_sel_obj is None:
  4961. self.collection.set_active(self.objects_under_the_click_list[0])
  4962. curr_sel_obj = self.collection.get_active()
  4963. # create the selection box around the selected object
  4964. if self.defaults['global_selection_shape'] is True:
  4965. self.draw_selection_shape(curr_sel_obj)
  4966. curr_sel_obj.selection_shape_drawn = True
  4967. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  4968. self.collection.on_objects_selection(False)
  4969. self.delete_selection_shape()
  4970. curr_sel_obj.selection_shape_drawn = False
  4971. self.collection.set_active(self.objects_under_the_click_list[0])
  4972. curr_sel_obj = self.collection.get_active()
  4973. # create the selection box around the selected object
  4974. if self.defaults['global_selection_shape'] is True:
  4975. self.draw_selection_shape(curr_sel_obj)
  4976. curr_sel_obj.selection_shape_drawn = True
  4977. self.selected_message(curr_sel_obj=curr_sel_obj)
  4978. elif curr_sel_obj.selection_shape_drawn is False:
  4979. if self.defaults['global_selection_shape'] is True:
  4980. self.draw_selection_shape(curr_sel_obj)
  4981. curr_sel_obj.selection_shape_drawn = True
  4982. else:
  4983. self.collection.on_objects_selection(False)
  4984. self.delete_selection_shape()
  4985. if self.call_source != 'app':
  4986. self.call_source = 'app'
  4987. self.selected_message(curr_sel_obj=curr_sel_obj)
  4988. else:
  4989. # If there is no selected object
  4990. # make active the first element of the overlapped objects list
  4991. if self.collection.get_active() is None:
  4992. self.collection.set_active(self.objects_under_the_click_list[0])
  4993. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  4994. name_sel_obj = self.collection.get_active().options['name']
  4995. # In case that there is a selected object but it is not in the overlapped object list
  4996. # make that object inactive and activate the first element in the overlapped object list
  4997. if name_sel_obj not in self.objects_under_the_click_list:
  4998. self.collection.set_inactive(name_sel_obj)
  4999. name_sel_obj = self.objects_under_the_click_list[0]
  5000. self.collection.set_active(name_sel_obj)
  5001. else:
  5002. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5003. self.collection.set_all_inactive()
  5004. self.collection.set_active(
  5005. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5006. curr_sel_obj = self.collection.get_active()
  5007. # delete the possible selection box around a possible selected object
  5008. self.delete_selection_shape()
  5009. curr_sel_obj.selection_shape_drawn = False
  5010. # create the selection box around the selected object
  5011. if self.defaults['global_selection_shape'] is True:
  5012. self.draw_selection_shape(curr_sel_obj)
  5013. curr_sel_obj.selection_shape_drawn = True
  5014. self.selected_message(curr_sel_obj=curr_sel_obj)
  5015. else:
  5016. # deselect everything
  5017. self.collection.on_objects_selection(False)
  5018. # delete the possible selection box around a possible selected object
  5019. self.delete_selection_shape()
  5020. for o in self.collection.get_list():
  5021. o.selection_shape_drawn = False
  5022. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5023. # only when working on App
  5024. if self.call_source == 'app':
  5025. if self.click_noproject is False:
  5026. # if the Tool Tab is in focus don't change focus to Project Tab
  5027. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5028. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5029. else:
  5030. # restore auto open the Project Tab
  5031. self.click_noproject = False
  5032. # delete any text in the status bar, implicitly the last object name that was selected
  5033. # self.inform.emit("")
  5034. else:
  5035. self.call_source = 'app'
  5036. except Exception as e:
  5037. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5038. def selected_message(self, curr_sel_obj):
  5039. if curr_sel_obj:
  5040. if curr_sel_obj.kind == 'gerber':
  5041. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5042. color='green',
  5043. name=str(curr_sel_obj.options['name']),
  5044. tx=_("selected"))
  5045. )
  5046. elif curr_sel_obj.kind == 'excellon':
  5047. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5048. color='brown',
  5049. name=str(curr_sel_obj.options['name']),
  5050. tx=_("selected"))
  5051. )
  5052. elif curr_sel_obj.kind == 'cncjob':
  5053. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5054. color='blue',
  5055. name=str(curr_sel_obj.options['name']),
  5056. tx=_("selected"))
  5057. )
  5058. elif curr_sel_obj.kind == 'geometry':
  5059. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5060. color='red',
  5061. name=str(curr_sel_obj.options['name']),
  5062. tx=_("selected"))
  5063. )
  5064. def delete_hover_shape(self):
  5065. self.hover_shapes.clear()
  5066. self.hover_shapes.redraw()
  5067. def draw_hover_shape(self, sel_obj, color=None):
  5068. """
  5069. :param sel_obj: The object for which the hover shape must be drawn
  5070. :param color: The color of the hover shape
  5071. :return: None
  5072. """
  5073. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5074. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5075. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5076. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5077. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5078. if self.defaults['units'].upper() == 'MM':
  5079. hover_rect = hover_rect.buffer(-0.1)
  5080. hover_rect = hover_rect.buffer(0.2)
  5081. else:
  5082. hover_rect = hover_rect.buffer(-0.00393)
  5083. hover_rect = hover_rect.buffer(0.00787)
  5084. # if color:
  5085. # face = Color(color)
  5086. # face.alpha = 0.2
  5087. # outline = Color(color, alpha=0.8)
  5088. # else:
  5089. # face = Color(self.defaults['global_sel_fill'])
  5090. # face.alpha = 0.2
  5091. # outline = self.defaults['global_sel_line']
  5092. if color:
  5093. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5094. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5095. else:
  5096. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5097. outline = self.defaults['global_sel_line']
  5098. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5099. if self.is_legacy is True:
  5100. self.hover_shapes.redraw()
  5101. def delete_selection_shape(self):
  5102. self.move_tool.sel_shapes.clear()
  5103. self.move_tool.sel_shapes.redraw()
  5104. def draw_selection_shape(self, sel_obj, color=None):
  5105. """
  5106. Will draw a selection shape around the selected object.
  5107. :param sel_obj: The object for which the selection shape must be drawn
  5108. :param color: The color for the selection shape.
  5109. :return: None
  5110. """
  5111. if sel_obj is None:
  5112. return
  5113. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5114. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5115. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5116. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5117. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5118. if self.defaults['units'].upper() == 'MM':
  5119. sel_rect = sel_rect.buffer(-0.1)
  5120. sel_rect = sel_rect.buffer(0.2)
  5121. else:
  5122. sel_rect = sel_rect.buffer(-0.00393)
  5123. sel_rect = sel_rect.buffer(0.00787)
  5124. if color:
  5125. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5126. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5127. else:
  5128. if self.is_legacy is False:
  5129. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5130. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5131. else:
  5132. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5133. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5134. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5135. color=outline,
  5136. face_color=face,
  5137. update=True,
  5138. layer=0,
  5139. tolerance=None))
  5140. if self.is_legacy is True:
  5141. self.move_tool.sel_shapes.redraw()
  5142. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5143. """
  5144. Will draw a selection shape when dragging mouse on canvas.
  5145. :param old_coords: Old coordinates
  5146. :param coords: New coordinates
  5147. :param kwargs: Keyword arguments
  5148. :return:
  5149. """
  5150. if 'color' in kwargs:
  5151. color = kwargs['color']
  5152. else:
  5153. color = self.defaults['global_sel_line']
  5154. if 'face_color' in kwargs:
  5155. face_color = kwargs['face_color']
  5156. else:
  5157. face_color = self.defaults['global_sel_fill']
  5158. if 'face_alpha' in kwargs:
  5159. face_alpha = kwargs['face_alpha']
  5160. else:
  5161. face_alpha = 0.3
  5162. x0, y0 = old_coords
  5163. x1, y1 = coords
  5164. pt1 = (x0, y0)
  5165. pt2 = (x1, y0)
  5166. pt3 = (x1, y1)
  5167. pt4 = (x0, y1)
  5168. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5169. # color_t = Color(face_color)
  5170. # color_t.alpha = face_alpha
  5171. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5172. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5173. layer=0, tolerance=None)
  5174. if self.is_legacy is True:
  5175. self.move_tool.sel_shapes.redraw()
  5176. def on_file_new_click(self):
  5177. """
  5178. Callback for menu item File -> New.
  5179. Executed on clicking the Menu -> File -> New Project
  5180. :return:
  5181. """
  5182. if self.collection.get_list() and self.should_we_save:
  5183. msgbox = QtWidgets.QMessageBox()
  5184. # msgbox.setText("<B>Save changes ...</B>")
  5185. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5186. "Creating a New project will delete them.\n"
  5187. "Do you want to Save the project?"))
  5188. msgbox.setWindowTitle(_("Save changes"))
  5189. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5190. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5191. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5192. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5193. msgbox.setDefaultButton(bt_yes)
  5194. msgbox.exec_()
  5195. response = msgbox.clickedButton()
  5196. if response == bt_yes:
  5197. self.on_file_saveprojectas()
  5198. elif response == bt_cancel:
  5199. return
  5200. elif response == bt_no:
  5201. self.on_file_new()
  5202. else:
  5203. self.on_file_new()
  5204. self.inform.emit('[success] %s...' % _("New Project created"))
  5205. def on_file_new(self, cli=None):
  5206. """
  5207. Returns the application to its startup state. This method is thread-safe.
  5208. :param cli: Boolean. If True this method was run from command line
  5209. :return: None
  5210. """
  5211. self.defaults.report_usage("on_file_new")
  5212. # Remove everything from memory
  5213. App.log.debug("on_file_new()")
  5214. # close any editor that might be open
  5215. if self.call_source != 'app':
  5216. self.editor2object(cleanup=True)
  5217. # ## EDITOR section
  5218. self.geo_editor = FlatCAMGeoEditor(self)
  5219. self.exc_editor = FlatCAMExcEditor(self)
  5220. self.grb_editor = FlatCAMGrbEditor(self)
  5221. # Clear pool
  5222. self.clear_pool()
  5223. for obj in self.collection.get_list():
  5224. # delete shapes left drawn from mark shape_collections, if any
  5225. if isinstance(obj, GerberObject):
  5226. try:
  5227. for el in obj.mark_shapes:
  5228. obj.mark_shapes[el].clear(update=True)
  5229. obj.mark_shapes[el].enabled = False
  5230. del el
  5231. except AttributeError:
  5232. pass
  5233. # also delete annotation shapes, if any
  5234. elif isinstance(obj, CNCJobObject):
  5235. try:
  5236. obj.text_col.enabled = False
  5237. del obj.text_col
  5238. obj.annotation.clear(update=True)
  5239. del obj.annotation
  5240. except AttributeError:
  5241. pass
  5242. # delete the exclusion areas
  5243. self.exc_areas.clear_shapes()
  5244. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5245. self.shell.init_tcl()
  5246. # delete any selection shape on canvas
  5247. self.delete_selection_shape()
  5248. # delete all FlatCAM objects
  5249. self.collection.delete_all()
  5250. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5251. self.setup_component_editor()
  5252. # Clear project filename
  5253. self.project_filename = None
  5254. # Load the application defaults
  5255. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5256. # Re-fresh project options
  5257. self.on_options_app2project()
  5258. # Init FlatCAMTools
  5259. self.init_tools()
  5260. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5261. if cli is None:
  5262. # we need to go in reverse because once we remove a tab then the index changes
  5263. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5264. # and so on. Therefore the deletion should be done in reverse
  5265. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5266. for index in range(wdg_count, -1, -1):
  5267. try:
  5268. self.ui.plot_tab_area.closeTab(index)
  5269. except Exception as e:
  5270. log.debug("App.on_file_new() --> %s" % str(e))
  5271. # # And then add again the Plot Area
  5272. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5273. self.ui.plot_tab_area.protectTab(0)
  5274. # take the focus of the Notebook on Project Tab.
  5275. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5276. self.set_ui_title(name=_("New Project - Not saved"))
  5277. def obj_properties(self):
  5278. """
  5279. Will launch the object Properties Tool
  5280. :return:
  5281. """
  5282. self.defaults.report_usage("obj_properties()")
  5283. self.properties_tool.run(toggle=False)
  5284. def on_project_context_save(self):
  5285. """
  5286. Wrapper, will save the object function of it's type
  5287. :return:
  5288. """
  5289. obj = self.collection.get_active()
  5290. if type(obj) == GeometryObject:
  5291. self.on_file_exportdxf()
  5292. elif type(obj) == ExcellonObject:
  5293. self.on_file_saveexcellon()
  5294. elif type(obj) == CNCJobObject:
  5295. obj.on_exportgcode_button_click()
  5296. elif type(obj) == GerberObject:
  5297. self.on_file_savegerber()
  5298. elif type(obj) == ScriptObject:
  5299. self.on_file_savescript()
  5300. elif type(obj) == DocumentObject:
  5301. self.on_file_savedocument()
  5302. def obj_move(self):
  5303. """
  5304. Callback for the Move menu entry in various Context Menu's.
  5305. :return:
  5306. """
  5307. self.defaults.report_usage("obj_move()")
  5308. self.move_tool.run(toggle=False)
  5309. def on_fileopengerber(self, signal, name=None):
  5310. """
  5311. File menu callback for opening a Gerber.
  5312. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5313. :param name:
  5314. :return: None
  5315. """
  5316. self.defaults.report_usage("on_fileopengerber")
  5317. App.log.debug("on_fileopengerber()")
  5318. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5319. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5320. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5321. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5322. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5323. "*.mil);;" \
  5324. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5325. "Allegro Files (*.art);;" \
  5326. "Mentor Files (*.pho *.gdo);;" \
  5327. "All Files (*.*)"
  5328. if name is None:
  5329. try:
  5330. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5331. directory=self.get_last_folder(),
  5332. filter=_filter_)
  5333. except TypeError:
  5334. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5335. filenames = [str(filename) for filename in filenames]
  5336. else:
  5337. filenames = [name]
  5338. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5339. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5340. _("Opening Gerber file.")),
  5341. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5342. color=QtGui.QColor("gray"))
  5343. if len(filenames) == 0:
  5344. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5345. else:
  5346. for filename in filenames:
  5347. if filename != '':
  5348. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5349. def on_fileopenexcellon(self, signal, name=None):
  5350. """
  5351. File menu callback for opening an Excellon file.
  5352. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5353. :param name:
  5354. :return: None
  5355. """
  5356. self.defaults.report_usage("on_fileopenexcellon")
  5357. App.log.debug("on_fileopenexcellon()")
  5358. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5359. "All Files (*.*)"
  5360. if name is None:
  5361. try:
  5362. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5363. directory=self.get_last_folder(),
  5364. filter=_filter_)
  5365. except TypeError:
  5366. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5367. filenames = [str(filename) for filename in filenames]
  5368. else:
  5369. filenames = [str(name)]
  5370. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5371. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5372. _("Opening Excellon file.")),
  5373. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5374. color=QtGui.QColor("gray"))
  5375. if len(filenames) == 0:
  5376. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5377. else:
  5378. for filename in filenames:
  5379. if filename != '':
  5380. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5381. def on_fileopengcode(self, signal, name=None):
  5382. """
  5383. File menu call back for opening gcode.
  5384. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5385. :param name:
  5386. :return:
  5387. """
  5388. self.defaults.report_usage("on_fileopengcode")
  5389. App.log.debug("on_fileopengcode()")
  5390. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5391. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5392. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5393. "All Files (*.*)"
  5394. if name is None:
  5395. try:
  5396. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5397. directory=self.get_last_folder(),
  5398. filter=_filter_)
  5399. except TypeError:
  5400. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5401. filenames = [str(filename) for filename in filenames]
  5402. else:
  5403. filenames = [name]
  5404. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5405. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5406. _("Opening G-Code file.")),
  5407. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5408. color=QtGui.QColor("gray"))
  5409. if len(filenames) == 0:
  5410. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5411. else:
  5412. for filename in filenames:
  5413. if filename != '':
  5414. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5415. def on_file_openproject(self, signal):
  5416. """
  5417. File menu callback for opening a project.
  5418. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5419. :return: None
  5420. """
  5421. self.defaults.report_usage("on_file_openproject")
  5422. App.log.debug("on_file_openproject()")
  5423. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5424. try:
  5425. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5426. directory=self.get_last_folder(), filter=_filter_)
  5427. except TypeError:
  5428. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5429. # The Qt methods above will return a QString which can cause problems later.
  5430. # So far json.dump() will fail to serialize it.
  5431. # TODO: Improve the serialization methods and remove this fix.
  5432. filename = str(filename)
  5433. if filename == "":
  5434. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5435. else:
  5436. # self.worker_task.emit({'fcn': self.open_project,
  5437. # 'params': [filename]})
  5438. # The above was failing because open_project() is not
  5439. # thread safe. The new_project()
  5440. self.open_project(filename)
  5441. def on_fileopenhpgl2(self, signal, name=None):
  5442. """
  5443. File menu callback for opening a HPGL2.
  5444. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5445. :param name:
  5446. :return: None
  5447. """
  5448. self.defaults.report_usage("on_fileopenhpgl2")
  5449. App.log.debug("on_fileopenhpgl2()")
  5450. _filter_ = "HPGL2 Files (*.plt);;" \
  5451. "All Files (*.*)"
  5452. if name is None:
  5453. try:
  5454. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5455. directory=self.get_last_folder(),
  5456. filter=_filter_)
  5457. except TypeError:
  5458. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5459. filenames = [str(filename) for filename in filenames]
  5460. else:
  5461. filenames = [name]
  5462. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5463. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5464. _("Opening HPGL2 file.")),
  5465. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5466. color=QtGui.QColor("gray"))
  5467. if len(filenames) == 0:
  5468. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5469. else:
  5470. for filename in filenames:
  5471. if filename != '':
  5472. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5473. def on_file_openconfig(self, signal):
  5474. """
  5475. File menu callback for opening a config file.
  5476. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5477. :return: None
  5478. """
  5479. self.defaults.report_usage("on_file_openconfig")
  5480. App.log.debug("on_file_openconfig()")
  5481. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5482. try:
  5483. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5484. directory=self.data_path, filter=_filter_)
  5485. except TypeError:
  5486. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5487. filter=_filter_)
  5488. if filename == "":
  5489. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5490. else:
  5491. self.open_config_file(filename)
  5492. def on_file_exportsvg(self):
  5493. """
  5494. Callback for menu item File->Export SVG.
  5495. :return: None
  5496. """
  5497. self.defaults.report_usage("on_file_exportsvg")
  5498. App.log.debug("on_file_exportsvg()")
  5499. obj = self.collection.get_active()
  5500. if obj is None:
  5501. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5502. msg = _("Please Select a Geometry object to export")
  5503. msgbox = QtWidgets.QMessageBox()
  5504. msgbox.setInformativeText(msg)
  5505. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5506. msgbox.setDefaultButton(bt_ok)
  5507. msgbox.exec_()
  5508. return
  5509. # Check for more compatible types and add as required
  5510. if (not isinstance(obj, GeometryObject)
  5511. and not isinstance(obj, GerberObject)
  5512. and not isinstance(obj, CNCJobObject)
  5513. and not isinstance(obj, ExcellonObject)):
  5514. msg = '[ERROR_NOTCL] %s' % \
  5515. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5516. msgbox = QtWidgets.QMessageBox()
  5517. msgbox.setInformativeText(msg)
  5518. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5519. msgbox.setDefaultButton(bt_ok)
  5520. msgbox.exec_()
  5521. return
  5522. name = obj.options["name"]
  5523. _filter = "SVG File (*.svg);;All Files (*.*)"
  5524. try:
  5525. filename, _f = FCFileSaveDialog.get_saved_filename(
  5526. caption=_("Export SVG"),
  5527. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5528. filter=_filter)
  5529. except TypeError:
  5530. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  5531. filename = str(filename)
  5532. if filename == "":
  5533. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5534. return
  5535. else:
  5536. self.export_svg(name, filename)
  5537. if self.defaults["global_open_style"] is False:
  5538. self.file_opened.emit("SVG", filename)
  5539. self.file_saved.emit("SVG", filename)
  5540. def on_file_exportpng(self):
  5541. self.defaults.report_usage("on_file_exportpng")
  5542. App.log.debug("on_file_exportpng()")
  5543. self.date = str(datetime.today()).rpartition('.')[0]
  5544. self.date = ''.join(c for c in self.date if c not in ':-')
  5545. self.date = self.date.replace(' ', '_')
  5546. if self.is_legacy is False:
  5547. image = _screenshot()
  5548. data = np.asarray(image)
  5549. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5550. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5551. return
  5552. filter_ = "PNG File (*.png);;All Files (*.*)"
  5553. try:
  5554. filename, _f = FCFileSaveDialog.get_saved_filename(
  5555. caption=_("Export PNG Image"),
  5556. directory=self.get_last_save_folder() + '/png_' + self.date,
  5557. filter=filter_)
  5558. except TypeError:
  5559. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  5560. filename = str(filename)
  5561. if filename == "":
  5562. self.inform.emit(_("Cancelled."))
  5563. return
  5564. else:
  5565. if self.is_legacy is False:
  5566. write_png(filename, data)
  5567. else:
  5568. self.plotcanvas.figure.savefig(filename)
  5569. if self.defaults["global_open_style"] is False:
  5570. self.file_opened.emit("png", filename)
  5571. self.file_saved.emit("png", filename)
  5572. def on_file_savegerber(self):
  5573. """
  5574. Callback for menu item in Project context menu.
  5575. :return: None
  5576. """
  5577. self.defaults.report_usage("on_file_savegerber")
  5578. App.log.debug("on_file_savegerber()")
  5579. obj = self.collection.get_active()
  5580. if obj is None:
  5581. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5582. return
  5583. # Check for more compatible types and add as required
  5584. if not isinstance(obj, GerberObject):
  5585. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5586. return
  5587. name = self.collection.get_active().options["name"]
  5588. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5589. try:
  5590. filename, _f = FCFileSaveDialog.get_saved_filename(
  5591. caption="Save Gerber source file",
  5592. directory=self.get_last_save_folder() + '/' + name,
  5593. filter=_filter)
  5594. except TypeError:
  5595. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  5596. filename = str(filename)
  5597. if filename == "":
  5598. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5599. return
  5600. else:
  5601. self.save_source_file(name, filename)
  5602. if self.defaults["global_open_style"] is False:
  5603. self.file_opened.emit("Gerber", filename)
  5604. self.file_saved.emit("Gerber", filename)
  5605. def on_file_savescript(self):
  5606. """
  5607. Callback for menu item in Project context menu.
  5608. :return: None
  5609. """
  5610. self.defaults.report_usage("on_file_savescript")
  5611. App.log.debug("on_file_savescript()")
  5612. obj = self.collection.get_active()
  5613. if obj is None:
  5614. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5615. return
  5616. # Check for more compatible types and add as required
  5617. if not isinstance(obj, ScriptObject):
  5618. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5619. return
  5620. name = self.collection.get_active().options["name"]
  5621. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5622. try:
  5623. filename, _f = FCFileSaveDialog.get_saved_filename(
  5624. caption="Save Script source file",
  5625. directory=self.get_last_save_folder() + '/' + name,
  5626. filter=_filter)
  5627. except TypeError:
  5628. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  5629. filename = str(filename)
  5630. if filename == "":
  5631. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5632. return
  5633. else:
  5634. self.save_source_file(name, filename)
  5635. if self.defaults["global_open_style"] is False:
  5636. self.file_opened.emit("Script", filename)
  5637. self.file_saved.emit("Script", filename)
  5638. def on_file_savedocument(self):
  5639. """
  5640. Callback for menu item in Project context menu.
  5641. :return: None
  5642. """
  5643. self.defaults.report_usage("on_file_savedocument")
  5644. App.log.debug("on_file_savedocument()")
  5645. obj = self.collection.get_active()
  5646. if obj is None:
  5647. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5648. return
  5649. # Check for more compatible types and add as required
  5650. if not isinstance(obj, ScriptObject):
  5651. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5652. return
  5653. name = self.collection.get_active().options["name"]
  5654. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5655. try:
  5656. filename, _f = FCFileSaveDialog.get_saved_filename(
  5657. caption="Save Document source file",
  5658. directory=self.get_last_save_folder() + '/' + name,
  5659. filter=_filter)
  5660. except TypeError:
  5661. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  5662. filename = str(filename)
  5663. if filename == "":
  5664. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5665. return
  5666. else:
  5667. self.save_source_file(name, filename)
  5668. if self.defaults["global_open_style"] is False:
  5669. self.file_opened.emit("Document", filename)
  5670. self.file_saved.emit("Document", filename)
  5671. def on_file_saveexcellon(self):
  5672. """
  5673. Callback for menu item in project context menu.
  5674. :return: None
  5675. """
  5676. self.defaults.report_usage("on_file_saveexcellon")
  5677. App.log.debug("on_file_saveexcellon()")
  5678. obj = self.collection.get_active()
  5679. if obj is None:
  5680. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5681. return
  5682. # Check for more compatible types and add as required
  5683. if not isinstance(obj, ExcellonObject):
  5684. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5685. return
  5686. name = self.collection.get_active().options["name"]
  5687. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5688. try:
  5689. filename, _f = FCFileSaveDialog.get_saved_filename(
  5690. caption=_("Save Excellon source file"),
  5691. directory=self.get_last_save_folder() + '/' + name,
  5692. filter=_filter)
  5693. except TypeError:
  5694. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  5695. filename = str(filename)
  5696. if filename == "":
  5697. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5698. return
  5699. else:
  5700. self.save_source_file(name, filename)
  5701. if self.defaults["global_open_style"] is False:
  5702. self.file_opened.emit("Excellon", filename)
  5703. self.file_saved.emit("Excellon", filename)
  5704. def on_file_exportexcellon(self):
  5705. """
  5706. Callback for menu item File->Export->Excellon.
  5707. :return: None
  5708. """
  5709. self.defaults.report_usage("on_file_exportexcellon")
  5710. App.log.debug("on_file_exportexcellon()")
  5711. obj = self.collection.get_active()
  5712. if obj is None:
  5713. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5714. return
  5715. # Check for more compatible types and add as required
  5716. if not isinstance(obj, ExcellonObject):
  5717. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5718. return
  5719. name = self.collection.get_active().options["name"]
  5720. _filter = self.defaults["excellon_save_filters"]
  5721. try:
  5722. filename, _f = FCFileSaveDialog.get_saved_filename(
  5723. caption=_("Export Excellon"),
  5724. directory=self.get_last_save_folder() + '/' + name,
  5725. filter=_filter)
  5726. except TypeError:
  5727. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  5728. filename = str(filename)
  5729. if filename == "":
  5730. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5731. return
  5732. else:
  5733. used_extension = filename.rpartition('.')[2]
  5734. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5735. self.export_excellon(name, filename)
  5736. if self.defaults["global_open_style"] is False:
  5737. self.file_opened.emit("Excellon", filename)
  5738. self.file_saved.emit("Excellon", filename)
  5739. def on_file_exportgerber(self):
  5740. """
  5741. Callback for menu item File->Export->Gerber.
  5742. :return: None
  5743. """
  5744. self.defaults.report_usage("on_file_exportgerber")
  5745. App.log.debug("on_file_exportgerber()")
  5746. obj = self.collection.get_active()
  5747. if obj is None:
  5748. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5749. return
  5750. # Check for more compatible types and add as required
  5751. if not isinstance(obj, GerberObject):
  5752. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5753. return
  5754. name = self.collection.get_active().options["name"]
  5755. _filter_ = self.defaults['gerber_save_filters']
  5756. try:
  5757. filename, _f = FCFileSaveDialog.get_saved_filename(
  5758. caption=_("Export Gerber"),
  5759. directory=self.get_last_save_folder() + '/' + name,
  5760. filter=_filter_)
  5761. except TypeError:
  5762. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  5763. filename = str(filename)
  5764. if filename == "":
  5765. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5766. return
  5767. else:
  5768. used_extension = filename.rpartition('.')[2]
  5769. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5770. self.export_gerber(name, filename)
  5771. if self.defaults["global_open_style"] is False:
  5772. self.file_opened.emit("Gerber", filename)
  5773. self.file_saved.emit("Gerber", filename)
  5774. def on_file_exportdxf(self):
  5775. """
  5776. Callback for menu item File->Export DXF.
  5777. :return: None
  5778. """
  5779. self.defaults.report_usage("on_file_exportdxf")
  5780. App.log.debug("on_file_exportdxf()")
  5781. obj = self.collection.get_active()
  5782. if obj is None:
  5783. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5784. msg = _("Please Select a Geometry object to export")
  5785. msgbox = QtWidgets.QMessageBox()
  5786. msgbox.setInformativeText(msg)
  5787. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5788. msgbox.setDefaultButton(bt_ok)
  5789. msgbox.exec_()
  5790. return
  5791. # Check for more compatible types and add as required
  5792. if not isinstance(obj, GeometryObject):
  5793. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5794. msgbox = QtWidgets.QMessageBox()
  5795. msgbox.setInformativeText(msg)
  5796. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5797. msgbox.setDefaultButton(bt_ok)
  5798. msgbox.exec_()
  5799. return
  5800. name = self.collection.get_active().options["name"]
  5801. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5802. try:
  5803. filename, _f = FCFileSaveDialog.get_saved_filename(
  5804. caption=_("Export DXF"),
  5805. directory=self.get_last_save_folder() + '/' + name,
  5806. filter=_filter_)
  5807. except TypeError:
  5808. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  5809. filename = str(filename)
  5810. if filename == "":
  5811. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5812. return
  5813. else:
  5814. self.export_dxf(name, filename)
  5815. if self.defaults["global_open_style"] is False:
  5816. self.file_opened.emit("DXF", filename)
  5817. self.file_saved.emit("DXF", filename)
  5818. def on_file_importsvg(self, type_of_obj):
  5819. """
  5820. Callback for menu item File->Import SVG.
  5821. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5822. :type type_of_obj: str
  5823. :return: None
  5824. """
  5825. self.defaults.report_usage("on_file_importsvg")
  5826. App.log.debug("on_file_importsvg()")
  5827. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  5828. try:
  5829. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5830. directory=self.get_last_folder(), filter=_filter_)
  5831. except TypeError:
  5832. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5833. filter=_filter_)
  5834. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5835. type_of_obj = "geometry"
  5836. filenames = [str(filename) for filename in filenames]
  5837. if len(filenames) == 0:
  5838. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5839. else:
  5840. for filename in filenames:
  5841. if filename != '':
  5842. self.worker_task.emit({'fcn': self.import_svg,
  5843. 'params': [filename, type_of_obj]})
  5844. def on_file_importdxf(self, type_of_obj):
  5845. """
  5846. Callback for menu item File->Import DXF.
  5847. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5848. :type type_of_obj: str
  5849. :return: None
  5850. """
  5851. self.defaults.report_usage("on_file_importdxf")
  5852. App.log.debug("on_file_importdxf()")
  5853. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5854. try:
  5855. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5856. directory=self.get_last_folder(),
  5857. filter=_filter_)
  5858. except TypeError:
  5859. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5860. filter=_filter_)
  5861. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5862. type_of_obj = "geometry"
  5863. filenames = [str(filename) for filename in filenames]
  5864. if len(filenames) == 0:
  5865. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5866. else:
  5867. for filename in filenames:
  5868. if filename != '':
  5869. self.worker_task.emit({'fcn': self.import_dxf,
  5870. 'params': [filename, type_of_obj]})
  5871. # ###############################################################################################################
  5872. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5873. # ###############################################################################################################
  5874. def init_code_editor(self, name):
  5875. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  5876. # add the tab if it was closed
  5877. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5878. self.text_editor_tab.setObjectName('text_editor_tab')
  5879. # delete the absolute and relative position and messages in the infobar
  5880. self.ui.position_label.setText("")
  5881. # self.ui.rel_position_label.setText("")
  5882. # first clear previous text in text editor (if any)
  5883. self.text_editor_tab.code_editor.clear()
  5884. self.text_editor_tab.code_editor.setReadOnly(False)
  5885. self.toggle_codeeditor = True
  5886. self.text_editor_tab.code_editor.completer_enable = False
  5887. self.text_editor_tab.buttonRun.hide()
  5888. # make sure to keep a reference to the code editor
  5889. self.reference_code_editor = self.text_editor_tab.code_editor
  5890. # Switch plot_area to CNCJob tab
  5891. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5892. def on_view_source(self):
  5893. """
  5894. Called when the user wants to see the source file of the selected object
  5895. :return:
  5896. """
  5897. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5898. self.proc_container.view.set_busy(_("Loading..."))
  5899. try:
  5900. obj = self.collection.get_active()
  5901. except Exception as e:
  5902. log.debug("App.on_view_source() --> %s" % str(e))
  5903. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5904. return 'fail'
  5905. if obj is None:
  5906. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5907. return 'fail'
  5908. flt = "All Files (*.*)"
  5909. if obj.kind == 'gerber':
  5910. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5911. elif obj.kind == 'excellon':
  5912. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5913. elif obj.kind == 'cncjob':
  5914. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5915. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  5916. # add the tab if it was closed
  5917. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5918. self.source_editor_tab.setObjectName('source_editor_tab')
  5919. # delete the absolute and relative position and messages in the infobar
  5920. self.ui.position_label.setText("")
  5921. # self.ui.rel_position_label.setText("")
  5922. # first clear previous text in text editor (if any)
  5923. self.source_editor_tab.code_editor.clear()
  5924. self.source_editor_tab.code_editor.setReadOnly(False)
  5925. self.source_editor_tab.code_editor.completer_enable = False
  5926. self.source_editor_tab.buttonRun.hide()
  5927. # Switch plot_area to CNCJob tab
  5928. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5929. try:
  5930. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5931. except TypeError:
  5932. pass
  5933. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5934. try:
  5935. self.source_editor_tab.buttonSave.clicked.disconnect()
  5936. except TypeError:
  5937. pass
  5938. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5939. # then append the text from GCode to the text editor
  5940. if obj.kind == 'cncjob':
  5941. try:
  5942. file = obj.export_gcode(
  5943. preamble=self.defaults["cncjob_prepend"],
  5944. postamble=self.defaults["cncjob_append"],
  5945. to_file=True)
  5946. if file == 'fail':
  5947. return 'fail'
  5948. except AttributeError:
  5949. self.inform.emit('[WARNING_NOTCL] %s' %
  5950. _("There is no selected object for which to see it's source file code."))
  5951. return 'fail'
  5952. else:
  5953. try:
  5954. file = StringIO(obj.source_file)
  5955. except (AttributeError, TypeError):
  5956. self.inform.emit('[WARNING_NOTCL] %s' %
  5957. _("There is no selected object for which to see it's source file code."))
  5958. return 'fail'
  5959. self.source_editor_tab.t_frame.hide()
  5960. try:
  5961. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  5962. # for line in file:
  5963. # QtWidgets.QApplication.processEvents()
  5964. # proc_line = str(line).strip('\n')
  5965. # self.source_editor_tab.code_editor.append(proc_line)
  5966. except Exception as e:
  5967. log.debug('App.on_view_source() -->%s' % str(e))
  5968. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5969. return
  5970. self.source_editor_tab.handleTextChanged()
  5971. self.source_editor_tab.t_frame.show()
  5972. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5973. self.proc_container.view.set_idle()
  5974. # self.ui.show()
  5975. def on_toggle_code_editor(self):
  5976. self.defaults.report_usage("on_toggle_code_editor()")
  5977. if self.toggle_codeeditor is False:
  5978. self.init_code_editor(name=_("Code Editor"))
  5979. self.text_editor_tab.buttonOpen.clicked.disconnect()
  5980. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  5981. self.text_editor_tab.buttonSave.clicked.disconnect()
  5982. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  5983. else:
  5984. for idx in range(self.ui.plot_tab_area.count()):
  5985. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  5986. self.ui.plot_tab_area.closeTab(idx)
  5987. break
  5988. self.toggle_codeeditor = False
  5989. def on_code_editor_close(self):
  5990. self.toggle_codeeditor = False
  5991. def goto_text_line(self):
  5992. """
  5993. Will scroll a text to the specified text line.
  5994. :return: None
  5995. """
  5996. dia_box = Dialog_box(title=_("Go to Line ..."),
  5997. label=_("Line:"),
  5998. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5999. initial_text='')
  6000. try:
  6001. line = int(dia_box.location) - 1
  6002. except (ValueError, TypeError):
  6003. line = 0
  6004. if dia_box.ok:
  6005. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6006. # at the top of the window
  6007. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6008. # get the document() of the TextEditor
  6009. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6010. # create a Text Cursor based on the searched line
  6011. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6012. # set cursor of the code editor with the cursor at the searcehd line
  6013. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6014. def on_filenewscript(self, silent=False):
  6015. """
  6016. Will create a new script file and open it in the Code Editor
  6017. :param silent: if True will not display status messages
  6018. :return: None
  6019. """
  6020. if silent is False:
  6021. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6022. # delete the absolute and relative position and messages in the infobar
  6023. self.ui.position_label.setText("")
  6024. # self.ui.rel_position_label.setText("")
  6025. self.app_obj.new_script_object()
  6026. # script_text = script_obj.source_file
  6027. #
  6028. # self.proc_container.view.set_busy(_("Loading..."))
  6029. # script_obj.script_editor_tab.t_frame.hide()
  6030. #
  6031. # script_obj.script_editor_tab.t_frame.show()
  6032. # self.proc_container.view.set_idle()
  6033. def on_fileopenscript(self, name=None, silent=False):
  6034. """
  6035. Will open a Tcl script file into the Code Editor
  6036. :param silent: if True will not display status messages
  6037. :param name: name of a Tcl script file to open
  6038. :return: None
  6039. """
  6040. self.defaults.report_usage("on_fileopenscript")
  6041. App.log.debug("on_fileopenscript()")
  6042. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6043. "All Files (*.*)"
  6044. if name:
  6045. filenames = [name]
  6046. else:
  6047. try:
  6048. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6049. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6050. except TypeError:
  6051. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6052. if len(filenames) == 0:
  6053. if silent is False:
  6054. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6055. else:
  6056. for filename in filenames:
  6057. if filename != '':
  6058. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6059. def on_fileopenscript_example(self, name=None, silent=False):
  6060. """
  6061. Will open a Tcl script file into the Code Editor
  6062. :param silent: if True will not display status messages
  6063. :param name: name of a Tcl script file to open
  6064. :return:
  6065. """
  6066. self.defaults.report_usage("on_fileopenscript_example")
  6067. log.debug("on_fileopenscript_example()")
  6068. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6069. "All Files (*.*)"
  6070. # test if the app was frozen and choose the path for the configuration file
  6071. if getattr(sys, "frozen", False) is True:
  6072. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6073. else:
  6074. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6075. if name:
  6076. filenames = [name]
  6077. else:
  6078. try:
  6079. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6080. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6081. except TypeError:
  6082. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6083. if len(filenames) == 0:
  6084. if silent is False:
  6085. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6086. else:
  6087. for filename in filenames:
  6088. if filename != '':
  6089. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6090. def on_filerunscript(self, name=None, silent=False):
  6091. """
  6092. File menu callback for loading and running a TCL script.
  6093. :param silent: if True will not display status messages
  6094. :param name: name of a Tcl script file to be run by FlatCAM
  6095. :return: None
  6096. """
  6097. self.defaults.report_usage("on_filerunscript")
  6098. App.log.debug("on_file_runscript()")
  6099. if name:
  6100. filename = name
  6101. if self.cmd_line_headless != 1:
  6102. self.splash.showMessage('%s: %ssec\n%s' %
  6103. (_("Canvas initialization started.\n"
  6104. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6105. _("Executing ScriptObject file.")
  6106. ),
  6107. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6108. color=QtGui.QColor("gray"))
  6109. else:
  6110. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6111. "All Files (*.*)"
  6112. try:
  6113. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6114. directory=self.get_last_folder(), filter=_filter_)
  6115. except TypeError:
  6116. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6117. # The Qt methods above will return a QString which can cause problems later.
  6118. # So far json.dump() will fail to serialize it.
  6119. filename = str(filename)
  6120. if filename == "":
  6121. if silent is False:
  6122. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6123. else:
  6124. if self.cmd_line_headless != 1:
  6125. if self.ui.shell_dock.isHidden():
  6126. self.ui.shell_dock.show()
  6127. try:
  6128. with open(filename, "r") as tcl_script:
  6129. cmd_line_shellfile_content = tcl_script.read()
  6130. if self.cmd_line_headless != 1:
  6131. self.shell.exec_command(cmd_line_shellfile_content)
  6132. else:
  6133. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6134. if silent is False:
  6135. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6136. except Exception as e:
  6137. log.debug("App.on_filerunscript() -> %s" % str(e))
  6138. sys.exit(2)
  6139. def on_file_saveproject(self, silent=False):
  6140. """
  6141. Callback for menu item File->Save Project. Saves the project to
  6142. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6143. if set to None. The project is saved by calling ``self.save_project()``.
  6144. :param silent: if True will not display status messages
  6145. :return: None
  6146. """
  6147. self.defaults.report_usage("on_file_saveproject")
  6148. if self.project_filename is None:
  6149. self.on_file_saveprojectas()
  6150. else:
  6151. self.worker_task.emit({'fcn': self.save_project,
  6152. 'params': [self.project_filename, silent]})
  6153. if self.defaults["global_open_style"] is False:
  6154. self.file_opened.emit("project", self.project_filename)
  6155. self.file_saved.emit("project", self.project_filename)
  6156. self.set_ui_title(name=self.project_filename)
  6157. self.should_we_save = False
  6158. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6159. """
  6160. Callback for menu item File->Save Project As... Opens a file
  6161. chooser and saves the project to the given file via
  6162. ``self.save_project()``.
  6163. :param make_copy if to be create a copy of the project; boolean
  6164. :param use_thread: if to be run in a separate thread; boolean
  6165. :param quit_action: if to be followed by quiting the application; boolean
  6166. :return: None
  6167. """
  6168. self.defaults.report_usage("on_file_saveprojectas")
  6169. self.date = str(datetime.today()).rpartition('.')[0]
  6170. self.date = ''.join(c for c in self.date if c not in ':-')
  6171. self.date = self.date.replace(' ', '_')
  6172. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6173. try:
  6174. filename, _f = FCFileSaveDialog.get_saved_filename(
  6175. caption=_("Save Project As ..."),
  6176. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6177. proj=_("Project")),
  6178. filter=filter_
  6179. )
  6180. except TypeError:
  6181. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6182. filename = str(filename)
  6183. if filename == '':
  6184. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6185. return
  6186. if use_thread is True:
  6187. self.worker_task.emit({'fcn': self.save_project,
  6188. 'params': [filename, quit_action]})
  6189. else:
  6190. self.save_project(filename, quit_action)
  6191. # self.save_project(filename)
  6192. if self.defaults["global_open_style"] is False:
  6193. self.file_opened.emit("project", filename)
  6194. self.file_saved.emit("project", filename)
  6195. if not make_copy:
  6196. self.project_filename = filename
  6197. self.set_ui_title(name=self.project_filename)
  6198. self.should_we_save = False
  6199. def on_file_save_objects_pdf(self, use_thread=True):
  6200. self.date = str(datetime.today()).rpartition('.')[0]
  6201. self.date = ''.join(c for c in self.date if c not in ':-')
  6202. self.date = self.date.replace(' ', '_')
  6203. try:
  6204. obj_selection = self.collection.get_selected()
  6205. if len(obj_selection) == 1:
  6206. obj_name = str(obj_selection[0].options['name'])
  6207. else:
  6208. obj_name = _("FlatCAM objects print")
  6209. except AttributeError as err:
  6210. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6211. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6212. return
  6213. if not obj_selection:
  6214. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6215. return
  6216. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6217. try:
  6218. filename, _f = FCFileSaveDialog.get_saved_filename(
  6219. caption=_("Save Object as PDF ..."),
  6220. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6221. obj_name=obj_name,
  6222. date=self.date),
  6223. filter=filter_
  6224. )
  6225. except TypeError:
  6226. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6227. filename = str(filename)
  6228. if filename == '':
  6229. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6230. return
  6231. if use_thread is True:
  6232. self.proc_container.new(_("Printing PDF ... Please wait."))
  6233. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6234. else:
  6235. self.save_pdf(filename, obj_selection)
  6236. # self.save_project(filename)
  6237. if self.defaults["global_open_style"] is False:
  6238. self.file_opened.emit("pdf", filename)
  6239. self.file_saved.emit("pdf", filename)
  6240. def save_pdf(self, file_name, obj_selection):
  6241. p_size = self.defaults['global_workspaceT']
  6242. orientation = self.defaults['global_workspace_orientation']
  6243. color = 'black'
  6244. transparency_level = 1.0
  6245. self.pagesize = {}
  6246. self.pagesize.update(
  6247. {
  6248. 'Bounds': None,
  6249. 'A0': (841 * mm, 1189 * mm),
  6250. 'A1': (594 * mm, 841 * mm),
  6251. 'A2': (420 * mm, 594 * mm),
  6252. 'A3': (297 * mm, 420 * mm),
  6253. 'A4': (210 * mm, 297 * mm),
  6254. 'A5': (148 * mm, 210 * mm),
  6255. 'A6': (105 * mm, 148 * mm),
  6256. 'A7': (74 * mm, 105 * mm),
  6257. 'A8': (52 * mm, 74 * mm),
  6258. 'A9': (37 * mm, 52 * mm),
  6259. 'A10': (26 * mm, 37 * mm),
  6260. 'B0': (1000 * mm, 1414 * mm),
  6261. 'B1': (707 * mm, 1000 * mm),
  6262. 'B2': (500 * mm, 707 * mm),
  6263. 'B3': (353 * mm, 500 * mm),
  6264. 'B4': (250 * mm, 353 * mm),
  6265. 'B5': (176 * mm, 250 * mm),
  6266. 'B6': (125 * mm, 176 * mm),
  6267. 'B7': (88 * mm, 125 * mm),
  6268. 'B8': (62 * mm, 88 * mm),
  6269. 'B9': (44 * mm, 62 * mm),
  6270. 'B10': (31 * mm, 44 * mm),
  6271. 'C0': (917 * mm, 1297 * mm),
  6272. 'C1': (648 * mm, 917 * mm),
  6273. 'C2': (458 * mm, 648 * mm),
  6274. 'C3': (324 * mm, 458 * mm),
  6275. 'C4': (229 * mm, 324 * mm),
  6276. 'C5': (162 * mm, 229 * mm),
  6277. 'C6': (114 * mm, 162 * mm),
  6278. 'C7': (81 * mm, 114 * mm),
  6279. 'C8': (57 * mm, 81 * mm),
  6280. 'C9': (40 * mm, 57 * mm),
  6281. 'C10': (28 * mm, 40 * mm),
  6282. # American paper sizes
  6283. 'LETTER': (8.5 * inch, 11 * inch),
  6284. 'LEGAL': (8.5 * inch, 14 * inch),
  6285. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6286. # From https://en.wikipedia.org/wiki/Paper_size
  6287. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6288. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6289. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6290. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6291. 'LEDGER': (17 * inch, 11 * inch),
  6292. }
  6293. )
  6294. exported_svg = []
  6295. for obj in obj_selection:
  6296. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6297. scale_factor_x=None, scale_factor_y=None,
  6298. skew_factor_x=None, skew_factor_y=None,
  6299. mirror=None)
  6300. if obj.kind.lower() == 'gerber':
  6301. # color = self.defaults["gerber_plot_fill"][:-2]
  6302. color = obj.fill_color[:-2]
  6303. elif obj.kind.lower() == 'excellon':
  6304. color = '#C40000'
  6305. elif obj.kind.lower() == 'geometry':
  6306. color = self.defaults["global_draw_color"]
  6307. # Change the attributes of the exported SVG
  6308. # We don't need stroke-width
  6309. # We set opacity to maximum
  6310. # We set the colour to WHITE
  6311. root = ET.fromstring(svg_obj)
  6312. for child in root:
  6313. child.set('fill', str(color))
  6314. child.set('opacity', str(transparency_level))
  6315. child.set('stroke', str(color))
  6316. exported_svg.append(ET.tostring(root))
  6317. xmin = Inf
  6318. ymin = Inf
  6319. xmax = -Inf
  6320. ymax = -Inf
  6321. for obj in obj_selection:
  6322. try:
  6323. gxmin, gymin, gxmax, gymax = obj.bounds()
  6324. xmin = min([xmin, gxmin])
  6325. ymin = min([ymin, gymin])
  6326. xmax = max([xmax, gxmax])
  6327. ymax = max([ymax, gymax])
  6328. except Exception as e:
  6329. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6330. # Determine bounding area for svg export
  6331. bounds = [xmin, ymin, xmax, ymax]
  6332. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6333. # This contain the measure units
  6334. uom = obj_selection[0].units.lower()
  6335. # Define a boundary around SVG of about 1.0mm (~39mils)
  6336. if uom in "mm":
  6337. boundary = 1.0
  6338. else:
  6339. boundary = 0.0393701
  6340. # Convert everything to strings for use in the xml doc
  6341. svgwidth = str(size[0] + (2 * boundary))
  6342. svgheight = str(size[1] + (2 * boundary))
  6343. minx = str(bounds[0] - boundary)
  6344. miny = str(bounds[1] + boundary + size[1])
  6345. # Add a SVG Header and footer to the svg output from shapely
  6346. # The transform flips the Y Axis so that everything renders
  6347. # properly within svg apps such as inkscape
  6348. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6349. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6350. svg_header += 'width="' + svgwidth + uom + '" '
  6351. svg_header += 'height="' + svgheight + uom + '" '
  6352. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6353. svg_header += '>'
  6354. svg_header += '<g transform="scale(1,-1)">'
  6355. svg_footer = '</g> </svg>'
  6356. svg_elem = str(svg_header)
  6357. for svg_item in exported_svg:
  6358. svg_elem += str(svg_item)
  6359. svg_elem += str(svg_footer)
  6360. # Parse the xml through a xml parser just to add line feeds
  6361. # and to make it look more pretty for the output
  6362. doc = parse_xml_string(svg_elem)
  6363. doc_final = doc.toprettyxml()
  6364. try:
  6365. if self.defaults['units'].upper() == 'IN':
  6366. unit = inch
  6367. else:
  6368. unit = mm
  6369. doc_final = StringIO(doc_final)
  6370. drawing = svg2rlg(doc_final)
  6371. if p_size == 'Bounds':
  6372. renderPDF.drawToFile(drawing, file_name)
  6373. else:
  6374. if orientation == 'p':
  6375. page_size = portrait(self.pagesize[p_size])
  6376. else:
  6377. page_size = landscape(self.pagesize[p_size])
  6378. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6379. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6380. renderPDF.draw(drawing, my_canvas, 0, 0)
  6381. my_canvas.save()
  6382. except Exception as e:
  6383. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6384. return 'fail'
  6385. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6386. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6387. """
  6388. Exports a Geometry Object to an SVG file.
  6389. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6390. :param filename: Path to the SVG file to save to.
  6391. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6392. :return:
  6393. """
  6394. self.defaults.report_usage("export_svg()")
  6395. if filename is None:
  6396. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6397. is not None else self.defaults["global_last_folder"]
  6398. self.log.debug("export_svg()")
  6399. try:
  6400. obj = self.collection.get_by_name(str(obj_name))
  6401. except Exception:
  6402. # TODO: The return behavior has not been established... should raise exception?
  6403. return "Could not retrieve object: %s" % obj_name
  6404. with self.proc_container.new(_("Exporting SVG")) as proc:
  6405. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6406. # Determine bounding area for svg export
  6407. bounds = obj.bounds()
  6408. size = obj.size()
  6409. # Convert everything to strings for use in the xml doc
  6410. svgwidth = str(size[0])
  6411. svgheight = str(size[1])
  6412. minx = str(bounds[0])
  6413. miny = str(bounds[1] - size[1])
  6414. uom = obj.units.lower()
  6415. # Add a SVG Header and footer to the svg output from shapely
  6416. # The transform flips the Y Axis so that everything renders
  6417. # properly within svg apps such as inkscape
  6418. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6419. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6420. svg_header += 'width="' + svgwidth + uom + '" '
  6421. svg_header += 'height="' + svgheight + uom + '" '
  6422. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6423. svg_header += '<g transform="scale(1,-1)">'
  6424. svg_footer = '</g> </svg>'
  6425. svg_elem = svg_header + exported_svg + svg_footer
  6426. # Parse the xml through a xml parser just to add line feeds
  6427. # and to make it look more pretty for the output
  6428. svgcode = parse_xml_string(svg_elem)
  6429. svgcode = svgcode.toprettyxml()
  6430. try:
  6431. with open(filename, 'w') as fp:
  6432. fp.write(svgcode)
  6433. except PermissionError:
  6434. self.inform.emit('[WARNING] %s' %
  6435. _("Permission denied, saving not possible.\n"
  6436. "Most likely another app is holding the file open and not accessible."))
  6437. return 'fail'
  6438. if self.defaults["global_open_style"] is False:
  6439. self.file_opened.emit("SVG", filename)
  6440. self.file_saved.emit("SVG", filename)
  6441. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6442. def save_source_file(self, obj_name, filename, use_thread=True):
  6443. """
  6444. Exports a FlatCAM Object to an Gerber/Excellon file.
  6445. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6446. :param filename: Path to the Gerber file to save to.
  6447. :param use_thread: if to be run in a separate thread
  6448. :return:
  6449. """
  6450. self.defaults.report_usage("save source file()")
  6451. if filename is None:
  6452. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6453. is not None else self.defaults["global_last_folder"]
  6454. self.log.debug("save source file()")
  6455. obj = self.collection.get_by_name(obj_name)
  6456. file_string = StringIO(obj.source_file)
  6457. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6458. if file_string.getvalue() == '':
  6459. self.inform.emit('[ERROR_NOTCL] %s' %
  6460. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6461. return 'fail'
  6462. try:
  6463. with open(filename, 'w') as file:
  6464. file.writelines('G04*\n')
  6465. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6466. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6467. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6468. file.writelines('G04 Created on : %s*\n' % time_string)
  6469. for line in file_string:
  6470. file.writelines(line)
  6471. except PermissionError:
  6472. self.inform.emit('[WARNING] %s' %
  6473. _("Permission denied, saving not possible.\n"
  6474. "Most likely another app is holding the file open and not accessible."))
  6475. return 'fail'
  6476. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6477. """
  6478. Exports a Excellon Object to an Excellon file.
  6479. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6480. :param filename: Path to the Excellon file to save to.
  6481. :param local_use:
  6482. :param use_thread: if to be run in a separate thread
  6483. :return:
  6484. """
  6485. self.defaults.report_usage("export_excellon()")
  6486. if filename is None:
  6487. if self.defaults["global_last_save_folder"]:
  6488. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6489. else:
  6490. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6491. self.log.debug("export_excellon()")
  6492. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6493. self.defaults["excellon_exp_decimals"]
  6494. )
  6495. if local_use is None:
  6496. try:
  6497. obj = self.collection.get_by_name(str(obj_name))
  6498. except Exception:
  6499. return "Could not retrieve object: %s" % obj_name
  6500. else:
  6501. obj = local_use
  6502. if not isinstance(obj, ExcellonObject):
  6503. self.inform.emit('[ERROR_NOTCL] %s' %
  6504. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6505. return
  6506. # updated units
  6507. eunits = self.defaults["excellon_exp_units"]
  6508. ewhole = self.defaults["excellon_exp_integer"]
  6509. efract = self.defaults["excellon_exp_decimals"]
  6510. ezeros = self.defaults["excellon_exp_zeros"]
  6511. eformat = self.defaults["excellon_exp_format"]
  6512. slot_type = self.defaults["excellon_exp_slot_type"]
  6513. fc_units = self.defaults['units'].upper()
  6514. if fc_units == 'MM':
  6515. factor = 1 if eunits == 'METRIC' else 0.03937
  6516. else:
  6517. factor = 25.4 if eunits == 'METRIC' else 1
  6518. def make_excellon():
  6519. try:
  6520. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6521. header = 'M48\n'
  6522. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6523. (str(self.version), str(self.version_date))
  6524. header += ';Filename: %s' % str(obj_name) + '\n'
  6525. header += ';Created on : %s' % time_str + '\n'
  6526. if eformat == 'dec':
  6527. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6528. header += eunits + '\n'
  6529. for tool in obj.tools:
  6530. if eunits == 'METRIC':
  6531. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6532. tool=str(tool),
  6533. dec=2)
  6534. else:
  6535. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6536. tool=str(tool),
  6537. dec=4)
  6538. else:
  6539. if ezeros == 'LZ':
  6540. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6541. form='ndec', e_zeros='LZ', factor=factor,
  6542. slot_type=slot_type)
  6543. header += '%s,%s\n' % (eunits, 'LZ')
  6544. header += format_exc
  6545. for tool in obj.tools:
  6546. if eunits == 'METRIC':
  6547. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6548. tool=str(tool),
  6549. dec=2)
  6550. else:
  6551. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6552. tool=str(tool),
  6553. dec=4)
  6554. else:
  6555. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6556. form='ndec', e_zeros='TZ', factor=factor,
  6557. slot_type=slot_type)
  6558. header += '%s,%s\n' % (eunits, 'TZ')
  6559. header += format_exc
  6560. for tool in obj.tools:
  6561. if eunits == 'METRIC':
  6562. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6563. tool=str(tool),
  6564. dec=2)
  6565. else:
  6566. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6567. tool=str(tool),
  6568. dec=4)
  6569. header += '%\n'
  6570. footer = 'M30\n'
  6571. exported_excellon = header
  6572. exported_excellon += excellon_code
  6573. exported_excellon += footer
  6574. if local_use is None:
  6575. try:
  6576. with open(filename, 'w') as fp:
  6577. fp.write(exported_excellon)
  6578. except PermissionError:
  6579. self.inform.emit('[WARNING] %s' %
  6580. _("Permission denied, saving not possible.\n"
  6581. "Most likely another app is holding the file open and not accessible."))
  6582. return 'fail'
  6583. if self.defaults["global_open_style"] is False:
  6584. self.file_opened.emit("Excellon", filename)
  6585. self.file_saved.emit("Excellon", filename)
  6586. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6587. else:
  6588. return exported_excellon
  6589. except Exception as e:
  6590. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6591. return 'fail'
  6592. if use_thread is True:
  6593. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6594. def job_thread_exc(app_obj):
  6595. ret = make_excellon()
  6596. if ret == 'fail':
  6597. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6598. return
  6599. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6600. else:
  6601. eret = make_excellon()
  6602. if eret == 'fail':
  6603. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6604. return 'fail'
  6605. if local_use is not None:
  6606. return eret
  6607. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6608. """
  6609. Exports a Gerber Object to an Gerber file.
  6610. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6611. :param filename: Path to the Gerber file to save to.
  6612. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6613. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6614. :param use_thread: if to be run in a separate thread
  6615. :return:
  6616. """
  6617. self.defaults.report_usage("export_gerber()")
  6618. if filename is None:
  6619. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6620. is not None else self.defaults["global_last_folder"]
  6621. self.log.debug("export_gerber()")
  6622. if local_use is None:
  6623. try:
  6624. obj = self.collection.get_by_name(str(obj_name))
  6625. except Exception:
  6626. return "Could not retrieve object: %s" % obj_name
  6627. else:
  6628. obj = local_use
  6629. # updated units
  6630. gunits = self.defaults["gerber_exp_units"]
  6631. gwhole = self.defaults["gerber_exp_integer"]
  6632. gfract = self.defaults["gerber_exp_decimals"]
  6633. gzeros = self.defaults["gerber_exp_zeros"]
  6634. fc_units = self.defaults['units'].upper()
  6635. if fc_units == 'MM':
  6636. factor = 1 if gunits == 'MM' else 0.03937
  6637. else:
  6638. factor = 25.4 if gunits == 'MM' else 1
  6639. def make_gerber():
  6640. try:
  6641. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6642. header = 'G04*\n'
  6643. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6644. (str(self.version), str(self.version_date))
  6645. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6646. header += 'G04 Created on : %s*' % time_str + '\n'
  6647. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6648. header += "%MO{units}*%\n".format(units=gunits)
  6649. for apid in obj.apertures:
  6650. if obj.apertures[apid]['type'] == 'C':
  6651. header += "%ADD{apid}{type},{size}*%\n".format(
  6652. apid=str(apid),
  6653. type='C',
  6654. size=(factor * obj.apertures[apid]['size'])
  6655. )
  6656. elif obj.apertures[apid]['type'] == 'R':
  6657. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6658. apid=str(apid),
  6659. type='R',
  6660. width=(factor * obj.apertures[apid]['width']),
  6661. height=(factor * obj.apertures[apid]['height'])
  6662. )
  6663. elif obj.apertures[apid]['type'] == 'O':
  6664. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6665. apid=str(apid),
  6666. type='O',
  6667. width=(factor * obj.apertures[apid]['width']),
  6668. height=(factor * obj.apertures[apid]['height'])
  6669. )
  6670. header += '\n'
  6671. # obsolete units but some software may need it
  6672. if gunits == 'IN':
  6673. header += 'G70*\n'
  6674. else:
  6675. header += 'G71*\n'
  6676. # Absolute Mode
  6677. header += 'G90*\n'
  6678. header += 'G01*\n'
  6679. # positive polarity
  6680. header += '%LPD*%\n'
  6681. footer = 'M02*\n'
  6682. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6683. exported_gerber = header
  6684. exported_gerber += gerber_code
  6685. exported_gerber += footer
  6686. if local_use is None:
  6687. try:
  6688. with open(filename, 'w') as fp:
  6689. fp.write(exported_gerber)
  6690. except PermissionError:
  6691. self.inform.emit('[WARNING] %s' %
  6692. _("Permission denied, saving not possible.\n"
  6693. "Most likely another app is holding the file open and not accessible."))
  6694. return 'fail'
  6695. if self.defaults["global_open_style"] is False:
  6696. self.file_opened.emit("Gerber", filename)
  6697. self.file_saved.emit("Gerber", filename)
  6698. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6699. else:
  6700. return exported_gerber
  6701. except Exception as e:
  6702. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6703. return 'fail'
  6704. if use_thread is True:
  6705. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6706. def job_thread_grb(app_obj):
  6707. ret = make_gerber()
  6708. if ret == 'fail':
  6709. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6710. return
  6711. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6712. else:
  6713. gret = make_gerber()
  6714. if gret == 'fail':
  6715. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6716. return 'fail'
  6717. if local_use is not None:
  6718. return gret
  6719. def export_dxf(self, obj_name, filename, use_thread=True):
  6720. """
  6721. Exports a Geometry Object to an DXF file.
  6722. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6723. :param filename: Path to the DXF file to save to.
  6724. :param use_thread: if to be run in a separate thread
  6725. :return:
  6726. """
  6727. self.defaults.report_usage("export_dxf()")
  6728. if filename is None:
  6729. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6730. is not None else self.defaults["global_last_folder"]
  6731. self.log.debug("export_dxf()")
  6732. try:
  6733. obj = self.collection.get_by_name(str(obj_name))
  6734. except Exception:
  6735. # TODO: The return behavior has not been established... should raise exception?
  6736. return "Could not retrieve object: %s" % obj_name
  6737. def make_dxf():
  6738. try:
  6739. dxf_code = obj.export_dxf()
  6740. dxf_code.saveas(filename)
  6741. if self.defaults["global_open_style"] is False:
  6742. self.file_opened.emit("DXF", filename)
  6743. self.file_saved.emit("DXF", filename)
  6744. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6745. except Exception:
  6746. return 'fail'
  6747. if use_thread is True:
  6748. with self.proc_container.new(_("Exporting DXF")) as proc:
  6749. def job_thread_exc(app_obj):
  6750. ret_dxf_val = make_dxf()
  6751. if ret_dxf_val == 'fail':
  6752. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6753. return
  6754. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6755. else:
  6756. ret = make_dxf()
  6757. if ret == 'fail':
  6758. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6759. return
  6760. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6761. """
  6762. Adds a new Geometry Object to the projects and populates
  6763. it with shapes extracted from the SVG file.
  6764. :param plot: If True then the resulting object will be plotted on canvas
  6765. :param filename: Path to the SVG file.
  6766. :param geo_type: Type of FlatCAM object that will be created from SVG
  6767. :param outname: The name given to the resulting FlatCAM object
  6768. :return:
  6769. """
  6770. self.defaults.report_usage("import_svg()")
  6771. log.debug("App.import_svg()")
  6772. obj_type = ""
  6773. if geo_type is None or geo_type == "geometry":
  6774. obj_type = "geometry"
  6775. elif geo_type == "gerber":
  6776. obj_type = "gerber"
  6777. else:
  6778. self.inform.emit('[ERROR_NOTCL] %s' %
  6779. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6780. return
  6781. units = self.defaults['units'].upper()
  6782. def obj_init(geo_obj, app_obj):
  6783. geo_obj.import_svg(filename, obj_type, units=units)
  6784. geo_obj.multigeo = False
  6785. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6786. with self.proc_container.new(_("Importing SVG")) as proc:
  6787. # Object name
  6788. name = outname or filename.split('/')[-1].split('\\')[-1]
  6789. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6790. if ret == 'fail':
  6791. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6792. return 'fail'
  6793. # Register recent file
  6794. self.file_opened.emit("svg", filename)
  6795. # AppGUI feedback
  6796. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6797. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  6798. """
  6799. Adds a new Geometry Object to the projects and populates
  6800. it with shapes extracted from the DXF file.
  6801. :param filename: Path to the DXF file.
  6802. :param geo_type: Type of FlatCAM object that will be created from DXF
  6803. :param outname: Name for the imported Geometry
  6804. :param plot: If True then the resulting object will be plotted on canvas
  6805. :return:
  6806. """
  6807. self.defaults.report_usage("import_dxf()")
  6808. obj_type = ""
  6809. if geo_type is None or geo_type == "geometry":
  6810. obj_type = "geometry"
  6811. elif geo_type == "gerber":
  6812. obj_type = geo_type
  6813. else:
  6814. self.inform.emit('[ERROR_NOTCL] %s' %
  6815. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6816. return
  6817. units = self.defaults['units'].upper()
  6818. def obj_init(geo_obj, app_obj):
  6819. geo_obj.import_dxf(filename, obj_type, units=units)
  6820. geo_obj.multigeo = False
  6821. with self.proc_container.new(_("Importing DXF")):
  6822. # Object name
  6823. name = outname or filename.split('/')[-1].split('\\')[-1]
  6824. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6825. if ret == 'fail':
  6826. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6827. return 'fail'
  6828. # Register recent file
  6829. self.file_opened.emit("dxf", filename)
  6830. # AppGUI feedback
  6831. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6832. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  6833. """
  6834. Opens a Gerber file, parses it and creates a new object for
  6835. it in the program. Thread-safe.
  6836. :param outname: Name of the resulting object. None causes the
  6837. name to be that of the file. Str.
  6838. :param filename: Gerber file filename
  6839. :type filename: str
  6840. :param plot: boolean, to plot or not the resulting object
  6841. :param from_tcl: True if run from Tcl Shell
  6842. :return: None
  6843. """
  6844. # How the object should be initialized
  6845. def obj_init(gerber_obj, app_obj):
  6846. assert isinstance(gerber_obj, GerberObject), \
  6847. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  6848. # Opening the file happens here
  6849. try:
  6850. gerber_obj.parse_file(filename)
  6851. except IOError:
  6852. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  6853. return "fail"
  6854. except ParseError as err:
  6855. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  6856. app_obj.log.error(str(err))
  6857. return "fail"
  6858. except Exception as e:
  6859. log.debug("App.open_gerber() --> %s" % str(e))
  6860. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  6861. msg += traceback.format_exc()
  6862. app_obj.inform.emit(msg)
  6863. return "fail"
  6864. if gerber_obj.is_empty():
  6865. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  6866. _("Object is not Gerber file or empty. Aborting object creation."))
  6867. return "fail"
  6868. App.log.debug("open_gerber()")
  6869. with self.proc_container.new(_("Opening Gerber")):
  6870. # Object name
  6871. name = outname or filename.split('/')[-1].split('\\')[-1]
  6872. # # ## Object creation # ##
  6873. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6874. if ret_val == 'fail':
  6875. if from_tcl:
  6876. filename = self.defaults['global_tcl_path'] + '/' + name
  6877. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6878. if ret_val == 'fail':
  6879. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  6880. return 'fail'
  6881. # Register recent file
  6882. self.file_opened.emit("gerber", filename)
  6883. # AppGUI feedback
  6884. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6885. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  6886. """
  6887. Opens an Excellon file, parses it and creates a new object for
  6888. it in the program. Thread-safe.
  6889. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6890. :param filename: Excellon file filename
  6891. :type filename: str
  6892. :param plot: boolean, to plot or not the resulting object
  6893. :param from_tcl: True if run from Tcl Shell
  6894. :return: None
  6895. """
  6896. App.log.debug("open_excellon()")
  6897. # How the object should be initialized
  6898. def obj_init(excellon_obj, app_obj):
  6899. try:
  6900. ret = excellon_obj.parse_file(filename=filename)
  6901. if ret == "fail":
  6902. log.debug("Excellon parsing failed.")
  6903. self.inform.emit('[ERROR_NOTCL] %s' %
  6904. _("This is not Excellon file."))
  6905. return "fail"
  6906. except IOError:
  6907. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  6908. (_("Cannot open file"), filename))
  6909. log.debug("Could not open Excellon object.")
  6910. return "fail"
  6911. except Exception:
  6912. msg = '[ERROR_NOTCL] %s' % \
  6913. _("An internal error has occurred. See shell.\n")
  6914. msg += traceback.format_exc()
  6915. app_obj.inform.emit(msg)
  6916. return "fail"
  6917. ret = excellon_obj.create_geometry()
  6918. if ret == 'fail':
  6919. log.debug("Could not create geometry for Excellon object.")
  6920. return "fail"
  6921. for tool in excellon_obj.tools:
  6922. if excellon_obj.tools[tool]['solid_geometry']:
  6923. return
  6924. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  6925. return "fail"
  6926. with self.proc_container.new(_("Opening Excellon.")):
  6927. # Object name
  6928. name = outname or filename.split('/')[-1].split('\\')[-1]
  6929. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  6930. if ret_val == 'fail':
  6931. if from_tcl:
  6932. filename = self.defaults['global_tcl_path'] + '/' + name
  6933. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  6934. if ret_val == 'fail':
  6935. self.inform.emit('[ERROR_NOTCL] %s' %
  6936. _('Open Excellon file failed. Probable not an Excellon file.'))
  6937. return
  6938. # Register recent file
  6939. self.file_opened.emit("excellon", filename)
  6940. # AppGUI feedback
  6941. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6942. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  6943. """
  6944. Opens a G-gcode file, parses it and creates a new object for
  6945. it in the program. Thread-safe.
  6946. :param filename: G-code file filename
  6947. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6948. :param force_parsing:
  6949. :param plot: If True plot the object on canvas
  6950. :param from_tcl: True if run from Tcl Shell
  6951. :return: None
  6952. """
  6953. App.log.debug("open_gcode()")
  6954. # How the object should be initialized
  6955. def obj_init(job_obj, app_obj_):
  6956. """
  6957. :param job_obj: the resulting object
  6958. :type app_obj_: App
  6959. """
  6960. assert isinstance(app_obj_, App), \
  6961. "Initializer expected App, got %s" % type(app_obj_)
  6962. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  6963. try:
  6964. f = open(filename)
  6965. gcode = f.read()
  6966. f.close()
  6967. except IOError:
  6968. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  6969. return "fail"
  6970. job_obj.gcode = gcode
  6971. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  6972. if gcode_ret == "fail":
  6973. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  6974. return "fail"
  6975. job_obj.create_geometry()
  6976. with self.proc_container.new(_("Opening G-Code.")):
  6977. # Object name
  6978. name = outname or filename.split('/')[-1].split('\\')[-1]
  6979. # New object creation and file processing
  6980. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  6981. if ret_val == 'fail':
  6982. if from_tcl:
  6983. filename = self.defaults['global_tcl_path'] + '/' + name
  6984. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  6985. if ret_val == 'fail':
  6986. self.inform.emit('[ERROR_NOTCL] %s' %
  6987. _("Failed to create CNCJob Object. Probable not a GCode file. "
  6988. "Try to load it from File menu.\n "
  6989. "Attempting to create a FlatCAM CNCJob Object from "
  6990. "G-Code file failed during processing"))
  6991. return "fail"
  6992. # Register recent file
  6993. self.file_opened.emit("cncjob", filename)
  6994. # AppGUI feedback
  6995. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6996. def open_hpgl2(self, filename, outname=None):
  6997. """
  6998. Opens a HPGL2 file, parses it and creates a new object for
  6999. it in the program. Thread-safe.
  7000. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7001. :param filename: HPGL2 file filename
  7002. :return: None
  7003. """
  7004. filename = filename
  7005. # How the object should be initialized
  7006. def obj_init(geo_obj, app_obj):
  7007. assert isinstance(geo_obj, GeometryObject), \
  7008. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7009. # Opening the file happens here
  7010. obj = HPGL2(self)
  7011. try:
  7012. HPGL2.parse_file(obj, filename)
  7013. except IOError:
  7014. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7015. return "fail"
  7016. except ParseError as err:
  7017. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7018. app_obj.log.error(str(err))
  7019. return "fail"
  7020. except Exception as e:
  7021. log.debug("App.open_hpgl2() --> %s" % str(e))
  7022. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7023. msg += traceback.format_exc()
  7024. app_obj.inform.emit(msg)
  7025. return "fail"
  7026. geo_obj.multigeo = True
  7027. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7028. geo_obj.tools = deepcopy(obj.tools)
  7029. geo_obj.source_file = deepcopy(obj.source_file)
  7030. del obj
  7031. if not geo_obj.solid_geometry:
  7032. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7033. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7034. return "fail"
  7035. App.log.debug("open_hpgl2()")
  7036. with self.proc_container.new(_("Opening HPGL2")):
  7037. # Object name
  7038. name = outname or filename.split('/')[-1].split('\\')[-1]
  7039. # # ## Object creation # ##
  7040. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7041. if ret == 'fail':
  7042. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7043. return 'fail'
  7044. # Register recent file
  7045. self.file_opened.emit("geometry", filename)
  7046. # AppGUI feedback
  7047. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7048. def open_script(self, filename, outname=None, silent=False):
  7049. """
  7050. Opens a Script file, parses it and creates a new object for
  7051. it in the program. Thread-safe.
  7052. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7053. :param filename: Script file filename
  7054. :param silent: If True there will be no messages printed to StatusBar
  7055. :return: None
  7056. """
  7057. def obj_init(script_obj, app_obj):
  7058. assert isinstance(script_obj, ScriptObject), \
  7059. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7060. if silent is False:
  7061. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7062. try:
  7063. script_obj.parse_file(filename)
  7064. except IOError:
  7065. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7066. return "fail"
  7067. except ParseError as err:
  7068. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7069. app_obj.log.error(str(err))
  7070. return "fail"
  7071. except Exception as e:
  7072. log.debug("App.open_script() -> %s" % str(e))
  7073. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7074. msg += traceback.format_exc()
  7075. app_obj.inform.emit(msg)
  7076. return "fail"
  7077. App.log.debug("open_script()")
  7078. with self.proc_container.new(_("Opening TCL Script...")):
  7079. # Object name
  7080. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7081. # Object creation
  7082. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7083. if ret_val == 'fail':
  7084. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7085. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7086. if ret_val == 'fail':
  7087. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7088. return 'fail'
  7089. # Register recent file
  7090. self.file_opened.emit("script", filename)
  7091. # AppGUI feedback
  7092. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7093. def open_config_file(self, filename, run_from_arg=None):
  7094. """
  7095. Loads a config file from the specified file.
  7096. :param filename: Name of the file from which to load.
  7097. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7098. :return: None
  7099. """
  7100. App.log.debug("Opening config file: " + filename)
  7101. if run_from_arg:
  7102. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7103. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7104. _("Opening FlatCAM Config file.")),
  7105. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7106. color=QtGui.QColor("gray"))
  7107. # # add the tab if it was closed
  7108. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7109. # # first clear previous text in text editor (if any)
  7110. # self.ui.text_editor_tab.code_editor.clear()
  7111. #
  7112. # # Switch plot_area to CNCJob tab
  7113. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7114. # close the Code editor if already open
  7115. if self.toggle_codeeditor:
  7116. self.on_toggle_code_editor()
  7117. self.on_toggle_code_editor()
  7118. try:
  7119. if filename:
  7120. f = QtCore.QFile(filename)
  7121. if f.open(QtCore.QIODevice.ReadOnly):
  7122. stream = QtCore.QTextStream(f)
  7123. code_edited = stream.readAll()
  7124. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7125. f.close()
  7126. except IOError:
  7127. App.log.error("Failed to open config file: %s" % filename)
  7128. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7129. (_("Failed to open config file"), filename))
  7130. return
  7131. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7132. """
  7133. Loads a project from the specified file.
  7134. 1) Loads and parses file
  7135. 2) Registers the file as recently opened.
  7136. 3) Calls on_file_new()
  7137. 4) Updates options
  7138. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7139. 6) Calls plot_all() if plot=True
  7140. :param filename: Name of the file from which to load.
  7141. :param run_from_arg: True if run for arguments
  7142. :param plot: If True plot all objects in the project
  7143. :param cli: Run from command line
  7144. :param from_tcl: True if run from Tcl Sehll
  7145. :return: None
  7146. """
  7147. App.log.debug("Opening project: " + filename)
  7148. # block autosaving while a project is loaded
  7149. self.block_autosave = True
  7150. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7151. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7152. if cli is None:
  7153. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7154. if run_from_arg:
  7155. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7156. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7157. _("Opening FlatCAM Project file.")),
  7158. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7159. color=QtGui.QColor("gray"))
  7160. # Open and parse an uncompressed Project file
  7161. try:
  7162. f = open(filename, 'r')
  7163. except IOError:
  7164. if from_tcl:
  7165. name = filename.split('/')[-1].split('\\')[-1]
  7166. filename = self.defaults['global_tcl_path'] + '/' + name
  7167. try:
  7168. f = open(filename, 'r')
  7169. except IOError:
  7170. log.error("Failed to open project file: %s" % filename)
  7171. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7172. return
  7173. else:
  7174. log.error("Failed to open project file: %s" % filename)
  7175. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7176. return
  7177. try:
  7178. d = json.load(f, object_hook=dict2obj)
  7179. except Exception as e:
  7180. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7181. (filename, str(e)))
  7182. f.close()
  7183. # Open and parse a compressed Project file
  7184. try:
  7185. with lzma.open(filename) as f:
  7186. file_content = f.read().decode('utf-8')
  7187. d = json.loads(file_content, object_hook=dict2obj)
  7188. except Exception as e:
  7189. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7190. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7191. return
  7192. # Clear the current project
  7193. # # NOT THREAD SAFE # ##
  7194. if run_from_arg is True:
  7195. pass
  7196. elif cli is True:
  7197. self.delete_selection_shape()
  7198. else:
  7199. self.on_file_new()
  7200. # Project options
  7201. self.options.update(d['options'])
  7202. self.project_filename = filename
  7203. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7204. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7205. if cli is None:
  7206. self.set_screen_units(self.options["units"])
  7207. # Re create objects
  7208. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7209. for obj in d['objs']:
  7210. try:
  7211. def obj_init(obj_inst, app_inst):
  7212. obj_inst.from_dict(obj)
  7213. App.log.debug("Recreating from opened project an %s object: %s" %
  7214. (obj['kind'].capitalize(), obj['options']['name']))
  7215. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7216. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7217. if cli is None:
  7218. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7219. obj['kind'].upper(),
  7220. obj['options']['name']
  7221. )
  7222. )
  7223. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7224. except Exception as e:
  7225. print('App.open_project() --> ' + str(e))
  7226. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7227. self.should_we_save = False
  7228. self.file_opened.emit("project", filename)
  7229. # restore autosaving after a project was loaded
  7230. self.block_autosave = False
  7231. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7232. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7233. if cli is None:
  7234. self.set_ui_title(name=self.project_filename)
  7235. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7236. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7237. """
  7238. Re-generates all plots from all objects.
  7239. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7240. :param muted: if True don't print messages
  7241. :param use_thread: if True will use threading for plotting the objects
  7242. :return: None
  7243. """
  7244. self.log.debug("Plot_all()")
  7245. if muted is not True:
  7246. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7247. for plot_obj in self.collection.get_list():
  7248. def worker_task(obj):
  7249. with self.proc_container.new("Plotting"):
  7250. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7251. if fit_view is True:
  7252. self.app_obj.object_plotted.emit(obj)
  7253. if use_thread is True:
  7254. # Send to worker
  7255. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7256. else:
  7257. worker_task(plot_obj)
  7258. def register_folder(self, filename):
  7259. """
  7260. Register the last folder used by the app to open something
  7261. :param filename: the last folder is extracted from the filename
  7262. :return: None
  7263. """
  7264. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7265. def register_save_folder(self, filename):
  7266. """
  7267. Register the last folder used by the app to save something
  7268. :param filename: the last folder is extracted from the filename
  7269. :return: None
  7270. """
  7271. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7272. # def set_progress_bar(self, percentage, text=""):
  7273. # """
  7274. # Set a progress bar to a value (percentage)
  7275. #
  7276. # :param percentage: Value set to the progressbar
  7277. # :param text: Not used
  7278. # :return: None
  7279. # """
  7280. # self.ui.progress_bar.setValue(int(percentage))
  7281. def setup_recent_items(self):
  7282. """
  7283. Setup a dictionary with the recent files accessed, organized by type
  7284. :return:
  7285. """
  7286. icons = {
  7287. "gerber": self.resource_location + "/flatcam_icon16.png",
  7288. "excellon": self.resource_location + "/drill16.png",
  7289. 'geometry': self.resource_location + "/geometry16.png",
  7290. "cncjob": self.resource_location + "/cnc16.png",
  7291. "script": self.resource_location + "/script_new24.png",
  7292. "document": self.resource_location + "/notes16_1.png",
  7293. "project": self.resource_location + "/project16.png",
  7294. "svg": self.resource_location + "/geometry16.png",
  7295. "dxf": self.resource_location + "/dxf16.png",
  7296. "pdf": self.resource_location + "/pdf32.png",
  7297. "image": self.resource_location + "/image16.png"
  7298. }
  7299. try:
  7300. image_opener = self.image_tool.import_image
  7301. except AttributeError:
  7302. image_opener = None
  7303. openers = {
  7304. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7305. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7306. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7307. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7308. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7309. "document": None,
  7310. 'project': self.open_project,
  7311. 'svg': self.import_svg,
  7312. 'dxf': self.import_dxf,
  7313. 'image': image_opener,
  7314. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7315. }
  7316. # Open recent file for files
  7317. try:
  7318. f = open(self.data_path + '/recent.json')
  7319. except IOError:
  7320. App.log.error("Failed to load recent item list.")
  7321. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7322. return
  7323. try:
  7324. self.recent = json.load(f)
  7325. except json.errors.JSONDecodeError:
  7326. App.log.error("Failed to parse recent item list.")
  7327. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7328. f.close()
  7329. return
  7330. f.close()
  7331. # Open recent file for projects
  7332. try:
  7333. fp = open(self.data_path + '/recent_projects.json')
  7334. except IOError:
  7335. App.log.error("Failed to load recent project item list.")
  7336. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7337. return
  7338. try:
  7339. self.recent_projects = json.load(fp)
  7340. except json.errors.JSONDecodeError:
  7341. App.log.error("Failed to parse recent project item list.")
  7342. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7343. fp.close()
  7344. return
  7345. fp.close()
  7346. # Closure needed to create callbacks in a loop.
  7347. # Otherwise late binding occurs.
  7348. def make_callback(func, fname):
  7349. def opener():
  7350. func(fname)
  7351. return opener
  7352. def reset_recent_files():
  7353. # Reset menu
  7354. self.ui.recent.clear()
  7355. self.recent = []
  7356. try:
  7357. ff = open(self.data_path + '/recent.json', 'w')
  7358. except IOError:
  7359. App.log.error("Failed to open recent items file for writing.")
  7360. return
  7361. json.dump(self.recent, ff)
  7362. def reset_recent_projects():
  7363. # Reset menu
  7364. self.ui.recent_projects.clear()
  7365. self.recent_projects = []
  7366. try:
  7367. frp = open(self.data_path + '/recent_projects.json', 'w')
  7368. except IOError:
  7369. App.log.error("Failed to open recent projects items file for writing.")
  7370. return
  7371. json.dump(self.recent, frp)
  7372. # Reset menu
  7373. self.ui.recent.clear()
  7374. self.ui.recent_projects.clear()
  7375. # Create menu items for projects
  7376. for recent in self.recent_projects:
  7377. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7378. if recent['kind'] == 'project':
  7379. try:
  7380. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7381. # Attach callback
  7382. o = make_callback(openers[recent["kind"]], recent['filename'])
  7383. action.triggered.connect(o)
  7384. self.ui.recent_projects.addAction(action)
  7385. except KeyError:
  7386. App.log.error("Unsupported file type: %s" % recent["kind"])
  7387. # Last action in Recent Files menu is one that Clear the content
  7388. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7389. (_("Clear Recent projects")), self)
  7390. clear_action_proj.triggered.connect(reset_recent_projects)
  7391. self.ui.recent_projects.addSeparator()
  7392. self.ui.recent_projects.addAction(clear_action_proj)
  7393. # Create menu items for files
  7394. for recent in self.recent:
  7395. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7396. if recent['kind'] != 'project':
  7397. try:
  7398. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7399. # Attach callback
  7400. o = make_callback(openers[recent["kind"]], recent['filename'])
  7401. action.triggered.connect(o)
  7402. self.ui.recent.addAction(action)
  7403. except KeyError:
  7404. App.log.error("Unsupported file type: %s" % recent["kind"])
  7405. # Last action in Recent Files menu is one that Clear the content
  7406. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7407. (_("Clear Recent files")), self)
  7408. clear_action.triggered.connect(reset_recent_files)
  7409. self.ui.recent.addSeparator()
  7410. self.ui.recent.addAction(clear_action)
  7411. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7412. # self.ui.menufilerecent.set_submenu(recent_menu)
  7413. # recent_menu.show_all()
  7414. # self.ui.recent.show()
  7415. self.log.debug("Recent items list has been populated.")
  7416. def setup_component_editor(self):
  7417. """
  7418. Default text for the Selected tab when is not taken by the Object UI.
  7419. :return:
  7420. """
  7421. # label = QtWidgets.QLabel("Choose an item from Project")
  7422. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7423. sel_title = QtWidgets.QTextEdit(
  7424. _('<b>Shortcut Key List</b>'))
  7425. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7426. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7427. f_settings = QSettings("Open Source", "FlatCAM")
  7428. if f_settings.contains("notebook_font_size"):
  7429. fsize = f_settings.value('notebook_font_size', type=int)
  7430. else:
  7431. fsize = 12
  7432. tsize = fsize + int(fsize / 2)
  7433. # selected_text = (_('''
  7434. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7435. # </p>
  7436. #
  7437. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7438. # The normal flow when working in FlatCAM is the following:</span></p>
  7439. #
  7440. # <ol>
  7441. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7442. # file into
  7443. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7444. # even dragging and dropping the files on the AppGUI.<br />
  7445. # <br />
  7446. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7447. # drop of the
  7448. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7449. # &nbsp;</li>
  7450. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7451. # and then
  7452. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7453. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7454. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7455. # <br />
  7456. # If the selection of the object is done on the canvas by single click instead, and the
  7457. # <strong>SELECTED TAB</strong>
  7458. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7459. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7460. # it even if it was out of focus.<br />
  7461. # <br />
  7462. # You can change the parameters in this screen and the flow direction is like this:<br />
  7463. # <br />
  7464. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7465. # <strong> Geometry Object
  7466. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7467. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7468. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7469. # </ol>
  7470. #
  7471. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7472. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7473. # <strong>F3</strong>.</span></p>
  7474. #
  7475. # ''').format(fsize=fsize, tsize=tsize))
  7476. selected_text = '''
  7477. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7478. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7479. {s1}</span></p>
  7480. <ol>
  7481. <li><span style="font-size:{fsize}px">{s2}<br />
  7482. <br />
  7483. {s3}</span><br />
  7484. &nbsp;</li>
  7485. <li><span style="font-size:{fsize}px">{s4}<br />
  7486. &nbsp;</li>
  7487. <br />
  7488. <li><span style="font-size:{fsize}px">{s5}<br />
  7489. &nbsp;</li>
  7490. <br />
  7491. <li><span style="font-size:{fsize}px">{s6}<br />
  7492. <br />
  7493. {s7}</span></li>
  7494. </ol>
  7495. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7496. '''.format(
  7497. title=_("Selected Tab - Choose an Item from Project Tab"),
  7498. subtitle=_("Details"),
  7499. s1=_("The normal flow when working in FlatCAM is the following:"),
  7500. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  7501. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7502. "files on the AppGUI."),
  7503. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  7504. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  7505. "actions offered within the app."),
  7506. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7507. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7508. "SELECTED TAB will be updated with the object properties according to its kind: "
  7509. "Gerber, Excellon, Geometry or CNCJob object."),
  7510. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7511. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7512. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7513. "the SELECTED TAB and populate it even if it was out of focus."),
  7514. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7515. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7516. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7517. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7518. "(again, done in SELECTED TAB) --> Save GCode."),
  7519. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7520. "or through its own key shortcut: <b>F3</b>."),
  7521. tsize=tsize,
  7522. fsize=fsize
  7523. )
  7524. sel_title.setText(selected_text)
  7525. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7526. self.ui.selected_scroll_area.setWidget(sel_title)
  7527. def setup_obj_classes(self):
  7528. """
  7529. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7530. class.
  7531. :return: None
  7532. """
  7533. FlatCAMObj.app = self
  7534. ObjectCollection.app = self
  7535. Gerber.app = self
  7536. Excellon.app = self
  7537. Geometry.app = self
  7538. CNCjob.app = self
  7539. FCProcess.app = self
  7540. FCProcessContainer.app = self
  7541. OptionsGroupUI.app = self
  7542. def version_check(self):
  7543. """
  7544. Checks for the latest version of the program. Alerts the
  7545. user if theirs is outdated. This method is meant to be run
  7546. in a separate thread.
  7547. :return: None
  7548. """
  7549. self.log.debug("version_check()")
  7550. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7551. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7552. App.version_url,
  7553. str(self.defaults['global_serial']),
  7554. str(self.version),
  7555. str(self.os),
  7556. urllib.parse.urlencode(self.defaults["global_stats"])
  7557. )
  7558. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7559. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7560. # urllib.parse.urlencode(self.defaults["global_stats"])
  7561. else:
  7562. # no_stats dict; just so it won't break things on website
  7563. no_ststs_dict = {}
  7564. no_ststs_dict["global_ststs"] = {}
  7565. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7566. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7567. App.log.debug("Checking for updates @ %s" % full_url)
  7568. # ## Get the data
  7569. try:
  7570. f = urllib.request.urlopen(full_url)
  7571. except Exception:
  7572. # App.log.warning("Failed checking for latest version. Could not connect.")
  7573. self.log.warning("Failed checking for latest version. Could not connect.")
  7574. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7575. return
  7576. try:
  7577. data = json.load(f)
  7578. except Exception as e:
  7579. App.log.error("Could not parse information about latest version.")
  7580. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7581. App.log.debug("json.load(): %s" % str(e))
  7582. f.close()
  7583. return
  7584. f.close()
  7585. # ## Latest version?
  7586. if self.version >= data["version"]:
  7587. App.log.debug("FlatCAM is up to date!")
  7588. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7589. return
  7590. App.log.debug("Newer version available.")
  7591. self.message.emit(
  7592. _("Newer Version Available"),
  7593. '%s<br><br>><b>%s</b><br>%s' % (
  7594. _("There is a newer version of FlatCAM available for download:"),
  7595. str(data["name"]),
  7596. str(data["message"])
  7597. ),
  7598. _("info")
  7599. )
  7600. def on_plotcanvas_setup(self, container=None):
  7601. """
  7602. This is doing the setup for the plot area (canvas).
  7603. :param container: QT Widget where to install the canvas
  7604. :return: None
  7605. """
  7606. if container:
  7607. plot_container = container
  7608. else:
  7609. plot_container = self.ui.right_layout
  7610. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7611. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7612. self.is_legacy = True
  7613. self.defaults["global_graphic_engine"] = "2D"
  7614. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7615. else:
  7616. try:
  7617. self.plotcanvas = PlotCanvas(plot_container, self)
  7618. except Exception as er:
  7619. msg_txt = traceback.format_exc()
  7620. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7621. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7622. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7623. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7624. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7625. msg += msg_txt
  7626. self.inform.emit(msg)
  7627. return 'fail'
  7628. # So it can receive key presses
  7629. self.plotcanvas.native.setFocus()
  7630. if self.is_legacy is False:
  7631. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7632. # Set the mouse button for panning
  7633. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7634. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7635. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7636. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7637. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7638. # Keys over plot enabled
  7639. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7640. if self.defaults['global_cursor_type'] == 'small':
  7641. self.app_cursor = self.plotcanvas.new_cursor()
  7642. else:
  7643. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7644. if self.ui.grid_snap_btn.isChecked():
  7645. self.app_cursor.enabled = True
  7646. else:
  7647. self.app_cursor.enabled = False
  7648. if self.is_legacy is False:
  7649. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7650. else:
  7651. # will use the default Matplotlib axes
  7652. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7653. def on_zoom_fit(self):
  7654. """
  7655. Callback for zoom-fit request. This can be either from the corresponding
  7656. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7657. with axes limits from the geometry bounds of all objects.
  7658. :return: None
  7659. """
  7660. if self.is_legacy is False:
  7661. self.plotcanvas.fit_view()
  7662. else:
  7663. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7664. width = xmax - xmin
  7665. height = ymax - ymin
  7666. xmin -= 0.05 * width
  7667. xmax += 0.05 * width
  7668. ymin -= 0.05 * height
  7669. ymax += 0.05 * height
  7670. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7671. def on_zoom_in(self):
  7672. """
  7673. Callback for zoom-in request.
  7674. :return:
  7675. """
  7676. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7677. def on_zoom_out(self):
  7678. """
  7679. Callback for zoom-out request.
  7680. :return:
  7681. """
  7682. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7683. def disable_all_plots(self):
  7684. self.defaults.report_usage("disable_all_plots()")
  7685. self.disable_plots(self.collection.get_list())
  7686. self.inform.emit('[success] %s' %
  7687. _("All plots disabled."))
  7688. def disable_other_plots(self):
  7689. self.defaults.report_usage("disable_other_plots()")
  7690. self.disable_plots(self.collection.get_non_selected())
  7691. self.inform.emit('[success] %s' %
  7692. _("All non selected plots disabled."))
  7693. def enable_all_plots(self):
  7694. self.defaults.report_usage("enable_all_plots()")
  7695. self.enable_plots(self.collection.get_list())
  7696. self.inform.emit('[success] %s' %
  7697. _("All plots enabled."))
  7698. def on_enable_sel_plots(self):
  7699. log.debug("App.on_enable_sel_plot()")
  7700. object_list = self.collection.get_selected()
  7701. self.enable_plots(objects=object_list)
  7702. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7703. def on_disable_sel_plots(self):
  7704. log.debug("App.on_disable_sel_plot()")
  7705. # self.inform.emit(_("Disabling plots ..."))
  7706. object_list = self.collection.get_selected()
  7707. self.disable_plots(objects=object_list)
  7708. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7709. def enable_plots(self, objects):
  7710. """
  7711. Enable plots
  7712. :param objects: list of Objects to be enabled
  7713. :return:
  7714. """
  7715. log.debug("Enabling plots ...")
  7716. # self.inform.emit(_("Working ..."))
  7717. for obj in objects:
  7718. if obj.options['plot'] is False:
  7719. obj.options.set_change_callback(lambda x: None)
  7720. obj.options['plot'] = True
  7721. try:
  7722. # only the Gerber obj has on_plot_cb_click() method
  7723. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7724. # disable this cb while disconnected,
  7725. # in case the operation takes time the user is not allowed to change it
  7726. obj.ui.plot_cb.setDisabled(True)
  7727. except AttributeError:
  7728. pass
  7729. obj.set_form_item("plot")
  7730. try:
  7731. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7732. obj.ui.plot_cb.setDisabled(False)
  7733. except AttributeError:
  7734. pass
  7735. obj.options.set_change_callback(obj.on_options_change)
  7736. def worker_task(objs):
  7737. with self.proc_container.new(_("Enabling plots ...")):
  7738. for plot_obj in objs:
  7739. # obj.options['plot'] = True
  7740. if isinstance(plot_obj, CNCJobObject):
  7741. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7742. else:
  7743. plot_obj.plot(visible=True)
  7744. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7745. def disable_plots(self, objects):
  7746. """
  7747. Disables plots
  7748. :param objects: list of Objects to be disabled
  7749. :return:
  7750. """
  7751. # if no objects selected then do nothing
  7752. if not self.collection.get_selected():
  7753. return
  7754. log.debug("Disabling plots ...")
  7755. # self.inform.emit(_("Working ..."))
  7756. for obj in objects:
  7757. if obj.options['plot'] is True:
  7758. obj.options.set_change_callback(lambda x: None)
  7759. obj.options['plot'] = False
  7760. try:
  7761. # only the Gerber obj has on_plot_cb_click() method
  7762. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7763. obj.ui.plot_cb.setDisabled(True)
  7764. except AttributeError:
  7765. pass
  7766. obj.set_form_item("plot")
  7767. try:
  7768. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7769. obj.ui.plot_cb.setDisabled(False)
  7770. except AttributeError:
  7771. pass
  7772. obj.options.set_change_callback(obj.on_options_change)
  7773. try:
  7774. self.delete_selection_shape()
  7775. except Exception as e:
  7776. log.debug("App.disable_plots() --> %s" % str(e))
  7777. def worker_task(objs):
  7778. with self.proc_container.new(_("Disabling plots ...")):
  7779. for plot_obj in objs:
  7780. # obj.options['plot'] = True
  7781. if isinstance(plot_obj, CNCJobObject):
  7782. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7783. else:
  7784. plot_obj.plot(visible=False)
  7785. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7786. def toggle_plots(self, objects):
  7787. """
  7788. Toggle plots visibility
  7789. :param objects: list of Objects for which to be toggled the visibility
  7790. :return: None
  7791. """
  7792. # if no objects selected then do nothing
  7793. if not self.collection.get_selected():
  7794. return
  7795. log.debug("Toggling plots ...")
  7796. self.inform.emit(_("Working ..."))
  7797. for obj in objects:
  7798. if obj.options['plot'] is False:
  7799. obj.options['plot'] = True
  7800. else:
  7801. obj.options['plot'] = False
  7802. self.app_obj.plots_updated.emit()
  7803. def clear_plots(self):
  7804. """
  7805. Clear the plots
  7806. :return: None
  7807. """
  7808. objects = self.collection.get_list()
  7809. for obj in objects:
  7810. obj.clear(obj == objects[-1])
  7811. # Clear pool to free memory
  7812. self.clear_pool()
  7813. def on_set_color_action_triggered(self):
  7814. """
  7815. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  7816. :return:
  7817. """
  7818. new_color = self.defaults['gerber_plot_fill']
  7819. clicked_action = self.sender()
  7820. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  7821. act_name = clicked_action.text()
  7822. sel_obj_list = self.collection.get_selected()
  7823. if not sel_obj_list:
  7824. return
  7825. # a default value, I just chose this one
  7826. alpha_level = 'BF'
  7827. for sel_obj in sel_obj_list:
  7828. if sel_obj.kind == 'excellon':
  7829. alpha_level = str(hex(
  7830. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  7831. elif sel_obj.kind == 'gerber':
  7832. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  7833. elif sel_obj.kind == 'geometry':
  7834. alpha_level = 'FF'
  7835. else:
  7836. log.debug(
  7837. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  7838. continue
  7839. sel_obj.alpha_level = alpha_level
  7840. if act_name == _('Red'):
  7841. new_color = '#FF0000' + alpha_level
  7842. if act_name == _('Blue'):
  7843. new_color = '#0000FF' + alpha_level
  7844. if act_name == _('Yellow'):
  7845. new_color = '#FFDF00' + alpha_level
  7846. if act_name == _('Green'):
  7847. new_color = '#00FF00' + alpha_level
  7848. if act_name == _('Purple'):
  7849. new_color = '#FF00FF' + alpha_level
  7850. if act_name == _('Brown'):
  7851. new_color = '#A52A2A' + alpha_level
  7852. if act_name == _('White'):
  7853. new_color = '#FFFFFF' + alpha_level
  7854. if act_name == _('Black'):
  7855. new_color = '#000000' + alpha_level
  7856. if act_name == _('Custom'):
  7857. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  7858. c_dialog = QtWidgets.QColorDialog()
  7859. plot_fill_color = c_dialog.getColor(initial=new_color)
  7860. if plot_fill_color.isValid() is False:
  7861. return
  7862. new_color = str(plot_fill_color.name()) + alpha_level
  7863. if act_name == _("Default"):
  7864. for sel_obj in sel_obj_list:
  7865. if sel_obj.kind == 'excellon':
  7866. new_color = self.defaults['excellon_plot_fill']
  7867. new_line_color = self.defaults['excellon_plot_line']
  7868. elif sel_obj.kind == 'gerber':
  7869. new_color = self.defaults['gerber_plot_fill']
  7870. new_line_color = self.defaults['gerber_plot_line']
  7871. elif sel_obj.kind == 'geometry':
  7872. new_color = self.defaults['geometry_plot_line']
  7873. new_line_color = self.defaults['geometry_plot_line']
  7874. else:
  7875. log.debug(
  7876. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  7877. continue
  7878. sel_obj.fill_color = new_color
  7879. sel_obj.outline_color = new_line_color
  7880. sel_obj.shapes.redraw(
  7881. update_colors=(new_color, new_line_color)
  7882. )
  7883. return
  7884. if act_name == _("Opacity"):
  7885. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  7886. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  7887. if ok_button:
  7888. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  7889. for sel_obj in sel_obj_list:
  7890. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  7891. sel_obj.shapes.redraw(
  7892. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  7893. )
  7894. return
  7895. new_line_color = color_variant(new_color[:7], 0.7)
  7896. if act_name == _("White"):
  7897. new_line_color = color_variant("#dedede", 0.7)
  7898. for sel_obj in sel_obj_list:
  7899. sel_obj.fill_color = new_color
  7900. sel_obj.outline_color = new_line_color
  7901. sel_obj.shapes.redraw(
  7902. update_colors=(new_color, new_line_color)
  7903. )
  7904. def generate_cnc_job(self, objects):
  7905. """
  7906. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  7907. :param objects: Selected objects in the Project Tab
  7908. :return:
  7909. """
  7910. self.defaults.report_usage("generate_cnc_job()")
  7911. # for obj in objects:
  7912. # obj.generatecncjob()
  7913. for obj in objects:
  7914. obj.on_generatecnc_button_click()
  7915. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  7916. """
  7917. Saves the current project to the specified file.
  7918. :param filename: Name of the file in which to save.
  7919. :type filename: str
  7920. :param quit_action: if the project saving will be followed by an app quit; boolean
  7921. :param silent: if True will not display status messages
  7922. :param from_tcl True is run from Tcl Shell
  7923. :return: None
  7924. """
  7925. self.log.debug("save_project()")
  7926. self.save_in_progress = True
  7927. with self.proc_container.new(_("Saving FlatCAM Project")):
  7928. # Capture the latest changes
  7929. # Current object
  7930. try:
  7931. current_object = self.collection.get_active()
  7932. if current_object:
  7933. current_object.read_form()
  7934. except Exception as e:
  7935. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  7936. pass
  7937. # Serialize the whole project
  7938. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  7939. "options": self.options,
  7940. "version": self.version}
  7941. if self.defaults["global_save_compressed"] is True:
  7942. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  7943. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  7944. # # Write
  7945. f.write(g)
  7946. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  7947. else:
  7948. # Open file
  7949. try:
  7950. f = open(filename, 'w')
  7951. except IOError:
  7952. App.log.error("Failed to open file for saving: %s", filename)
  7953. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  7954. return
  7955. # Write
  7956. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  7957. f.close()
  7958. # verification of the saved project
  7959. # Open and parse
  7960. try:
  7961. saved_f = open(filename, 'r')
  7962. except IOError:
  7963. if silent is False:
  7964. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  7965. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  7966. return
  7967. try:
  7968. saved_d = json.load(saved_f, object_hook=dict2obj)
  7969. except Exception:
  7970. if silent is False:
  7971. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  7972. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  7973. f.close()
  7974. return
  7975. saved_f.close()
  7976. if silent is False:
  7977. if 'version' in saved_d:
  7978. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  7979. else:
  7980. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  7981. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  7982. tb_settings = QSettings("Open Source", "FlatCAM")
  7983. lock_state = self.ui.lock_action.isChecked()
  7984. tb_settings.setValue('toolbar_lock', lock_state)
  7985. # This will write the setting to the platform specific storage.
  7986. del tb_settings
  7987. # if quit:
  7988. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  7989. # t.start()
  7990. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  7991. def start_delayed_quit(self, delay, filename, should_quit=None):
  7992. """
  7993. :param delay: period of checking if project file size is more than zero; in seconds
  7994. :param filename: the name of the project file to be checked periodically for size more than zero
  7995. :param should_quit: if the task finished will be followed by an app quit; boolean
  7996. :return:
  7997. """
  7998. to_quit = should_quit
  7999. self.save_timer = QtCore.QTimer()
  8000. self.save_timer.setInterval(delay)
  8001. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8002. self.save_timer.start()
  8003. def check_project_file_size(self, filename, should_quit=None):
  8004. """
  8005. :param filename: the name of the project file to be checked periodically for size more than zero
  8006. :param should_quit: will quit the app if True; boolean
  8007. :return:
  8008. """
  8009. try:
  8010. if os.stat(filename).st_size > 0:
  8011. self.save_in_progress = False
  8012. self.save_timer.stop()
  8013. if should_quit:
  8014. self.app_quit.emit()
  8015. except Exception:
  8016. traceback.print_exc()
  8017. def save_project_auto(self):
  8018. """
  8019. Called periodically to save the project.
  8020. 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
  8021. # progress.
  8022. :return:
  8023. """
  8024. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8025. self.on_file_saveproject()
  8026. def save_project_auto_update(self):
  8027. """
  8028. Update the auto save time interval value.
  8029. :return:
  8030. """
  8031. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8032. try:
  8033. if self.autosave_timer.isActive():
  8034. self.autosave_timer.stop()
  8035. except Exception:
  8036. pass
  8037. if self.defaults['global_autosave'] is True:
  8038. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8039. self.autosave_timer.start()
  8040. def on_options_app2project(self):
  8041. """
  8042. Callback for Options->Transfer Options->App=>Project. Copies options
  8043. from application defaults to project defaults.
  8044. :return: None
  8045. """
  8046. self.defaults.report_usage("on_options_app2project")
  8047. self.preferencesUiManager.defaults_read_form()
  8048. self.options.update(self.defaults)
  8049. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8050. """
  8051. Shows a message on the FlatCAM Shell
  8052. :param msg: Message to display.
  8053. :param show: Opens the shell.
  8054. :param error: Shows the message as an error.
  8055. :param warning: Shows the message as an warning.
  8056. :param success: Shows the message as an success.
  8057. :param selected: Indicate that something was selected on canvas
  8058. :return: None
  8059. """
  8060. if show:
  8061. self.ui.shell_dock.show()
  8062. try:
  8063. if error:
  8064. self.shell.append_error(msg + "\n")
  8065. elif warning:
  8066. self.shell.append_warning(msg + "\n")
  8067. elif success:
  8068. self.shell.append_success(msg + "\n")
  8069. elif selected:
  8070. self.shell.append_selected(msg + "\n")
  8071. else:
  8072. self.shell.append_output(msg + "\n")
  8073. except AttributeError:
  8074. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8075. class ArgsThread(QtCore.QObject):
  8076. open_signal = pyqtSignal(list)
  8077. start = pyqtSignal()
  8078. stop = pyqtSignal()
  8079. if sys.platform == 'win32':
  8080. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8081. else:
  8082. address = ('/tmp/testipc', 'AF_UNIX')
  8083. def __init__(self):
  8084. super(ArgsThread, self).__init__()
  8085. self.listener = None
  8086. self.thread_exit = False
  8087. self.start.connect(self.run)
  8088. self.stop.connect(self.close_listener)
  8089. def my_loop(self, address):
  8090. try:
  8091. self.listener = Listener(*address)
  8092. while self.thread_exit is False:
  8093. conn = self.listener.accept()
  8094. self.serve(conn)
  8095. except socket.error:
  8096. try:
  8097. conn = Client(*address)
  8098. conn.send(sys.argv)
  8099. conn.send('close')
  8100. # close the current instance only if there are args
  8101. if len(sys.argv) > 1:
  8102. try:
  8103. self.listener.close()
  8104. except Exception:
  8105. pass
  8106. sys.exit()
  8107. except ConnectionRefusedError:
  8108. if sys.platform == 'win32':
  8109. pass
  8110. else:
  8111. os.system('rm /tmp/testipc')
  8112. self.listener = Listener(*address)
  8113. while True:
  8114. conn = self.listener.accept()
  8115. self.serve(conn)
  8116. def serve(self, conn):
  8117. while self.thread_exit is False:
  8118. msg = conn.recv()
  8119. if msg == 'close':
  8120. break
  8121. self.open_signal.emit(msg)
  8122. conn.close()
  8123. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8124. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8125. @pyqtSlot()
  8126. def run(self):
  8127. self.my_loop(self.address)
  8128. @pyqtSlot()
  8129. def close_listener(self):
  8130. self.thread_exit = True
  8131. self.listener.close()
  8132. # end of file