app_Main.py 466 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387
  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 shapely.ops import unary_union
  23. from io import StringIO
  24. from reportlab.graphics import renderPDF
  25. from reportlab.pdfgen import canvas
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. import gc
  30. from xml.dom.minidom import parseString as parse_xml_string
  31. from multiprocessing.connection import Listener, Client
  32. from multiprocessing import Pool
  33. import socket
  34. # ####################################################################################################################
  35. # ################################### Imports part of FlatCAM #############################################
  36. # ####################################################################################################################
  37. # Various
  38. from Common import LoudDict
  39. from Common import color_variant
  40. from Common import ExclusionAreas
  41. from Bookmark import BookmarkManager
  42. from appDatabase import ToolsDB2
  43. from vispy.gloo.util import _screenshot
  44. from vispy.io import write_png
  45. # FlatCAM defaults (preferences)
  46. from defaults import FlatCAMDefaults
  47. # FlatCAM Objects
  48. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  49. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  50. from appObjects.ObjectCollection import *
  51. from appObjects.FlatCAMObj import FlatCAMObj
  52. from appObjects.AppObject import AppObject
  53. # FlatCAM Parsing files
  54. from appParsers.ParseExcellon import Excellon
  55. from appParsers.ParseGerber import Gerber
  56. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  57. # FlatCAM appGUI
  58. from appGUI.PlotCanvas import *
  59. from appGUI.PlotCanvasLegacy import *
  60. from appGUI.MainGUI import *
  61. from appGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  62. # FlatCAM Pre-processors
  63. from appPreProcessor import load_preprocessors
  64. # FlatCAM appEditors
  65. from appEditors.AppGeoEditor import AppGeoEditor
  66. from appEditors.AppExcEditor import AppExcEditor
  67. from appEditors.AppGerberEditor import AppGerberEditor
  68. from appEditors.AppTextEditor import AppTextEditor
  69. from appParsers.ParseHPGL2 import HPGL2
  70. # FlatCAM Workers
  71. from appProcess import *
  72. from appWorkerStack import WorkerStack
  73. # FlatCAM Tools
  74. from appTools import *
  75. # FlatCAM Translation
  76. import gettext
  77. import appTranslation as fcTranslate
  78. import builtins
  79. if sys.platform == 'win32':
  80. import winreg
  81. from win32comext.shell import shell, shellcon
  82. fcTranslate.apply_language('strings')
  83. if '_' not in builtins.__dict__:
  84. _ = gettext.gettext
  85. class App(QtCore.QObject):
  86. """
  87. The main application class. The constructor starts the GUI and all other classes used by the program.
  88. """
  89. # ###############################################################################################################
  90. # ########################################## App ################################################################
  91. # ###############################################################################################################
  92. # ###############################################################################################################
  93. # ######################################### LOGGING #############################################################
  94. # ###############################################################################################################
  95. log = logging.getLogger('base')
  96. log.setLevel(logging.DEBUG)
  97. # log.setLevel(logging.WARNING)
  98. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  99. handler = logging.StreamHandler()
  100. handler.setFormatter(formatter)
  101. log.addHandler(handler)
  102. # ###############################################################################################################
  103. # #################################### Get Cmd Line Options #####################################################
  104. # ###############################################################################################################
  105. cmd_line_shellfile = ''
  106. cmd_line_shellvar = ''
  107. cmd_line_headless = None
  108. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  109. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  110. "FlatCam.py --headless=1"
  111. try:
  112. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  113. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  114. "shellvar=",
  115. "headless=",
  116. "multiprocessing-fork="])
  117. except getopt.GetoptError:
  118. print(cmd_line_help)
  119. sys.exit(2)
  120. for opt, arg in cmd_line_options:
  121. if opt == '-h':
  122. print(cmd_line_help)
  123. sys.exit()
  124. elif opt == '--shellfile':
  125. cmd_line_shellfile = arg
  126. elif opt == '--shellvar':
  127. cmd_line_shellvar = arg
  128. elif opt == '--headless':
  129. try:
  130. cmd_line_headless = eval(arg)
  131. except NameError:
  132. pass
  133. # ###############################################################################################################
  134. # ################################### Version and VERSION DATE ##################################################
  135. # ###############################################################################################################
  136. version = "Unstable Version"
  137. # version = 8.994
  138. version_date = "2020/07/05"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by: App.info() --> Print on the status bar
  169. inform = QtCore.pyqtSignal([str], [str, bool])
  170. # Handled by: App.info_shell() --> Print on the shell
  171. inform_shell = QtCore.pyqtSignal(str)
  172. app_quit = QtCore.pyqtSignal()
  173. # General purpose background task
  174. worker_task = QtCore.pyqtSignal(dict)
  175. # File opened
  176. # Handled by:
  177. # * register_folder()
  178. # * register_recent()
  179. # Note: Setting the parameters to unicode does not seem
  180. # to have an effect. Then are received as Qstring
  181. # anyway.
  182. # File type and filename
  183. file_opened = QtCore.pyqtSignal(str, str)
  184. # File type and filename
  185. file_saved = QtCore.pyqtSignal(str, str)
  186. # Percentage of progress
  187. progress = QtCore.pyqtSignal(int)
  188. # Emitted when a new object has been added or deleted from/to the collection
  189. object_status_changed = QtCore.pyqtSignal(object, str, str)
  190. message = QtCore.pyqtSignal(str, str, str)
  191. # Emmited when shell command is finished(one command only)
  192. shell_command_finished = QtCore.pyqtSignal(object)
  193. # Emitted when multiprocess pool has been recreated
  194. pool_recreated = QtCore.pyqtSignal(object)
  195. # Emitted when an unhandled exception happens
  196. # in the worker task.
  197. thread_exception = QtCore.pyqtSignal(object)
  198. # used to signal that there are arguments for the app
  199. args_at_startup = QtCore.pyqtSignal(list)
  200. # a reusable signal to replot a list of objects
  201. # should be disconnected after use so it can be reused
  202. replot_signal = pyqtSignal(list)
  203. # signal emitted when jumping
  204. jump_signal = pyqtSignal(tuple)
  205. # signal emitted when jumping
  206. locate_signal = pyqtSignal(tuple, str)
  207. # close app signal
  208. close_app_signal = pyqtSignal()
  209. # will perform the cleanup operation after a Graceful Exit
  210. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  211. # graphic residues behind
  212. cleanup = pyqtSignal()
  213. def __init__(self, user_defaults=True):
  214. """
  215. Starts the application.
  216. :return: app
  217. :rtype: App
  218. """
  219. super().__init__()
  220. App.log.info("FlatCAM Starting...")
  221. # ############################################################################################################
  222. # ################# Setup the listening thread for another instance launching with args ######################
  223. # ############################################################################################################
  224. if sys.platform == 'win32' or sys.platform == 'linux':
  225. # make sure the thread is stored by using a self. otherwise it's garbage collected
  226. self.listen_th = QtCore.QThread()
  227. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  228. self.new_launch = ArgsThread()
  229. self.new_launch.open_signal[list].connect(self.on_startup_args)
  230. self.new_launch.moveToThread(self.listen_th)
  231. self.new_launch.start.emit()
  232. # ############################################################################################################
  233. # ########################################## OS-specific #####################################################
  234. # ############################################################################################################
  235. portable = False
  236. # Folder for user settings.
  237. if sys.platform == 'win32':
  238. if platform.architecture()[0] == '32bit':
  239. App.log.debug("Win32!")
  240. else:
  241. App.log.debug("Win64!")
  242. # #######################################################################################################
  243. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  244. # #######################################################################################################
  245. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  246. try:
  247. with open(config_file, 'r'):
  248. pass
  249. except FileNotFoundError:
  250. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  251. try:
  252. with open(config_file, 'r') as f:
  253. try:
  254. for line in f:
  255. param = str(line).replace('\n', '').rpartition('=')
  256. if param[0] == 'portable':
  257. try:
  258. portable = eval(param[2])
  259. except NameError:
  260. portable = False
  261. if param[0] == 'headless':
  262. if param[2].lower() == 'true':
  263. self.cmd_line_headless = 1
  264. else:
  265. self.cmd_line_headless = None
  266. except Exception as e:
  267. log.debug('App.__init__() -->%s' % str(e))
  268. return
  269. except FileNotFoundError as e:
  270. log.debug(str(e))
  271. pass
  272. if portable is False:
  273. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  274. else:
  275. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  276. self.os = 'windows'
  277. else: # Linux/Unix/MacOS
  278. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  279. self.os = 'unix'
  280. # ############################################################################################################
  281. # ################################# Setup folders and files ##################################################
  282. # ############################################################################################################
  283. if not os.path.exists(self.data_path):
  284. os.makedirs(self.data_path)
  285. App.log.debug('Created data folder: ' + self.data_path)
  286. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  287. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  288. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  289. if not os.path.exists(self.preprocessorpaths):
  290. os.makedirs(self.preprocessorpaths)
  291. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  292. # create geo_tools_db.FlatDB file if there is none
  293. try:
  294. f = open(self.data_path + '/geo_tools_db.FlatDB')
  295. f.close()
  296. except IOError:
  297. App.log.debug('Creating empty geo_tool_db.FlatDB')
  298. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  299. json.dump({}, f)
  300. f.close()
  301. # create current_defaults.FlatConfig file if there is none
  302. try:
  303. f = open(self.data_path + '/current_defaults.FlatConfig')
  304. f.close()
  305. except IOError:
  306. App.log.debug('Creating empty current_defaults.FlatConfig')
  307. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  308. json.dump({}, f)
  309. f.close()
  310. # the factory defaults are written only once at the first launch of the application after installation
  311. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  312. # create a recent files json file if there is none
  313. try:
  314. f = open(self.data_path + '/recent.json')
  315. f.close()
  316. except IOError:
  317. App.log.debug('Creating empty recent.json')
  318. f = open(self.data_path + '/recent.json', 'w')
  319. json.dump([], f)
  320. f.close()
  321. # create a recent projects json file if there is none
  322. try:
  323. fp = open(self.data_path + '/recent_projects.json')
  324. fp.close()
  325. except IOError:
  326. App.log.debug('Creating empty recent_projects.json')
  327. fp = open(self.data_path + '/recent_projects.json', 'w')
  328. json.dump([], fp)
  329. fp.close()
  330. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  331. # This will fail under cx_freeze ...
  332. self.app_home = os.path.dirname(os.path.realpath(__file__))
  333. log.debug("Application path is " + self.app_home)
  334. log.debug("Started in " + os.getcwd())
  335. # cx_freeze workaround
  336. if os.path.isfile(self.app_home):
  337. self.app_home = os.path.dirname(self.app_home)
  338. os.chdir(self.app_home)
  339. # ############################################################################################################
  340. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  341. # ############################################################################################################
  342. self.defaults = FlatCAMDefaults()
  343. self.defaults["root_folder_path"] = self.app_home
  344. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  345. if user_defaults:
  346. self.defaults.load(filename=current_defaults_path)
  347. if self.defaults['units'] == 'MM':
  348. self.decimals = int(self.defaults['decimals_metric'])
  349. else:
  350. self.decimals = int(self.defaults['decimals_inch'])
  351. if self.defaults["global_gray_icons"] is False:
  352. self.resource_location = 'assets/resources'
  353. else:
  354. self.resource_location = 'assets/resources/dark_resources'
  355. self.current_units = self.defaults['units']
  356. # ###########################################################################################################
  357. # #################################### SETUP OBJECT CLASSES #################################################
  358. # ###########################################################################################################
  359. self.setup_obj_classes()
  360. # ###########################################################################################################
  361. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  362. # ###########################################################################################################
  363. self.pool = Pool()
  364. # ###########################################################################################################
  365. # ###################################### Clear GUI Settings - once at first start ###########################
  366. # ###########################################################################################################
  367. if self.defaults["first_run"] is True:
  368. # on first run clear the previous QSettings, therefore clearing the GUI settings
  369. qsettings = QSettings("Open Source", "FlatCAM")
  370. for key in qsettings.allKeys():
  371. qsettings.remove(key)
  372. # This will write the setting to the platform specific storage.
  373. del qsettings
  374. # ###########################################################################################################
  375. # ###################################### Setting the Splash Screen ##########################################
  376. # ###########################################################################################################
  377. splash_settings = QSettings("Open Source", "FlatCAM")
  378. if splash_settings.contains("splash_screen"):
  379. show_splash = splash_settings.value("splash_screen")
  380. else:
  381. splash_settings.setValue('splash_screen', 1)
  382. # This will write the setting to the platform specific storage.
  383. del splash_settings
  384. show_splash = 1
  385. if show_splash and self.cmd_line_headless != 1:
  386. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  387. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  388. # self.splash.setMask(splash_pix.mask())
  389. # move splashscreen to the current monitor
  390. desktop = QtWidgets.QApplication.desktop()
  391. screen = desktop.screenNumber(QtGui.QCursor.pos())
  392. current_screen_center = desktop.availableGeometry(screen).center()
  393. self.splash.move(current_screen_center - self.splash.rect().center())
  394. self.splash.show()
  395. self.splash.showMessage(_("FlatCAM is initializing ..."),
  396. alignment=Qt.AlignBottom | Qt.AlignLeft,
  397. color=QtGui.QColor("gray"))
  398. else:
  399. show_splash = 0
  400. # ###########################################################################################################
  401. # ######################################### Initialize GUI ##################################################
  402. # ###########################################################################################################
  403. # FlatCAM colors used in plotting
  404. self.FC_light_green = '#BBF268BF'
  405. self.FC_dark_green = '#006E20BF'
  406. self.FC_light_blue = '#a5a5ffbf'
  407. self.FC_dark_blue = '#0000ffbf'
  408. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  409. if theme_settings.contains("theme"):
  410. theme = theme_settings.value('theme', type=str)
  411. else:
  412. theme = 'white'
  413. if self.defaults["global_cursor_color_enabled"]:
  414. self.cursor_color_3D = self.defaults["global_cursor_color"]
  415. else:
  416. if theme == 'white':
  417. self.cursor_color_3D = 'black'
  418. else:
  419. self.cursor_color_3D = 'gray'
  420. # update the defaults dict with the setting in QSetting
  421. self.defaults['global_theme'] = theme
  422. self.ui = MainGUI(self)
  423. # set FlatCAM units in the Status bar
  424. self.set_screen_units(self.defaults['units'])
  425. # ###########################################################################################################
  426. # ########################################### AUTOSAVE SETUP ################################################
  427. # ###########################################################################################################
  428. self.block_autosave = False
  429. self.autosave_timer = QtCore.QTimer(self)
  430. self.save_project_auto_update()
  431. self.autosave_timer.timeout.connect(self.save_project_auto)
  432. # ###########################################################################################################
  433. # #################################### LOAD PREPROCESSORS ###################################################
  434. # ###########################################################################################################
  435. # ----------------------------------------- WARNING --------------------------------------------------------
  436. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  437. # That's because the number of preprocessors can vary and here the comboboxes are populated
  438. # -----------------------------------------------------------------------------------------------------------
  439. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  440. # the preprocessor file
  441. self.preprocessors = load_preprocessors(self)
  442. # make sure that always the 'default' preprocessor is the first item in the dictionary
  443. if 'default' in self.preprocessors.keys():
  444. new_ppp_dict = {}
  445. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  446. default_pp = self.preprocessors.pop('default')
  447. new_ppp_dict['default'] = default_pp
  448. # then add the rest of the keys
  449. for name, val_class in self.preprocessors.items():
  450. new_ppp_dict[name] = val_class
  451. # and now put back the ordered dict with 'default' key first
  452. self.preprocessors = new_ppp_dict
  453. for name in list(self.preprocessors.keys()):
  454. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  455. if name.partition('_')[0] == 'Paste':
  456. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  457. continue
  458. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  459. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  460. if name == 'hpgl':
  461. continue
  462. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  463. # ###########################################################################################################
  464. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  465. # ###########################################################################################################
  466. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  467. inform=self.inform)
  468. self.preferencesUiManager.defaults_write_form()
  469. # When the self.defaults dictionary changes will update the Preferences GUI forms
  470. self.defaults.set_change_callback(self.on_defaults_dict_change)
  471. # ###########################################################################################################
  472. # ##################################### FIRST RUN SECTION ###################################################
  473. # ################################ It's done only once after install #####################################
  474. # ###########################################################################################################
  475. if self.defaults["first_run"] is True:
  476. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  477. initial_lay = 'minimal'
  478. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  479. # Set the combobox in Preferences to the current layout
  480. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  481. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  482. # after the first run, this object should be False
  483. self.defaults["first_run"] = False
  484. self.preferencesUiManager.save_defaults(silent=True)
  485. # ###########################################################################################################
  486. # ############################################ Data #########################################################
  487. # ###########################################################################################################
  488. self.recent = []
  489. self.recent_projects = []
  490. self.clipboard = QtWidgets.QApplication.clipboard()
  491. self.project_filename = None
  492. self.toggle_units_ignore = False
  493. self.main_thread = QtWidgets.QApplication.instance().thread()
  494. # ###########################################################################################################
  495. # ########################################## LOAD LANGUAGES ################################################
  496. # ###########################################################################################################
  497. self.languages = fcTranslate.load_languages()
  498. for name in sorted(self.languages.values()):
  499. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  500. # ###########################################################################################################
  501. # ####################################### APPLY APP LANGUAGE ################################################
  502. # ###########################################################################################################
  503. ret_val = fcTranslate.apply_language('strings')
  504. if ret_val == "no language":
  505. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  506. log.debug("Could not find the Language files. The App strings are missing.")
  507. else:
  508. # make the current language the current selection on the language combobox
  509. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  510. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  511. # ###########################################################################################################
  512. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  513. # ###########################################################################################################
  514. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  515. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  516. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  517. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  518. self.defaults.propagate_defaults()
  519. # ###########################################################################################################
  520. # ######################################## UPDATE THE OPTIONS ###############################################
  521. # ###########################################################################################################
  522. self.options = LoudDict()
  523. # -----------------------------------------------------------------------------------------------------------
  524. # Update the self.options from the self.defaults
  525. # The self.defaults holds the application defaults while the self.options holds the object defaults
  526. # -----------------------------------------------------------------------------------------------------------
  527. # Copy app defaults to project options
  528. for def_key, def_val in self.defaults.items():
  529. self.options[def_key] = deepcopy(def_val)
  530. self.preferencesUiManager.show_preferences_gui()
  531. # ### End of Data ####
  532. # ###########################################################################################################
  533. # #################################### SETUP OBJECT COLLECTION ##############################################
  534. # ###########################################################################################################
  535. self.collection = ObjectCollection(app=self)
  536. self.ui.project_tab_layout.addWidget(self.collection.view)
  537. self.app_obj = AppObject(app=self)
  538. # ### Adjust tabs width ## ##
  539. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  540. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  541. self.collection.view.setMinimumWidth(290)
  542. self.log.debug("Finished creating Object Collection.")
  543. # ###########################################################################################################
  544. # ######################################## SETUP Plot Area ##################################################
  545. # ###########################################################################################################
  546. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  547. if self.defaults["global_graphic_engine"] == '3D':
  548. self.is_legacy = False
  549. else:
  550. self.is_legacy = True
  551. # Event signals disconnect id holders
  552. self.mp = None
  553. self.mm = None
  554. self.mr = None
  555. self.mdc = None
  556. self.mp_zc = None
  557. self.kp = None
  558. # Matplotlib axis
  559. self.axes = None
  560. if show_splash:
  561. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  562. "Canvas initialization started."),
  563. alignment=Qt.AlignBottom | Qt.AlignLeft,
  564. color=QtGui.QColor("gray"))
  565. start_plot_time = time.time() # debug
  566. self.plotcanvas = None
  567. self.app_cursor = None
  568. self.hover_shapes = None
  569. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  570. # setup the PlotCanvas
  571. self.on_plotcanvas_setup()
  572. end_plot_time = time.time()
  573. self.used_time = end_plot_time - start_plot_time
  574. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  575. if show_splash:
  576. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  577. "Canvas initialization started.\n"
  578. "Canvas initialization finished in"), '%.2f' % self.used_time),
  579. alignment=Qt.AlignBottom | Qt.AlignLeft,
  580. color=QtGui.QColor("gray"))
  581. self.ui.splitter.setStretchFactor(1, 2)
  582. # ###########################################################################################################
  583. # ############################################### SYS TRAY ##################################################
  584. # ###########################################################################################################
  585. if self.defaults["global_systray_icon"]:
  586. self.parent_w = QtWidgets.QWidget()
  587. if self.cmd_line_headless == 1:
  588. self.trayIcon = FlatCAMSystemTray(app=self,
  589. icon=QtGui.QIcon(self.resource_location +
  590. '/flatcam_icon32_green.png'),
  591. headless=True,
  592. parent=self.parent_w)
  593. else:
  594. self.trayIcon = FlatCAMSystemTray(app=self,
  595. icon=QtGui.QIcon(self.resource_location +
  596. '/flatcam_icon32_green.png'),
  597. parent=self.parent_w)
  598. # ###########################################################################################################
  599. # ############################################### Worker SETUP ##############################################
  600. # ###########################################################################################################
  601. if self.defaults["global_worker_number"]:
  602. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  603. else:
  604. self.workers = WorkerStack(workers_number=2)
  605. self.worker_task.connect(self.workers.add_task)
  606. self.log.debug("Finished creating Workers crew.")
  607. # ###########################################################################################################
  608. # ############################################# Activity Monitor ###########################################
  609. # ###########################################################################################################
  610. # self.activity_view = FlatCAMActivityView(app=self)
  611. # self.ui.infobar.addWidget(self.activity_view)
  612. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  613. # ###########################################################################################################
  614. # ############################################# Signal handling #############################################
  615. # ###########################################################################################################
  616. # ########################################## Custom signals ################################################
  617. # signal for displaying messages in status bar
  618. self.inform[str].connect(self.info)
  619. self.inform[str, bool].connect(self.info)
  620. # signal for displaying messages in the shell
  621. self.inform_shell.connect(self.info_shell)
  622. # signal to be called when the app is quiting
  623. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  624. self.message.connect(lambda: message_dialog(parent=self.ui))
  625. # self.progress.connect(self.set_progress_bar)
  626. # signals emitted when file state change
  627. self.file_opened.connect(self.register_recent)
  628. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  629. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  630. # ########################################## Standard signals ###############################################
  631. # ### Menu
  632. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  633. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  634. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  635. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  636. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  637. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  638. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  639. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  640. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  641. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  642. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  643. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  644. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  645. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  646. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  647. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  648. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  649. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  650. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  651. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  652. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  653. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  654. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  655. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  656. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  657. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  658. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  659. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  660. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  661. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  662. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  663. self.ui.menufile_exit.triggered.connect(self.final_save)
  664. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  665. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  666. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  667. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  668. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  669. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  670. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  671. self.ui.menueditdelete.triggered.connect(self.on_delete)
  672. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  673. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  674. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  675. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  676. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  677. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  678. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  679. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  680. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  681. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  682. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  683. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  684. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  685. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  686. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  687. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  688. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  689. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  690. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  691. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  692. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  693. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  694. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  695. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  696. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  697. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  698. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  699. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  700. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  701. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  702. self.ui.menuview_replot.triggered.connect(self.plot_all)
  703. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  704. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  705. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  706. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  707. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  708. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  709. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  710. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  711. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  712. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  713. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  714. self.ui.menuhelp_about.triggered.connect(self.on_about)
  715. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  716. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  717. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  718. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  719. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  720. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  721. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  722. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  723. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  724. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  725. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  726. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  727. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  728. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  729. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  730. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  731. # ToolBar signals
  732. self.connect_toolbar_signals(ui=self.ui)
  733. # Context Menu
  734. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  735. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  736. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  737. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  738. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  739. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  740. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  741. self.ui.clearplot.triggered.connect(self.clear_plots)
  742. self.ui.replot.triggered.connect(self.plot_all)
  743. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  744. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  745. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  746. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  747. self.ui.popmenu_move.triggered.connect(self.obj_move)
  748. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  749. # Project Context Menu -> Color Setting
  750. for act in self.ui.menuprojectcolor.actions():
  751. act.triggered.connect(self.on_set_color_action_triggered)
  752. # ###########################################################################################################
  753. # #################################### GUI PREFERENCES SIGNALS ##############################################
  754. # ###########################################################################################################
  755. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  756. lambda: self.on_toggle_units(no_pref=False))
  757. # ##################################### Workspace Setting Signals ###########################################
  758. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  759. self.on_workspace_modified)
  760. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  761. self.on_workspace_modified
  762. )
  763. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  764. # ###########################################################################################################
  765. # ######################################## GUI SETTINGS SIGNALS #############################################
  766. # ###########################################################################################################
  767. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  768. # ######################################## Tools related signals ############################################
  769. # portability changed signal
  770. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  771. # Object list
  772. self.object_status_changed.connect(self.collection.on_collection_updated)
  773. # when there are arguments at application startup this get launched
  774. self.args_at_startup[list].connect(self.on_startup_args)
  775. # ###########################################################################################################
  776. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  777. # ###########################################################################################################
  778. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  779. lambda: self.restore_extensions(ext_type='excellon'))
  780. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  781. lambda: self.restore_extensions(ext_type='gcode'))
  782. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  783. lambda: self.restore_extensions(ext_type='gerber'))
  784. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  785. lambda: self.delete_all_extensions(ext_type='excellon'))
  786. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  787. lambda: self.delete_all_extensions(ext_type='gcode'))
  788. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  789. lambda: self.delete_all_extensions(ext_type='gerber'))
  790. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  791. lambda: self.add_extension(ext_type='excellon'))
  792. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  793. lambda: self.add_extension(ext_type='gcode'))
  794. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  795. lambda: self.add_extension(ext_type='gerber'))
  796. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  797. lambda: self.del_extension(ext_type='excellon'))
  798. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  799. lambda: self.del_extension(ext_type='gcode'))
  800. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  801. lambda: self.del_extension(ext_type='gerber'))
  802. # connect the 'Apply' buttons from the Preferences/File Associations
  803. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  804. lambda: self.on_register_files(obj_type='excellon'))
  805. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  806. lambda: self.on_register_files(obj_type='gcode'))
  807. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  808. lambda: self.on_register_files(obj_type='gerber'))
  809. # ###########################################################################################################
  810. # ########################################### KEYWORDS SIGNALS ##############################################
  811. # ###########################################################################################################
  812. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  813. lambda: self.restore_extensions(ext_type='keyword'))
  814. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  815. lambda: self.delete_all_extensions(ext_type='keyword'))
  816. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  817. lambda: self.add_extension(ext_type='keyword'))
  818. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  819. lambda: self.del_extension(ext_type='keyword'))
  820. # ###########################################################################################################
  821. # ########################################### GUI SIGNALS ###################################################
  822. # ###########################################################################################################
  823. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  824. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  825. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  826. # ###########################################################################################################
  827. # ####################################### VARIOUS SIGNALS ###################################################
  828. # ###########################################################################################################
  829. # connect the abort_all_tasks related slots to the related signals
  830. self.proc_container.idle_flag.connect(self.app_is_idle)
  831. # signal emitted when a tab is closed in the Plot Area
  832. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  833. # signal to close the application
  834. self.close_app_signal.connect(self.kill_app)
  835. # ################################# FINISHED CONNECTING SIGNALS #############################################
  836. # ###########################################################################################################
  837. # ###########################################################################################################
  838. # ###########################################################################################################
  839. self.log.debug("Finished connecting Signals.")
  840. # ###########################################################################################################
  841. # ########################################## Other setups ###################################################
  842. # ###########################################################################################################
  843. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  844. # depending on from where those tools are called different actions can be done
  845. self.call_source = 'app'
  846. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  847. self.tool_tab_locked = False
  848. # decide if to show or hide the Notebook side of the screen at startup
  849. if self.defaults["global_project_at_startup"] is True:
  850. self.ui.splitter.setSizes([1, 1])
  851. else:
  852. self.ui.splitter.setSizes([0, 1])
  853. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  854. self.setup_component_editor()
  855. # ###########################################################################################################
  856. # ####################################### Auto-complete KEYWORDS ############################################
  857. # ###########################################################################################################
  858. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  859. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  860. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  861. 'export_exc',
  862. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  863. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  864. 'interiors', 'isolate', 'join_excellon',
  865. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  866. 'mirror', 'ncc',
  867. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  868. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  869. 'options', 'origin',
  870. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  871. 'save', 'save_project',
  872. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  873. 'skew', 'subtract_poly', 'subtract_rectangle',
  874. 'version', 'write_gcode'
  875. ]
  876. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  877. 'Paste_1',
  878. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  879. 'Toolchange_manual', 'True', 'Users',
  880. 'all', 'auto', 'axis',
  881. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  882. 'contour', 'default',
  883. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  884. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  885. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  886. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  887. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  888. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  889. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  890. 'spacing_columns',
  891. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  892. 'toolchange_xy', 'toolchangez', 'travelz',
  893. 'tooldia', 'use_threads', 'value',
  894. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  895. ]
  896. self.tcl_keywords = [
  897. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  898. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  899. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  900. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  901. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  902. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  903. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  904. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  905. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  906. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  907. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  908. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  909. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  910. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  911. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  912. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  913. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  914. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  915. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  916. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  917. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  918. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  919. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  920. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  921. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  922. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  923. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  924. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  925. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  926. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  927. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  928. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  929. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  930. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  931. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  932. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  933. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  934. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  935. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  936. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  937. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  938. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  939. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  940. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  941. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  942. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  943. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  944. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  945. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  946. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  947. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  948. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  949. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  950. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  951. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  952. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  953. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  954. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  955. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  956. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  957. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  958. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  959. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  960. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  961. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  962. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  963. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  964. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  965. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  966. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  967. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  968. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  969. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  970. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  971. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  972. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  973. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  974. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  975. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  976. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  977. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  978. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  979. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  980. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  981. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  982. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  983. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  984. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  985. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  986. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  987. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  988. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  989. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  990. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  991. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  992. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  993. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  994. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  995. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  996. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  997. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  998. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  999. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1000. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1001. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1002. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1003. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1004. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1005. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1006. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1007. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1008. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1009. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1010. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1011. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1012. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1013. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1014. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1015. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1016. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1017. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1018. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1019. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1020. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1021. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1022. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1023. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1024. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1025. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1026. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1027. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1028. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1029. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1030. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1031. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1032. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1033. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1034. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1035. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1036. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1037. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1038. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1039. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1040. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1041. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1042. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1043. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1044. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1045. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1046. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1047. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1048. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1049. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1050. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1051. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1052. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1053. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1054. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1055. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1056. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1057. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1058. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1059. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1060. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1061. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1062. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1063. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1064. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1065. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1066. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1067. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1068. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1069. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1070. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1071. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1072. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1073. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1074. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1075. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1076. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1077. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1078. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1079. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1080. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1081. ]
  1082. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1083. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1084. # ###########################################################################################################
  1085. # ########################################## Tools and Plugins ##############################################
  1086. # ###########################################################################################################
  1087. self.shell = None
  1088. self.dblsidedtool = None
  1089. self.distance_tool = None
  1090. self.distance_min_tool = None
  1091. self.panelize_tool = None
  1092. self.film_tool = None
  1093. self.paste_tool = None
  1094. self.calculator_tool = None
  1095. self.rules_tool = None
  1096. self.sub_tool = None
  1097. self.move_tool = None
  1098. self.cutout_tool = None
  1099. self.ncclear_tool = None
  1100. self.paint_tool = None
  1101. self.isolation_tool = None
  1102. self.drilling_tool = None
  1103. self.optimal_tool = None
  1104. self.transform_tool = None
  1105. self.properties_tool = None
  1106. self.pdf_tool = None
  1107. self.image_tool = None
  1108. self.pcb_wizard_tool = None
  1109. self.cal_exc_tool = None
  1110. self.qrcode_tool = None
  1111. self.copper_thieving_tool = None
  1112. self.fiducial_tool = None
  1113. self.edrills_tool = None
  1114. self.align_objects_tool = None
  1115. self.punch_tool = None
  1116. self.invert_tool = None
  1117. self.corners_tool = None
  1118. self.etch_tool = None
  1119. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1120. try:
  1121. self.install_tools()
  1122. except AttributeError as e:
  1123. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1124. # ###########################################################################################################
  1125. # ############################################ SETUP RECENT ITEMS ###########################################
  1126. # ###########################################################################################################
  1127. self.setup_recent_items()
  1128. # ###########################################################################################################
  1129. # ######################################### BookMarks Manager ###############################################
  1130. # ###########################################################################################################
  1131. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1132. self.install_bookmarks()
  1133. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1134. # ###########################################################################################################
  1135. # ########################################### Tools Database ################################################
  1136. # ###########################################################################################################
  1137. self.tools_db_tab = None
  1138. # ### System Font Parsing ###
  1139. # self.f_parse = ParseFont(self)
  1140. # self.parse_system_fonts()
  1141. # ###########################################################################################################
  1142. # ############################################## Shell SETUP ################################################
  1143. # ###########################################################################################################
  1144. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1145. if self.defaults["global_shell_at_startup"]:
  1146. self.ui.shell_dock.show()
  1147. else:
  1148. self.ui.shell_dock.hide()
  1149. # ###########################################################################################################
  1150. # ######################################### Check for updates ###############################################
  1151. # ###########################################################################################################
  1152. # Separate thread (Not worker)
  1153. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1154. if (self.beta is False or self.beta is None) and \
  1155. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1156. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1157. # self.thr2 = QtCore.QThread()
  1158. self.worker_task.emit({'fcn': self.version_check,
  1159. 'params': []})
  1160. # self.thr2.start(QtCore.QThread.LowPriority)
  1161. # ###########################################################################################################
  1162. # ##################################### Register files with FlatCAM; #######################################
  1163. # ################################### It works only for Windows for now ####################################
  1164. # ###########################################################################################################
  1165. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1166. self.on_register_files()
  1167. # ###########################################################################################################
  1168. # ######################################## Variables for global usage #######################################
  1169. # ###########################################################################################################
  1170. # hold the App units
  1171. self.units = 'MM'
  1172. # coordinates for relative position display
  1173. self.rel_point1 = (0, 0)
  1174. self.rel_point2 = (0, 0)
  1175. # variable to store coordinates
  1176. self.pos = (0, 0)
  1177. self.pos_canvas = (0, 0)
  1178. self.pos_jump = (0, 0)
  1179. # variable to store mouse coordinates
  1180. self.mouse = [0, 0]
  1181. # variable to store the delta positions on cavnas
  1182. self.dx = 0
  1183. self.dy = 0
  1184. # decide if we have a double click or single click
  1185. self.doubleclick = False
  1186. # store here the is_dragging value
  1187. self.event_is_dragging = False
  1188. # variable to store if a command is active (then the var is not None) and which one it is
  1189. self.command_active = None
  1190. # variable to store the status of moving selection action
  1191. # None value means that it's not an selection action
  1192. # True value = a selection from left to right
  1193. # False value = a selection from right to left
  1194. self.selection_type = None
  1195. # List to store the objects that are currently loaded in FlatCAM
  1196. # This list is updated on each object creation or object delete
  1197. self.all_objects_list = []
  1198. self.objects_under_the_click_list = []
  1199. # List to store the objects that are selected
  1200. self.sel_objects_list = []
  1201. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1202. self.key_modifiers = None
  1203. # Variable to store the status of the code editor
  1204. self.toggle_codeeditor = False
  1205. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1206. self.click_noproject = False
  1207. self.cursor = None
  1208. # Variable to store the GCODE that was edited
  1209. self.gcode_edited = ""
  1210. self.text_editor_tab = None
  1211. # reference for the self.ui.code_editor
  1212. self.reference_code_editor = None
  1213. self.script_code = ''
  1214. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1215. self.tools_db_changed_flag = False
  1216. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1217. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1218. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1219. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1220. 'tsm']
  1221. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1222. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1223. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1224. 'sbp', 'tap', 'xpi']
  1225. self.svg_list = ['svg']
  1226. self.dxf_list = ['dxf']
  1227. self.pdf_list = ['pdf']
  1228. self.prj_list = ['flatprj']
  1229. self.conf_list = ['flatconfig']
  1230. # last used filters
  1231. self.last_op_gerber_filter = None
  1232. self.last_op_excellon_filter = None
  1233. self.last_op_gcode_filter = None
  1234. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1235. # flag for polygons not cleared
  1236. self.poly_not_cleared = False
  1237. # VisPy visuals
  1238. self.isHovering = False
  1239. self.notHovering = True
  1240. # Window geometry
  1241. self.x_pos = None
  1242. self.y_pos = None
  1243. self.width = None
  1244. self.height = None
  1245. # when True, the app has to return from any thread
  1246. self.abort_flag = False
  1247. # set the value used in the Windows Title
  1248. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1249. # this holds a widget that is installed in the Plot Area when View Source option is used
  1250. self.source_editor_tab = None
  1251. self.pagesize = {}
  1252. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1253. # VisPy visuals
  1254. if self.is_legacy is False:
  1255. try:
  1256. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1257. except AttributeError:
  1258. self.tool_shapes = None
  1259. else:
  1260. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1261. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1262. # used in the delayed shutdown self.start_delayed_quit() method
  1263. self.save_timer = None
  1264. # ###########################################################################################################
  1265. # ################################## ADDING FlatCAM EDITORS section #########################################
  1266. # ###########################################################################################################
  1267. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1268. # at the first launch of the App , the editors will not be functional.
  1269. try:
  1270. self.geo_editor = AppGeoEditor(self)
  1271. except Exception as es:
  1272. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1273. try:
  1274. self.exc_editor = AppExcEditor(self)
  1275. except Exception as es:
  1276. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1277. try:
  1278. self.grb_editor = AppGerberEditor(self)
  1279. except Exception as es:
  1280. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1281. self.log.debug("Finished adding FlatCAM Editor's.")
  1282. self.set_ui_title(name=_("New Project - Not saved"))
  1283. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1284. current_platform = platform.architecture()[0]
  1285. if current_platform != '64bit':
  1286. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1287. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1288. # ###########################################################################################################
  1289. # ########################################### EXCLUSION AREAS ###############################################
  1290. # ###########################################################################################################
  1291. self.exc_areas = ExclusionAreas(app=self)
  1292. # ###########################################################################################################
  1293. # ##################################### Finished the CONSTRUCTOR ############################################
  1294. # ###########################################################################################################
  1295. App.log.debug("END of constructor. Releasing control.")
  1296. # ###########################################################################################################
  1297. # ########################################## SHOW GUI #######################################################
  1298. # ###########################################################################################################
  1299. # if the app is not started as headless, show it
  1300. if self.cmd_line_headless != 1:
  1301. if show_splash:
  1302. # finish the splash
  1303. self.splash.finish(self.ui)
  1304. mgui_settings = QSettings("Open Source", "FlatCAM")
  1305. if mgui_settings.contains("maximized_gui"):
  1306. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1307. if maximized_ui is True:
  1308. self.ui.showMaximized()
  1309. else:
  1310. self.ui.show()
  1311. else:
  1312. self.ui.show()
  1313. if self.defaults["global_systray_icon"]:
  1314. self.trayIcon.show()
  1315. else:
  1316. log.warning("******************* RUNNING HEADLESS *******************")
  1317. # ###########################################################################################################
  1318. # ######################################## START-UP ARGUMENTS ###############################################
  1319. # ###########################################################################################################
  1320. # test if the program was started with a script as parameter
  1321. if self.cmd_line_shellvar:
  1322. try:
  1323. cnt = 0
  1324. command_tcl = 0
  1325. for i in self.cmd_line_shellvar.split(','):
  1326. if i is not None:
  1327. # noinspection PyBroadException
  1328. try:
  1329. command_tcl = eval(i)
  1330. except Exception:
  1331. command_tcl = i
  1332. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1333. cnt += 1
  1334. # if there are Windows paths then replace the path separator with a Unix like one
  1335. if sys.platform == 'win32':
  1336. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1337. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1338. except Exception as ext:
  1339. print("ERROR: ", ext)
  1340. sys.exit(2)
  1341. if self.cmd_line_shellfile:
  1342. if self.cmd_line_headless != 1:
  1343. if self.ui.shell_dock.isHidden():
  1344. self.ui.shell_dock.show()
  1345. try:
  1346. with open(self.cmd_line_shellfile, "r") as myfile:
  1347. # if show_splash:
  1348. # self.splash.showMessage('%s: %ssec\n%s' % (
  1349. # _("Canvas initialization started.\n"
  1350. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1351. # _("Executing Tcl Script ...")),
  1352. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1353. # color=QtGui.QColor("gray"))
  1354. cmd_line_shellfile_text = myfile.read()
  1355. if self.cmd_line_headless != 1:
  1356. self.shell.exec_command(cmd_line_shellfile_text)
  1357. else:
  1358. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1359. except Exception as ext:
  1360. print("ERROR: ", ext)
  1361. sys.exit(2)
  1362. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1363. # the path/file_name must be enclosed in quotes if it contain spaces
  1364. if App.args:
  1365. self.args_at_startup.emit(App.args)
  1366. if self.defaults.old_defaults_found is True:
  1367. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1368. "Please reboot the application to update."))
  1369. self.defaults.old_defaults_found = False
  1370. # ######################################### INIT FINISHED #######################################################
  1371. # #################################################################################################################
  1372. # #################################################################################################################
  1373. # #################################################################################################################
  1374. # #################################################################################################################
  1375. # #################################################################################################################
  1376. @staticmethod
  1377. def copy_and_overwrite(from_path, to_path):
  1378. """
  1379. From here:
  1380. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1381. :param from_path: source path
  1382. :param to_path: destination path
  1383. :return: None
  1384. """
  1385. if os.path.exists(to_path):
  1386. shutil.rmtree(to_path)
  1387. try:
  1388. shutil.copytree(from_path, to_path)
  1389. except FileNotFoundError:
  1390. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1391. shutil.copytree(from_new_path, to_path)
  1392. def on_startup_args(self, args, silent=False):
  1393. """
  1394. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1395. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1396. :param args: a list containing the application args at startup
  1397. :return: None
  1398. """
  1399. if args is not None:
  1400. args_to_process = args
  1401. else:
  1402. args_to_process = App.args
  1403. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1404. for argument in args_to_process:
  1405. if '.FlatPrj'.lower() in argument.lower():
  1406. try:
  1407. project_name = str(argument)
  1408. if project_name == "":
  1409. if silent is False:
  1410. self.inform.emit(_("Cancelled."))
  1411. else:
  1412. # self.open_project(project_name)
  1413. run_from_arg = True
  1414. # self.worker_task.emit({'fcn': self.open_project,
  1415. # 'params': [project_name, run_from_arg]})
  1416. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1417. except Exception as e:
  1418. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1419. elif '.FlatConfig'.lower() in argument.lower():
  1420. try:
  1421. file_name = str(argument)
  1422. if file_name == "":
  1423. if silent is False:
  1424. self.inform.emit(_("Open Config file failed."))
  1425. else:
  1426. run_from_arg = True
  1427. # self.worker_task.emit({'fcn': self.open_config_file,
  1428. # 'params': [file_name, run_from_arg]})
  1429. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1430. except Exception as e:
  1431. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1432. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1433. try:
  1434. file_name = str(argument)
  1435. if file_name == "":
  1436. if silent is False:
  1437. self.inform.emit(_("Open Script file failed."))
  1438. else:
  1439. if silent is False:
  1440. self.on_fileopenscript(name=file_name)
  1441. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1442. self.on_filerunscript(name=file_name)
  1443. except Exception as e:
  1444. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1445. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1446. log.debug("App.on_startup_args() --> Quit event.")
  1447. sys.exit()
  1448. elif 'save'.lower() in argument.lower():
  1449. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1450. self.preferencesUiManager.save_defaults()
  1451. else:
  1452. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1453. proc_arg = argument.lower()
  1454. for ext in exc_list:
  1455. proc_ext = ext.replace(' ', '')
  1456. proc_ext = '.%s' % proc_ext
  1457. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1458. file_name = str(argument)
  1459. if file_name == "":
  1460. if silent is False:
  1461. self.inform.emit(_("Open Excellon file failed."))
  1462. else:
  1463. self.on_fileopenexcellon(name=file_name, signal=None)
  1464. return
  1465. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1466. for ext in gco_list:
  1467. proc_ext = ext.replace(' ', '')
  1468. proc_ext = '.%s' % proc_ext
  1469. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1470. file_name = str(argument)
  1471. if file_name == "":
  1472. if silent is False:
  1473. self.inform.emit(_("Open GCode file failed."))
  1474. else:
  1475. self.on_fileopengcode(name=file_name, signal=None)
  1476. return
  1477. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1478. for ext in grb_list:
  1479. proc_ext = ext.replace(' ', '')
  1480. proc_ext = '.%s' % proc_ext
  1481. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1482. file_name = str(argument)
  1483. if file_name == "":
  1484. if silent is False:
  1485. self.inform.emit(_("Open Gerber file failed."))
  1486. else:
  1487. self.on_fileopengerber(name=file_name, signal=None)
  1488. return
  1489. # if it reached here without already returning then the app was registered with a file that it does not
  1490. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1491. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1492. # for arg in args_to_process:
  1493. # if 'FlatCAM.exe' in arg:
  1494. # continue
  1495. # else:
  1496. # sys.exit(2)
  1497. def set_ui_title(self, name):
  1498. """
  1499. Sets the title of the main window.
  1500. :param name: String that store the project path and project name
  1501. :return: None
  1502. """
  1503. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1504. (self.version,
  1505. ('BETA' if self.beta else ''),
  1506. platform.architecture()[0],
  1507. self.engine,
  1508. name)
  1509. )
  1510. def on_app_restart(self):
  1511. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1512. # be left in the SySTray
  1513. try:
  1514. self.trayIcon.hide()
  1515. except Exception:
  1516. pass
  1517. fcTranslate.restart_program(app=self)
  1518. def clear_pool(self):
  1519. """
  1520. Clear the multiprocessing pool and calls garbage collector.
  1521. :return: None
  1522. """
  1523. self.pool.close()
  1524. self.pool = Pool()
  1525. self.pool_recreated.emit(self.pool)
  1526. gc.collect()
  1527. def install_tools(self):
  1528. """
  1529. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1530. Instantiation of the Tools classes.
  1531. The order that the tools are installed is important as they can depend on each other install position.
  1532. :return: None
  1533. """
  1534. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1535. self.shell = FCShell(app=self, version=self.version)
  1536. self.distance_tool = Distance(self)
  1537. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1538. before=self.ui.menueditorigin,
  1539. separator=False)
  1540. self.distance_min_tool = DistanceMin(self)
  1541. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1542. pos=self.ui.menuedit,
  1543. before=self.ui.menueditorigin,
  1544. separator=True)
  1545. self.dblsidedtool = DblSidedTool(self)
  1546. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1547. self.cal_exc_tool = ToolCalibration(self)
  1548. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1549. before=self.dblsidedtool.menuAction,
  1550. separator=False)
  1551. self.align_objects_tool = AlignObjects(self)
  1552. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1553. self.edrills_tool = ToolExtractDrills(self)
  1554. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1555. self.panelize_tool = Panelize(self)
  1556. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1557. self.film_tool = Film(self)
  1558. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1559. self.paste_tool = SolderPaste(self)
  1560. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1561. self.calculator_tool = ToolCalculator(self)
  1562. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1563. self.sub_tool = ToolSub(self)
  1564. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1565. pos=self.ui.menutool, separator=True)
  1566. self.rules_tool = RulesCheck(self)
  1567. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1568. pos=self.ui.menutool, separator=False)
  1569. self.optimal_tool = ToolOptimal(self)
  1570. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1571. pos=self.ui.menutool, separator=True)
  1572. self.move_tool = ToolMove(self)
  1573. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1574. before=self.ui.menueditorigin, separator=True)
  1575. self.cutout_tool = CutOut(self)
  1576. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1577. before=self.sub_tool.menuAction)
  1578. self.ncclear_tool = NonCopperClear(self)
  1579. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1580. before=self.sub_tool.menuAction, separator=True)
  1581. self.paint_tool = ToolPaint(self)
  1582. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1583. before=self.sub_tool.menuAction, separator=True)
  1584. self.isolation_tool = ToolIsolation(self)
  1585. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1586. before=self.sub_tool.menuAction, separator=True)
  1587. self.drilling_tool = ToolDrilling(self)
  1588. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1589. before=self.sub_tool.menuAction, separator=True)
  1590. self.copper_thieving_tool = ToolCopperThieving(self)
  1591. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1592. pos=self.ui.menutool)
  1593. self.fiducial_tool = ToolFiducials(self)
  1594. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1595. pos=self.ui.menutool)
  1596. self.qrcode_tool = QRCode(self)
  1597. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1598. pos=self.ui.menutool)
  1599. self.punch_tool = ToolPunchGerber(self)
  1600. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1601. self.invert_tool = ToolInvertGerber(self)
  1602. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1603. self.corners_tool = ToolCorners(self)
  1604. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1605. self.etch_tool = ToolEtchCompensation(self)
  1606. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1607. self.transform_tool = ToolTransform(self)
  1608. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1609. pos=self.ui.menuoptions, separator=True)
  1610. self.properties_tool = Properties(self)
  1611. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1612. pos=self.ui.menuoptions)
  1613. self.pdf_tool = ToolPDF(self)
  1614. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1615. pos=self.ui.menufileimport,
  1616. separator=True)
  1617. self.image_tool = ToolImage(self)
  1618. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1619. pos=self.ui.menufileimport,
  1620. separator=True)
  1621. self.pcb_wizard_tool = PcbWizard(self)
  1622. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1623. pos=self.ui.menufileimport)
  1624. self.log.debug("Tools are installed.")
  1625. def remove_tools(self):
  1626. """
  1627. Will remove all the actions in the Tool menu.
  1628. :return: None
  1629. """
  1630. for act in self.ui.menutool.actions():
  1631. self.ui.menutool.removeAction(act)
  1632. def init_tools(self):
  1633. """
  1634. Initialize the Tool tab in the notebook side of the central widget.
  1635. Remove the actions in the Tools menu.
  1636. Instantiate again the FlatCAM tools (plugins).
  1637. All this is required when changing the layout: standard, compact etc.
  1638. :return: None
  1639. """
  1640. log.debug("init_tools()")
  1641. # delete the data currently in the Tools Tab and the Tab itself
  1642. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1643. if widget is not None:
  1644. widget.deleteLater()
  1645. self.ui.notebook.removeTab(2)
  1646. # rebuild the Tools Tab
  1647. self.ui.tool_tab = QtWidgets.QWidget()
  1648. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1649. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1650. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1651. self.ui.tool_scroll_area = VerticalScrollArea()
  1652. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1653. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1654. # first remove all of them
  1655. self.remove_tools()
  1656. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1657. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1658. '&Command Line\tS')
  1659. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1660. # third install all of them
  1661. try:
  1662. self.install_tools()
  1663. except AttributeError:
  1664. pass
  1665. self.log.debug("Tools are initialized.")
  1666. # def parse_system_fonts(self):
  1667. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1668. # 'params': []})
  1669. def connect_tools_signals_to_toolbar(self, ui):
  1670. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1671. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1672. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1673. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1674. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1675. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1676. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1677. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1678. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1679. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1680. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1681. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1682. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1683. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1684. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1685. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1686. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1687. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1688. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1689. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1690. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1691. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1692. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1693. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1694. def connect_toolbar_signals(self, ui):
  1695. """
  1696. Reconnect the signals to the actions in the toolbar.
  1697. This has to be done each time after the FlatCAM tools are removed/installed.
  1698. :return: None
  1699. """
  1700. # Toolbar
  1701. # File Toolbar Signals
  1702. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1703. ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1704. ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1705. ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1706. ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1707. # View Toolbar Signals
  1708. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1709. ui.replot_btn.triggered.connect(self.plot_all)
  1710. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1711. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1712. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1713. # Edit Toolbar Signals
  1714. ui.editgeo_btn.triggered.connect(self.object2editor)
  1715. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1716. ui.copy_btn.triggered.connect(self.on_copy_command)
  1717. ui.delete_btn.triggered.connect(self.on_delete)
  1718. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1719. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1720. ui.origin_btn.triggered.connect(self.on_set_origin)
  1721. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1722. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1723. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1724. # Scripting Toolbar Signals
  1725. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1726. ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1727. ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1728. ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1729. # Tools Toolbar Signals
  1730. try:
  1731. self.connect_tools_signals_to_toolbar(ui=ui)
  1732. except Exception as err:
  1733. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1734. def object2editor(self):
  1735. """
  1736. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1737. :return: None
  1738. """
  1739. self.defaults.report_usage("object2editor()")
  1740. # disable the objects menu as it may interfere with the appEditors
  1741. self.ui.menuobjects.setDisabled(True)
  1742. edited_object = self.collection.get_active()
  1743. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1744. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1745. pass
  1746. else:
  1747. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1748. return
  1749. if isinstance(edited_object, GeometryObject):
  1750. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1751. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1752. # we set the notebook to hidden
  1753. # self.ui.splitter.setSizes([0, 1])
  1754. if edited_object.multigeo is True:
  1755. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1756. if len(sel_rows) > 1:
  1757. self.inform.emit('[WARNING_NOTCL] %s' %
  1758. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1759. "is not possible.\n"
  1760. "Edit only one geometry at a time."))
  1761. if not sel_rows:
  1762. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1763. return
  1764. # determine the tool dia of the selected tool
  1765. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1766. # now find the key in the edited_object.tools that has this tooldia
  1767. multi_tool = 1
  1768. for tool in edited_object.tools:
  1769. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1770. multi_tool = tool
  1771. break
  1772. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1773. else:
  1774. self.geo_editor.edit_fcgeometry(edited_object)
  1775. # set call source to the Editor we go into
  1776. self.call_source = 'geo_editor'
  1777. elif isinstance(edited_object, ExcellonObject):
  1778. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1779. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1780. if self.ui.splitter.sizes()[0] == 0:
  1781. self.ui.splitter.setSizes([1, 1])
  1782. self.exc_editor.edit_fcexcellon(edited_object)
  1783. # set call source to the Editor we go into
  1784. self.call_source = 'exc_editor'
  1785. elif isinstance(edited_object, GerberObject):
  1786. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1787. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1788. if self.ui.splitter.sizes()[0] == 0:
  1789. self.ui.splitter.setSizes([1, 1])
  1790. self.grb_editor.edit_fcgerber(edited_object)
  1791. # set call source to the Editor we go into
  1792. self.call_source = 'grb_editor'
  1793. # reset the following variables so the UI is built again after edit
  1794. edited_object.ui_build = False
  1795. edited_object.build_aperture_storage = False
  1796. elif isinstance(edited_object, CNCJobObject):
  1797. if self.ui.splitter.sizes()[0] == 0:
  1798. self.ui.splitter.setSizes([1, 1])
  1799. edited_object.on_edit_code_click()
  1800. return
  1801. # make sure that we can't select another object while in Editor Mode:
  1802. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1803. self.ui.project_frame.setDisabled(True)
  1804. # delete any selection shape that might be active as they are not relevant in Editor
  1805. self.delete_selection_shape()
  1806. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1807. self.ui.plot_tab_area.protectTab(0)
  1808. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1809. self.should_we_save = True
  1810. def editor2object(self, cleanup=None):
  1811. """
  1812. Transfers the Geometry or Excellon from it's editor to the current object.
  1813. :return: None
  1814. """
  1815. self.defaults.report_usage("editor2object()")
  1816. # re-enable the objects menu that was disabled on entry in Editor mode
  1817. self.ui.menuobjects.setDisabled(False)
  1818. # do not update a geometry or excellon object unless it comes out of an editor
  1819. if self.call_source != 'app':
  1820. edited_obj = self.collection.get_active()
  1821. if cleanup is None:
  1822. msgbox = QtWidgets.QMessageBox()
  1823. msgbox.setText(_("Do you want to save the edited object?"))
  1824. msgbox.setWindowTitle(_("Close Editor"))
  1825. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1826. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1827. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1828. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1829. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1830. msgbox.setDefaultButton(bt_yes)
  1831. msgbox.exec_()
  1832. response = msgbox.clickedButton()
  1833. if response == bt_yes:
  1834. # clean the Tools Tab
  1835. self.ui.tool_scroll_area.takeWidget()
  1836. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1837. self.ui.notebook.setTabText(2, "Tool")
  1838. if isinstance(edited_obj, GeometryObject):
  1839. obj_type = "Geometry"
  1840. self.geo_editor.update_fcgeometry(edited_obj)
  1841. # self.geo_editor.update_options(edited_obj)
  1842. # restore GUI to the Selected TAB
  1843. # Remove anything else in the appGUI
  1844. self.ui.tool_scroll_area.takeWidget()
  1845. # update the geo object options so it is including the bounding box values
  1846. try:
  1847. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1848. edited_obj.options['xmin'] = xmin
  1849. edited_obj.options['ymin'] = ymin
  1850. edited_obj.options['xmax'] = xmax
  1851. edited_obj.options['ymax'] = ymax
  1852. except AttributeError as e:
  1853. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1854. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1855. edited_obj.build_ui()
  1856. edited_obj.plot()
  1857. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1858. elif isinstance(edited_obj, GerberObject):
  1859. obj_type = "Gerber"
  1860. self.grb_editor.update_fcgerber()
  1861. # self.grb_editor.update_options(edited_obj)
  1862. # delete the old object (the source object) if it was an empty one
  1863. try:
  1864. if len(edited_obj.solid_geometry) == 0:
  1865. old_name = edited_obj.options['name']
  1866. self.collection.delete_by_name(old_name)
  1867. except TypeError:
  1868. # if the solid_geometry is a single Polygon the len() will not work
  1869. # in any case, falling here means that we have something in the solid_geometry, even if only
  1870. # a single Polygon, therefore we pass this
  1871. pass
  1872. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1873. # restore GUI to the Selected TAB
  1874. # Remove anything else in the GUI
  1875. self.ui.selected_scroll_area.takeWidget()
  1876. elif isinstance(edited_obj, ExcellonObject):
  1877. obj_type = "Excellon"
  1878. self.exc_editor.update_fcexcellon(edited_obj)
  1879. # self.exc_editor.update_options(edited_obj)
  1880. # restore GUI to the Selected TAB
  1881. # Remove anything else in the GUI
  1882. self.ui.tool_scroll_area.takeWidget()
  1883. # delete the old object (the source object) if it was an empty one
  1884. # find if we have drills:
  1885. has_drills = None
  1886. for tt in edited_obj.tools:
  1887. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1888. has_drills = True
  1889. break
  1890. # find if we have slots:
  1891. has_slots = None
  1892. for tt in edited_obj.tools:
  1893. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1894. has_slots = True
  1895. break
  1896. if has_drills is None and has_slots is None:
  1897. old_name = edited_obj.options['name']
  1898. self.collection.delete_by_name(name=old_name)
  1899. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1900. else:
  1901. self.inform.emit('[WARNING_NOTCL] %s' %
  1902. _("Select a Gerber, Geometry or Excellon Object to update."))
  1903. return
  1904. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1905. elif response == bt_no:
  1906. # clean the Tools Tab
  1907. self.ui.tool_scroll_area.takeWidget()
  1908. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1909. self.ui.notebook.setTabText(2, "Tool")
  1910. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1911. if isinstance(edited_obj, GeometryObject):
  1912. self.geo_editor.deactivate()
  1913. edited_obj.build_ui()
  1914. edited_obj.plot()
  1915. elif isinstance(edited_obj, GerberObject):
  1916. self.grb_editor.deactivate_grb_editor()
  1917. edited_obj.build_ui()
  1918. elif isinstance(edited_obj, ExcellonObject):
  1919. self.exc_editor.deactivate()
  1920. edited_obj.build_ui()
  1921. else:
  1922. self.inform.emit('[WARNING_NOTCL] %s' %
  1923. _("Select a Gerber, Geometry or Excellon Object to update."))
  1924. return
  1925. elif response == bt_cancel:
  1926. return
  1927. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1928. # edited_obj.build_ui()
  1929. # Switch notebook to Selected page
  1930. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1931. else:
  1932. if isinstance(edited_obj, GeometryObject):
  1933. self.geo_editor.deactivate()
  1934. elif isinstance(edited_obj, GerberObject):
  1935. self.grb_editor.deactivate_grb_editor()
  1936. elif isinstance(edited_obj, ExcellonObject):
  1937. self.exc_editor.deactivate()
  1938. else:
  1939. self.inform.emit('[WARNING_NOTCL] %s' %
  1940. _("Select a Gerber, Geometry or Excellon Object to update."))
  1941. return
  1942. # if notebook is hidden we show it
  1943. if self.ui.splitter.sizes()[0] == 0:
  1944. self.ui.splitter.setSizes([1, 1])
  1945. # restore the call_source to app
  1946. self.call_source = 'app'
  1947. # edited_obj.plot()
  1948. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1949. self.ui.plot_tab_area.protectTab(0)
  1950. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1951. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1952. self.ui.project_frame.setDisabled(False)
  1953. def get_last_folder(self):
  1954. """
  1955. Get the folder path from where the last file was opened.
  1956. :return: String, last opened folder path
  1957. """
  1958. return self.defaults["global_last_folder"]
  1959. def get_last_save_folder(self):
  1960. """
  1961. Get the folder path from where the last file was saved.
  1962. :return: String, last saved folder path
  1963. """
  1964. loc = self.defaults["global_last_save_folder"]
  1965. if loc is None:
  1966. loc = self.defaults["global_last_folder"]
  1967. if loc is None:
  1968. loc = os.path.dirname(__file__)
  1969. return loc
  1970. @QtCore.pyqtSlot(str)
  1971. @QtCore.pyqtSlot(str, bool)
  1972. def info(self, msg, shell_echo=True):
  1973. """
  1974. Informs the user. Normally on the status bar, optionally
  1975. also on the shell.
  1976. :param msg: Text to write.
  1977. :type msg: str
  1978. :param shell_echo: Control if to display the message msg in the Shell
  1979. :type shell_echo: bool
  1980. :return: None
  1981. """
  1982. # Type of message in brackets at the beginning of the message.
  1983. match = re.search(r"\[(.*)\](.*)", msg)
  1984. if match:
  1985. level = match.group(1)
  1986. msg_ = match.group(2)
  1987. self.ui.fcinfo.set_status(str(msg_), level=level)
  1988. if shell_echo is True:
  1989. if level.lower() == "error":
  1990. self.shell_message(msg, error=True, show=True)
  1991. elif level.lower() == "warning":
  1992. self.shell_message(msg, warning=True, show=True)
  1993. elif level.lower() == "error_notcl":
  1994. self.shell_message(msg, error=True, show=False)
  1995. elif level.lower() == "warning_notcl":
  1996. self.shell_message(msg, warning=True, show=False)
  1997. elif level.lower() == "success":
  1998. self.shell_message(msg, success=True, show=False)
  1999. elif level.lower() == "selected":
  2000. self.shell_message(msg, selected=True, show=False)
  2001. else:
  2002. self.shell_message(msg, show=False)
  2003. else:
  2004. self.ui.fcinfo.set_status(str(msg), level="info")
  2005. # make sure that if the message is to clear the infobar with a space
  2006. # is not printed over and over on the shell
  2007. if msg != '' and shell_echo is True:
  2008. self.shell_message(msg)
  2009. def info_shell(self, msg):
  2010. self.shell_message(msg=msg)
  2011. def on_import_preferences(self):
  2012. """
  2013. Loads the application default settings from a saved file into
  2014. ``self.defaults`` dictionary.
  2015. :return: None
  2016. """
  2017. self.defaults.report_usage("on_import_preferences")
  2018. App.log.debug("App.on_import_preferences()")
  2019. # Show file chooser
  2020. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2021. try:
  2022. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2023. directory=self.data_path,
  2024. filter=filter_)
  2025. except TypeError:
  2026. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2027. filter=filter_)
  2028. filename = str(filename)
  2029. if filename == "":
  2030. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2031. return
  2032. # Load in the defaults from the chosen file
  2033. self.defaults.load(filename=filename)
  2034. self.preferencesUiManager.on_preferences_edited()
  2035. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2036. def on_export_preferences(self):
  2037. """
  2038. Save the defaults dictionary to a file.
  2039. :return: None
  2040. """
  2041. self.defaults.report_usage("on_export_preferences")
  2042. App.log.debug("on_export_preferences()")
  2043. # defaults_file_content = None
  2044. # Show file chooser
  2045. date = str(datetime.today()).rpartition('.')[0]
  2046. date = ''.join(c for c in date if c not in ':-')
  2047. date = date.replace(' ', '_')
  2048. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2049. try:
  2050. filename, _f = FCFileSaveDialog.get_saved_filename(
  2051. caption=_("Export FlatCAM Preferences"),
  2052. directory=self.data_path + '/preferences_' + date,
  2053. ext_filter=filter__
  2054. )
  2055. except TypeError:
  2056. filename, _f = FCFileSaveDialog.get_saved_filename(
  2057. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2058. filename = str(filename)
  2059. if filename == "":
  2060. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2061. return
  2062. # Update options
  2063. self.preferencesUiManager.defaults_read_form()
  2064. self.defaults.propagate_defaults()
  2065. # Save update options
  2066. try:
  2067. self.defaults.write(filename=filename)
  2068. except Exception:
  2069. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2070. return
  2071. if self.defaults["global_open_style"] is False:
  2072. self.file_opened.emit("preferences", filename)
  2073. self.file_saved.emit("preferences", filename)
  2074. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2075. def save_to_file(self, content_to_save, txt_content):
  2076. """
  2077. Save something to a file.
  2078. :return: None
  2079. """
  2080. self.defaults.report_usage("save_to_file")
  2081. App.log.debug("save_to_file()")
  2082. self.date = str(datetime.today()).rpartition('.')[0]
  2083. self.date = ''.join(c for c in self.date if c not in ':-')
  2084. self.date = self.date.replace(' ', '_')
  2085. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2086. path_to_save = self.defaults["global_last_save_folder"] if \
  2087. self.defaults["global_last_save_folder"] is not None else self.data_path
  2088. try:
  2089. filename, _f = FCFileSaveDialog.get_saved_filename(
  2090. caption=_("Save to file"),
  2091. directory=path_to_save + '/file_' + self.date,
  2092. ext_filter=filter__
  2093. )
  2094. except TypeError:
  2095. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2096. filename = str(filename)
  2097. if filename == "":
  2098. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2099. return
  2100. else:
  2101. try:
  2102. with open(filename, 'w') as f:
  2103. ___ = f.read()
  2104. except PermissionError:
  2105. self.inform.emit('[WARNING] %s' %
  2106. _("Permission denied, saving not possible.\n"
  2107. "Most likely another app is holding the file open and not accessible."))
  2108. return
  2109. except IOError:
  2110. App.log.debug('Creating a new file ...')
  2111. f = open(filename, 'w')
  2112. f.close()
  2113. except Exception:
  2114. e = sys.exc_info()[0]
  2115. App.log.error("Could not load the file.")
  2116. App.log.error(str(e))
  2117. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2118. return
  2119. # Save content
  2120. if filename.rpartition('.')[2].lower() == 'html':
  2121. file_content = content_to_save
  2122. else:
  2123. file_content = txt_content
  2124. try:
  2125. with open(filename, "w") as f:
  2126. f.write(file_content)
  2127. except Exception:
  2128. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2129. return
  2130. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2131. def register_recent(self, kind, filename):
  2132. """
  2133. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2134. dictionary.
  2135. :param kind: type of file that was opened
  2136. :param filename: the path and file name for the file that was opened
  2137. :return:
  2138. """
  2139. self.log.debug("register_recent()")
  2140. self.log.debug(" %s" % kind)
  2141. self.log.debug(" %s" % filename)
  2142. record = {'kind': str(kind), 'filename': str(filename)}
  2143. if record in self.recent:
  2144. return
  2145. if record in self.recent_projects:
  2146. return
  2147. if record['kind'] == 'project':
  2148. self.recent_projects.insert(0, record)
  2149. else:
  2150. self.recent.insert(0, record)
  2151. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2152. self.recent.pop()
  2153. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2154. self.recent_projects.pop()
  2155. try:
  2156. f = open(self.data_path + '/recent.json', 'w')
  2157. except IOError:
  2158. App.log.error("Failed to open recent items file for writing.")
  2159. self.inform.emit('[ERROR_NOTCL] %s' %
  2160. _('Failed to open recent files file for writing.'))
  2161. return
  2162. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2163. f.close()
  2164. try:
  2165. fp = open(self.data_path + '/recent_projects.json', 'w')
  2166. except IOError:
  2167. App.log.error("Failed to open recent items file for writing.")
  2168. self.inform.emit('[ERROR_NOTCL] %s' %
  2169. _('Failed to open recent projects file for writing.'))
  2170. return
  2171. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2172. fp.close()
  2173. # Re-build the recent items menu
  2174. self.setup_recent_items()
  2175. def on_about(self):
  2176. """
  2177. Displays the "about" dialog found in the Menu --> Help.
  2178. :return: None
  2179. """
  2180. self.defaults.report_usage("on_about")
  2181. version = self.version
  2182. version_date = self.version_date
  2183. beta = self.beta
  2184. class AboutDialog(QtWidgets.QDialog):
  2185. def __init__(self, app, parent=None):
  2186. QtWidgets.QDialog.__init__(self, parent)
  2187. self.app = app
  2188. # Icon and title
  2189. self.setWindowIcon(parent.app_icon)
  2190. self.setWindowTitle(_("About FlatCAM"))
  2191. self.resize(600, 200)
  2192. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2193. # self.setStyleSheet(
  2194. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2195. # "background-attachment: fixed"
  2196. # )
  2197. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2198. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2199. # palette = QtGui.QPalette()
  2200. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2201. # self.setPalette(palette)
  2202. logo = QtWidgets.QLabel()
  2203. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2204. title = QtWidgets.QLabel(
  2205. "<font size=8><B>FlatCAM</B></font><BR>"
  2206. "{title}<BR>"
  2207. "<BR>"
  2208. "<BR>"
  2209. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2210. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2211. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2212. "<B>{issue}</B></a><BR>".format(
  2213. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2214. devel=_("Development"),
  2215. down=_("DOWNLOAD"),
  2216. issue=_("Issue tracker"))
  2217. )
  2218. title.setOpenExternalLinks(True)
  2219. closebtn = QtWidgets.QPushButton(_("Close"))
  2220. tab_widget = QtWidgets.QTabWidget()
  2221. description_label = QtWidgets.QLabel(
  2222. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2223. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2224. version=version,
  2225. beta=('BETA' if beta else ''),
  2226. date=version_date,
  2227. arch=platform.architecture()[0])
  2228. )
  2229. description_label.setOpenExternalLinks(True)
  2230. lic_lbl_header = QtWidgets.QLabel(
  2231. '%s:<br>%s<br>' % (
  2232. _('Licensed under the MIT license'),
  2233. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2234. "http://www.opensource.org/licenses/mit-license.php</a>"
  2235. )
  2236. )
  2237. lic_lbl_header.setOpenExternalLinks(True)
  2238. lic_lbl_body = QtWidgets.QLabel(
  2239. _(
  2240. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2241. 'of this software and associated documentation files (the "Software"), to deal\n'
  2242. 'in the Software without restriction, including without limitation the rights\n'
  2243. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2244. 'copies of the Software, and to permit persons to whom the Software is\n'
  2245. 'furnished to do so, subject to the following conditions:\n\n'
  2246. 'The above copyright notice and this permission notice shall be included in\n'
  2247. 'all copies or substantial portions of the Software.\n\n'
  2248. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2249. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2250. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2251. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2252. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2253. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2254. 'THE SOFTWARE.'
  2255. )
  2256. )
  2257. attributions_label = QtWidgets.QLabel(
  2258. _(
  2259. 'Some of the icons used are from the following sources:<br>'
  2260. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2261. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2262. 'title="Flaticon">www.flaticon.com</a></div>'
  2263. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2264. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2265. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2266. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2267. 'title="Flaticon">www.flaticon.com</a></div>'
  2268. )
  2269. )
  2270. attributions_label.setOpenExternalLinks(True)
  2271. # layouts
  2272. layout1 = QtWidgets.QVBoxLayout()
  2273. layout1_1 = QtWidgets.QHBoxLayout()
  2274. layout1_2 = QtWidgets.QHBoxLayout()
  2275. layout2 = QtWidgets.QHBoxLayout()
  2276. layout3 = QtWidgets.QHBoxLayout()
  2277. self.setLayout(layout1)
  2278. layout1.addLayout(layout1_1)
  2279. layout1.addLayout(layout1_2)
  2280. layout1.addLayout(layout2)
  2281. layout1.addLayout(layout3)
  2282. layout1_1.addStretch()
  2283. layout1_1.addWidget(description_label)
  2284. layout1_2.addWidget(tab_widget)
  2285. self.splash_tab = QtWidgets.QWidget()
  2286. self.splash_tab.setObjectName("splash_about")
  2287. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2288. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2289. tab_widget.addTab(self.splash_tab, _("Splash"))
  2290. self.programmmers_tab = QtWidgets.QWidget()
  2291. self.programmmers_tab.setObjectName("programmers_about")
  2292. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2293. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2294. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2295. self.translators_tab = QtWidgets.QWidget()
  2296. self.translators_tab.setObjectName("translators_about")
  2297. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2298. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2299. tab_widget.addTab(self.translators_tab, _("Translators"))
  2300. self.license_tab = QtWidgets.QWidget()
  2301. self.license_tab.setObjectName("license_about")
  2302. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2303. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2304. tab_widget.addTab(self.license_tab, _("License"))
  2305. self.attributions_tab = QtWidgets.QWidget()
  2306. self.attributions_tab.setObjectName("attributions_about")
  2307. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2308. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2309. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2310. self.splash_tab_layout.addWidget(logo, stretch=0)
  2311. self.splash_tab_layout.addWidget(title, stretch=1)
  2312. pal = QtGui.QPalette()
  2313. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2314. self.prog_grid_lay = QtWidgets.QGridLayout()
  2315. self.prog_grid_lay.setHorizontalSpacing(20)
  2316. self.prog_grid_lay.setColumnStretch(0, 0)
  2317. self.prog_grid_lay.setColumnStretch(2, 1)
  2318. prog_widget = QtWidgets.QWidget()
  2319. prog_widget.setLayout(self.prog_grid_lay)
  2320. prog_scroll = QtWidgets.QScrollArea()
  2321. prog_scroll.setWidget(prog_widget)
  2322. prog_scroll.setWidgetResizable(True)
  2323. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2324. prog_scroll.setPalette(pal)
  2325. self.programmmers_tab_layout.addWidget(prog_scroll)
  2326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2328. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2330. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2332. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2333. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2334. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2335. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2336. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2337. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2338. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2339. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2340. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2341. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2342. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2343. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2344. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2345. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2346. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2347. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2348. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2349. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2350. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2351. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2352. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2353. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2354. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2355. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2356. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2357. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2358. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2359. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2360. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2361. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2362. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2363. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2364. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2365. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2366. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2367. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2368. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2369. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2370. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2371. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2372. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2373. self.translator_grid_lay = QtWidgets.QGridLayout()
  2374. self.translator_grid_lay.setColumnStretch(0, 0)
  2375. self.translator_grid_lay.setColumnStretch(1, 0)
  2376. self.translator_grid_lay.setColumnStretch(2, 1)
  2377. self.translator_grid_lay.setColumnStretch(3, 0)
  2378. # trans_widget = QtWidgets.QWidget()
  2379. # trans_widget.setLayout(self.translator_grid_lay)
  2380. # self.translators_tab_layout.addWidget(trans_widget)
  2381. # self.translators_tab_layout.addStretch()
  2382. trans_widget = QtWidgets.QWidget()
  2383. trans_widget.setLayout(self.translator_grid_lay)
  2384. trans_scroll = QtWidgets.QScrollArea()
  2385. trans_scroll.setWidget(trans_widget)
  2386. trans_scroll.setWidgetResizable(True)
  2387. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2388. trans_scroll.setPalette(pal)
  2389. self.translators_tab_layout.addWidget(trans_scroll)
  2390. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2391. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2392. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2393. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2394. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2395. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2396. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2397. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2398. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2399. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2400. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2401. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2402. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2403. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2404. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2405. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2406. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2407. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2408. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2409. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2410. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2411. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2412. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2413. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2414. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2415. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2416. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2417. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2418. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2419. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2420. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2421. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2422. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2423. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2424. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2425. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2426. self.translator_grid_lay.setColumnStretch(0, 0)
  2427. self.translators_tab_layout.addStretch()
  2428. self.license_tab_layout.addWidget(lic_lbl_header)
  2429. self.license_tab_layout.addWidget(lic_lbl_body)
  2430. self.license_tab_layout.addStretch()
  2431. self.attributions_tab_layout.addWidget(attributions_label)
  2432. self.attributions_tab_layout.addStretch()
  2433. layout3.addStretch()
  2434. layout3.addWidget(closebtn)
  2435. closebtn.clicked.connect(self.accept)
  2436. AboutDialog(app=self, parent=self.ui).exec_()
  2437. def on_readme(self):
  2438. """
  2439. Displays the "about" dialog found in the Menu --> Help.
  2440. :return: None
  2441. """
  2442. class ReadmeDialog(QtWidgets.QDialog):
  2443. def __init__(self, app, parent=None):
  2444. QtWidgets.QDialog.__init__(self, parent)
  2445. self.app = app
  2446. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2447. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2448. "<b>click</b></a>"
  2449. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2450. # donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2451. # "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2452. # Icon and title
  2453. self.setWindowIcon(parent.app_icon)
  2454. self.setWindowTitle(_("Important Information's"))
  2455. self.resize(750, 375)
  2456. logo = QtWidgets.QLabel()
  2457. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2458. # content = QtWidgets.QLabel(
  2459. # "%s<br>"
  2460. # "%s<br><br>"
  2461. # "%s,<br>"
  2462. # "%s<br>"
  2463. # "<ul>"
  2464. # "<li> &nbsp;%s %s</li>"
  2465. # "<li> &nbsp;%s %s</li>"
  2466. # "</ul>"
  2467. # "%s %s.<br>"
  2468. # "%s"
  2469. # "<ul>"
  2470. # "<li> &nbsp;%s &#128077;</li>"
  2471. # "<li> &nbsp;%s &#128513;</li>"
  2472. # "</ul>" %
  2473. # (
  2474. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2475. # _("Yet it cannot evolve without <b>contributions</b>."),
  2476. # _("If you want to see this application grow and become better and better"),
  2477. # _("you can <b>contribute</b> to the development yourself by:"),
  2478. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2479. # new_features_link,
  2480. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2481. # bugs_link,
  2482. # _("If you like or use this program you can make a donation"),
  2483. # donation_link,
  2484. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2485. # _("it will be welcomed with joy"),
  2486. # _("it will give me a reason to continue")
  2487. # )
  2488. # )
  2489. content = QtWidgets.QLabel(
  2490. "%s<br>"
  2491. "%s<br><br>"
  2492. "%s,<br>"
  2493. "%s<br>"
  2494. "<ul>"
  2495. "<li> &nbsp;%s %s</li>"
  2496. "<li> &nbsp;%s %s</li>"
  2497. "</ul>" %
  2498. (
  2499. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2500. _("Yet it cannot evolve without <b>contributions</b>."),
  2501. _("If you want to see this application grow and become better and better"),
  2502. _("you can <b>contribute</b> to the development yourself by:"),
  2503. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2504. new_features_link,
  2505. _("Bug Reports by providing the steps required to reproduce the bug"),
  2506. bugs_link
  2507. )
  2508. )
  2509. content.setOpenExternalLinks(True)
  2510. # palette
  2511. pal = QtGui.QPalette()
  2512. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2513. # layouts
  2514. main_layout = QtWidgets.QVBoxLayout()
  2515. self.setLayout(main_layout)
  2516. tab_layout = QtWidgets.QHBoxLayout()
  2517. buttons_hlay = QtWidgets.QHBoxLayout()
  2518. main_layout.addLayout(tab_layout)
  2519. main_layout.addLayout(buttons_hlay)
  2520. tab_widget = QtWidgets.QTabWidget()
  2521. tab_layout.addWidget(tab_widget)
  2522. closebtn = QtWidgets.QPushButton(_("Close"))
  2523. buttons_hlay.addStretch()
  2524. buttons_hlay.addWidget(closebtn)
  2525. # CONTRIBUTE section
  2526. self.intro_tab = QtWidgets.QWidget()
  2527. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2528. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2529. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2530. self.grid_lay = QtWidgets.QGridLayout()
  2531. self.grid_lay.setHorizontalSpacing(20)
  2532. self.grid_lay.setColumnStretch(0, 0)
  2533. self.grid_lay.setColumnStretch(1, 1)
  2534. intro_wdg = QtWidgets.QWidget()
  2535. intro_wdg.setLayout(self.grid_lay)
  2536. intro_scroll_area = QtWidgets.QScrollArea()
  2537. intro_scroll_area.setWidget(intro_wdg)
  2538. intro_scroll_area.setWidgetResizable(True)
  2539. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2540. intro_scroll_area.setPalette(pal)
  2541. self.grid_lay.addWidget(logo, 0, 0)
  2542. self.grid_lay.addWidget(content, 0, 1)
  2543. self.intro_tab_layout.addWidget(intro_scroll_area)
  2544. # LINKS EXCHANGE section
  2545. self.links_tab = QtWidgets.QWidget()
  2546. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2547. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2548. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2549. self.links_lay = QtWidgets.QHBoxLayout()
  2550. links_wdg = QtWidgets.QWidget()
  2551. links_wdg.setLayout(self.links_lay)
  2552. links_scroll_area = QtWidgets.QScrollArea()
  2553. links_scroll_area.setWidget(links_wdg)
  2554. links_scroll_area.setWidgetResizable(True)
  2555. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2556. links_scroll_area.setPalette(pal)
  2557. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2558. self.links_tab_layout.addWidget(links_scroll_area)
  2559. # HOW TO section
  2560. self.howto_tab = QtWidgets.QWidget()
  2561. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2562. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2563. tab_widget.addTab(self.howto_tab, _("How To's"))
  2564. self.howto_lay = QtWidgets.QHBoxLayout()
  2565. howto_wdg = QtWidgets.QWidget()
  2566. howto_wdg.setLayout(self.howto_lay)
  2567. howto_scroll_area = QtWidgets.QScrollArea()
  2568. howto_scroll_area.setWidget(howto_wdg)
  2569. howto_scroll_area.setWidgetResizable(True)
  2570. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2571. howto_scroll_area.setPalette(pal)
  2572. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2573. self.howto_tab_layout.addWidget(howto_scroll_area)
  2574. # BUTTONS section
  2575. closebtn.clicked.connect(self.accept)
  2576. ReadmeDialog(app=self, parent=self.ui).exec_()
  2577. def install_bookmarks(self, book_dict=None):
  2578. """
  2579. Install the bookmarks actions in the Help menu -> Bookmarks
  2580. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2581. :return: None
  2582. """
  2583. if book_dict is None:
  2584. self.defaults["global_bookmarks"].update(
  2585. {
  2586. '1': ['FlatCAM', "http://flatcam.org"],
  2587. '2': ['Backup Site', ""]
  2588. }
  2589. )
  2590. else:
  2591. self.defaults["global_bookmarks"].clear()
  2592. self.defaults["global_bookmarks"].update(book_dict)
  2593. # first try to disconnect if somehow they get connected from elsewhere
  2594. for act in self.ui.menuhelp_bookmarks.actions():
  2595. try:
  2596. act.triggered.disconnect()
  2597. except TypeError:
  2598. pass
  2599. # clear all actions except the last one who is the Bookmark manager
  2600. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2601. pass
  2602. else:
  2603. self.ui.menuhelp_bookmarks.removeAction(act)
  2604. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2605. if self.defaults["global_bookmarks"]:
  2606. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2607. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2608. # the JSON is first making the keys as strings (therefore I have to use strings too
  2609. # or do the conversion :(
  2610. # )
  2611. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2612. # the '10' entry jsut after '1' therefore ordering as strings
  2613. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2614. key=lambda x: int(x[0]))
  2615. for entry, bookmark in sorted_bookmarks:
  2616. title = bookmark[0]
  2617. weblink = bookmark[1]
  2618. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2619. act.setText(title)
  2620. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2621. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2622. if title == 'Backup Site' and weblink == "":
  2623. act.triggered.connect(self.on_backup_site)
  2624. else:
  2625. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2626. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2627. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2628. def on_bookmarks_manager(self):
  2629. """
  2630. Adds the bookmark manager in a Tab in Plot Area
  2631. :return:
  2632. """
  2633. for idx in range(self.ui.plot_tab_area.count()):
  2634. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2635. # there can be only one instance of Bookmark Manager at one time
  2636. return
  2637. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2638. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2639. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2640. # add the tab if it was closed
  2641. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2642. # delete the absolute and relative position and messages in the infobar
  2643. # self.ui.position_label.setText("")
  2644. # self.ui.rel_position_label.setText("")
  2645. # hide coordinates toolbars in the infobar while in DB
  2646. self.ui.coords_toolbar.hide()
  2647. self.ui.delta_coords_toolbar.hide()
  2648. # Switch plot_area to preferences page
  2649. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2650. def on_backup_site(self):
  2651. msgbox = QtWidgets.QMessageBox()
  2652. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2653. "1. FlatCAM.org website is down\n"
  2654. "2. Someone forked FlatCAM project and wants to point\n"
  2655. "to his own website\n\n"
  2656. "If you can't get any informations about FlatCAM beta\n"
  2657. "use the YouTube channel link from the Help menu."))
  2658. msgbox.setWindowTitle(_("Alternative website"))
  2659. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2660. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2661. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2662. msgbox.setDefaultButton(bt_yes)
  2663. msgbox.exec_()
  2664. # response = msgbox.clickedButton()
  2665. def on_file_savedefaults(self):
  2666. """
  2667. Callback for menu item File->Save Defaults. Saves application default options
  2668. ``self.defaults`` to current_defaults.FlatConfig.
  2669. :return: None
  2670. """
  2671. self.preferencesUiManager.save_defaults()
  2672. def final_save(self):
  2673. """
  2674. Callback for doing a preferences save to file whenever the application is about to quit.
  2675. If the project has changes, it will ask the user to save the project.
  2676. :return: None
  2677. """
  2678. if self.save_in_progress:
  2679. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2680. return
  2681. if self.should_we_save and self.collection.get_list():
  2682. msgbox = QtWidgets.QMessageBox()
  2683. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2684. "\n"
  2685. "Do you want to Save the project?"))
  2686. msgbox.setWindowTitle(_("Save changes"))
  2687. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2688. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2689. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2690. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2691. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2692. msgbox.setDefaultButton(bt_yes)
  2693. msgbox.exec_()
  2694. response = msgbox.clickedButton()
  2695. if response == bt_yes:
  2696. try:
  2697. self.trayIcon.hide()
  2698. except Exception:
  2699. pass
  2700. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2701. elif response == bt_no:
  2702. try:
  2703. self.trayIcon.hide()
  2704. except Exception:
  2705. pass
  2706. self.quit_application()
  2707. elif response == bt_cancel:
  2708. return
  2709. else:
  2710. try:
  2711. self.trayIcon.hide()
  2712. except Exception:
  2713. pass
  2714. self.quit_application()
  2715. def quit_application(self):
  2716. """
  2717. Called (as a pyslot or not) when the application is quit.
  2718. :return: None
  2719. """
  2720. # close editors before quiting the app, if they are open
  2721. if self.geo_editor.editor_active is True:
  2722. self.geo_editor.deactivate()
  2723. try:
  2724. self.geo_editor.disconnect()
  2725. except TypeError:
  2726. pass
  2727. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2728. if self.exc_editor.editor_active is True:
  2729. self.exc_editor.deactivate()
  2730. try:
  2731. self.grb_editor.disconnect()
  2732. except TypeError:
  2733. pass
  2734. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2735. if self.grb_editor.editor_active is True:
  2736. self.grb_editor.deactivate_grb_editor()
  2737. try:
  2738. self.exc_editor.disconnect()
  2739. except TypeError:
  2740. pass
  2741. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2742. # disconnect the mouse events
  2743. if self.is_legacy:
  2744. self.plotcanvas.graph_event_disconnect(self.mm)
  2745. self.plotcanvas.graph_event_disconnect(self.mp)
  2746. self.plotcanvas.graph_event_disconnect(self.mr)
  2747. self.plotcanvas.graph_event_disconnect(self.mdc)
  2748. self.plotcanvas.graph_event_disconnect(self.kp)
  2749. else:
  2750. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2751. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2752. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2753. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2754. self.on_mouse_double_click_over_plot)
  2755. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2756. self.preferencesUiManager.save_defaults(silent=True)
  2757. log.debug("App.quit_application() --> App Defaults saved.")
  2758. if self.cmd_line_headless != 1:
  2759. # save app state to file
  2760. stgs = QSettings("Open Source", "FlatCAM")
  2761. stgs.setValue('saved_gui_state', self.ui.saveState())
  2762. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2763. stgs.setValue(
  2764. 'language',
  2765. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2766. )
  2767. stgs.setValue(
  2768. 'notebook_font_size',
  2769. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2770. )
  2771. stgs.setValue(
  2772. 'axis_font_size',
  2773. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2774. )
  2775. stgs.setValue(
  2776. 'textbox_font_size',
  2777. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2778. )
  2779. stgs.setValue(
  2780. 'hud_font_size',
  2781. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2782. )
  2783. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2784. stgs.setValue(
  2785. 'machinist',
  2786. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2787. )
  2788. # This will write the setting to the platform specific storage.
  2789. del stgs
  2790. log.debug("App.quit_application() --> App UI state saved.")
  2791. # try to quit the Socket opened by ArgsThread class
  2792. try:
  2793. # self.new_launch.thread_exit = True
  2794. # self.new_launch.listener.close()
  2795. self.new_launch.stop.emit()
  2796. except Exception as err:
  2797. log.debug("App.quit_application() --> %s" % str(err))
  2798. # try to quit the QThread that run ArgsThread class
  2799. try:
  2800. # del self.new_launch
  2801. self.listen_th.quit()
  2802. except Exception as e:
  2803. log.debug("App.quit_application() --> %s" % str(e))
  2804. # terminate workers
  2805. # self.workers.__del__()
  2806. self.clear_pool()
  2807. # quit app by signalling for self.kill_app() method
  2808. # self.close_app_signal.emit()
  2809. QtWidgets.qApp.quit()
  2810. sys.exit(0)
  2811. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2812. # we use the following command
  2813. # minor_v = sys.version_info.minor
  2814. # if minor_v < 8:
  2815. # # make sure that the app closes
  2816. # sys.exit(0)
  2817. # else:
  2818. # os._exit(0) # fix to work with Python 3.8
  2819. @staticmethod
  2820. def kill_app():
  2821. QtWidgets.qApp.quit()
  2822. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2823. # we use the following command
  2824. sys.exit(0)
  2825. def on_portable_checked(self, state):
  2826. """
  2827. Callback called when the checkbox in Preferences GUI is checked.
  2828. It will set the application as portable by creating the preferences and recent files in the
  2829. 'config' folder found in the FlatCAM installation folder.
  2830. :param state: boolean, the state of the checkbox when clicked/checked
  2831. :return:
  2832. """
  2833. line_no = 0
  2834. data = None
  2835. if sys.platform != 'win32':
  2836. # this won't work in Linux or MacOS
  2837. return
  2838. # test if the app was frozen and choose the path for the configuration file
  2839. if getattr(sys, "frozen", False) is True:
  2840. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2841. else:
  2842. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2843. config_file = current_data_path + '\\configuration.txt'
  2844. try:
  2845. with open(config_file, 'r') as f:
  2846. try:
  2847. data = f.readlines()
  2848. except Exception as e:
  2849. log.debug('App.__init__() -->%s' % str(e))
  2850. return
  2851. except FileNotFoundError:
  2852. pass
  2853. for line in data:
  2854. line = line.strip('\n')
  2855. param = str(line).rpartition('=')
  2856. if param[0] == 'portable':
  2857. break
  2858. line_no += 1
  2859. if state:
  2860. data[line_no] = 'portable=True\n'
  2861. # create the new defauults files
  2862. # create current_defaults.FlatConfig file if there is none
  2863. try:
  2864. f = open(current_data_path + '/current_defaults.FlatConfig')
  2865. f.close()
  2866. except IOError:
  2867. App.log.debug('Creating empty current_defaults.FlatConfig')
  2868. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2869. json.dump({}, f)
  2870. f.close()
  2871. # create factory_defaults.FlatConfig file if there is none
  2872. try:
  2873. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2874. f.close()
  2875. except IOError:
  2876. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2877. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2878. json.dump({}, f)
  2879. f.close()
  2880. try:
  2881. f = open(current_data_path + '/recent.json')
  2882. f.close()
  2883. except IOError:
  2884. App.log.debug('Creating empty recent.json')
  2885. f = open(current_data_path + '/recent.json', 'w')
  2886. json.dump([], f)
  2887. f.close()
  2888. try:
  2889. fp = open(current_data_path + '/recent_projects.json')
  2890. fp.close()
  2891. except IOError:
  2892. App.log.debug('Creating empty recent_projects.json')
  2893. fp = open(current_data_path + '/recent_projects.json', 'w')
  2894. json.dump([], fp)
  2895. fp.close()
  2896. # save the current defaults to the new defaults file
  2897. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2898. else:
  2899. data[line_no] = 'portable=False\n'
  2900. with open(config_file, 'w') as f:
  2901. f.writelines(data)
  2902. def on_register_files(self, obj_type=None):
  2903. """
  2904. Called whenever there is a need to register file extensions with FlatCAM.
  2905. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2906. :param obj_type: the type of object to be register for.
  2907. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2908. :return: None
  2909. """
  2910. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2911. new_reg_path = 'Software\\Classes\\'
  2912. # find if the current user is admin
  2913. try:
  2914. is_admin = os.getuid() == 0
  2915. except AttributeError:
  2916. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2917. if is_admin is True:
  2918. root_path = winreg.HKEY_LOCAL_MACHINE
  2919. else:
  2920. root_path = winreg.HKEY_CURRENT_USER
  2921. # create the keys
  2922. def set_reg(name, root_pth, new_reg_path, value):
  2923. try:
  2924. winreg.CreateKey(root_pth, new_reg_path)
  2925. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2926. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2927. return True
  2928. except WindowsError:
  2929. return False
  2930. # delete key in registry
  2931. def delete_reg(root_pth, reg_path, key_to_del):
  2932. key_to_del_path = reg_path + key_to_del
  2933. try:
  2934. winreg.DeleteKey(root_pth, key_to_del_path)
  2935. return True
  2936. except WindowsError:
  2937. return False
  2938. if obj_type is None or obj_type == 'excellon':
  2939. exc_list = \
  2940. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2941. exc_list = [x for x in exc_list if x != '']
  2942. # register all keys in the Preferences window
  2943. for ext in exc_list:
  2944. new_k = new_reg_path + '.%s' % ext
  2945. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2946. # and unregister those that are no longer in the Preferences windows but are in the file
  2947. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2948. if ext not in exc_list:
  2949. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2950. # now write the updated extensions to the self.defaults
  2951. # new_ext = ''
  2952. # for ext in exc_list:
  2953. # new_ext = new_ext + ext + ', '
  2954. # self.defaults["fa_excellon"] = new_ext
  2955. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2956. if obj_type is None or obj_type == 'gcode':
  2957. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2958. gco_list = [x for x in gco_list if x != '']
  2959. # register all keys in the Preferences window
  2960. for ext in gco_list:
  2961. new_k = new_reg_path + '.%s' % ext
  2962. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2963. # and unregister those that are no longer in the Preferences windows but are in the file
  2964. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2965. if ext not in gco_list:
  2966. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2967. # now write the updated extensions to the self.defaults
  2968. # new_ext = ''
  2969. # for ext in gco_list:
  2970. # new_ext = new_ext + ext + ', '
  2971. # self.defaults["fa_gcode"] = new_ext
  2972. self.inform.emit('[success] %s' %
  2973. _("Selected GCode file extensions registered with FlatCAM."))
  2974. if obj_type is None or obj_type == 'gerber':
  2975. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2976. grb_list = [x for x in grb_list if x != '']
  2977. # register all keys in the Preferences window
  2978. for ext in grb_list:
  2979. new_k = new_reg_path + '.%s' % ext
  2980. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2981. # and unregister those that are no longer in the Preferences windows but are in the file
  2982. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2983. if ext not in grb_list:
  2984. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2985. # now write the updated extensions to the self.defaults
  2986. # new_ext = ''
  2987. # for ext in grb_list:
  2988. # new_ext = new_ext + ext + ', '
  2989. # self.defaults["fa_gerber"] = new_ext
  2990. self.inform.emit('[success] %s' %
  2991. _("Selected Gerber file extensions registered with FlatCAM."))
  2992. def add_extension(self, ext_type):
  2993. """
  2994. Add a file extension to the list for a specific object
  2995. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2996. :return:
  2997. """
  2998. if ext_type == 'excellon':
  2999. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3000. if new_ext == '':
  3001. return
  3002. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3003. if new_ext in old_val:
  3004. return
  3005. old_val.append(new_ext)
  3006. old_val.sort()
  3007. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3008. if ext_type == 'gcode':
  3009. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3010. if new_ext == '':
  3011. return
  3012. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3013. if new_ext in old_val:
  3014. return
  3015. old_val.append(new_ext)
  3016. old_val.sort()
  3017. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3018. if ext_type == 'gerber':
  3019. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3020. if new_ext == '':
  3021. return
  3022. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3023. if new_ext in old_val:
  3024. return
  3025. old_val.append(new_ext)
  3026. old_val.sort()
  3027. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3028. if ext_type == 'keyword':
  3029. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3030. if new_kw == '':
  3031. return
  3032. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3033. if new_kw in old_val:
  3034. return
  3035. old_val.append(new_kw)
  3036. old_val.sort()
  3037. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3038. # update the self.myKeywords so the model is updated
  3039. self.autocomplete_kw_list = \
  3040. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3041. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3042. self.shell._edit.set_model_data(self.myKeywords)
  3043. def del_extension(self, ext_type):
  3044. """
  3045. Remove a file extension from the list for a specific object
  3046. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3047. :return:
  3048. """
  3049. if ext_type == 'excellon':
  3050. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3051. if new_ext == '':
  3052. return
  3053. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3054. if new_ext not in old_val:
  3055. return
  3056. old_val.remove(new_ext)
  3057. old_val.sort()
  3058. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3059. if ext_type == 'gcode':
  3060. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3061. if new_ext == '':
  3062. return
  3063. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3064. if new_ext not in old_val:
  3065. return
  3066. old_val.remove(new_ext)
  3067. old_val.sort()
  3068. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3069. if ext_type == 'gerber':
  3070. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3071. if new_ext == '':
  3072. return
  3073. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3074. if new_ext not in old_val:
  3075. return
  3076. old_val.remove(new_ext)
  3077. old_val.sort()
  3078. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3079. if ext_type == 'keyword':
  3080. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3081. if new_kw == '':
  3082. return
  3083. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3084. if new_kw not in old_val:
  3085. return
  3086. old_val.remove(new_kw)
  3087. old_val.sort()
  3088. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3089. # update the self.myKeywords so the model is updated
  3090. self.autocomplete_kw_list = \
  3091. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3092. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3093. self.shell._edit.set_model_data(self.myKeywords)
  3094. def restore_extensions(self, ext_type):
  3095. """
  3096. Restore all file extensions associations with FlatCAM, for a specific object
  3097. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3098. :return:
  3099. """
  3100. if ext_type == 'excellon':
  3101. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3102. # for the ability to open Excellon files with .txt extension
  3103. new_exc_list = deepcopy(self.exc_list)
  3104. try:
  3105. new_exc_list.remove('txt')
  3106. except ValueError:
  3107. pass
  3108. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3109. if ext_type == 'gcode':
  3110. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3111. if ext_type == 'gerber':
  3112. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3113. if ext_type == 'keyword':
  3114. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3115. # update the self.myKeywords so the model is updated
  3116. self.autocomplete_kw_list = self.default_keywords
  3117. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3118. self.shell._edit.set_model_data(self.myKeywords)
  3119. def delete_all_extensions(self, ext_type):
  3120. """
  3121. Delete all file extensions associations with FlatCAM, for a specific object
  3122. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3123. :return:
  3124. """
  3125. if ext_type == 'excellon':
  3126. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3127. if ext_type == 'gcode':
  3128. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3129. if ext_type == 'gerber':
  3130. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3131. if ext_type == 'keyword':
  3132. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3133. # update the self.myKeywords so the model is updated
  3134. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3135. self.shell._edit.set_model_data(self.myKeywords)
  3136. def on_edit_join(self, name=None):
  3137. """
  3138. Callback for Edit->Join. Joins the selected geometry objects into
  3139. a new one.
  3140. :return: None
  3141. """
  3142. self.defaults.report_usage("on_edit_join()")
  3143. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3144. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3145. geo_type_set = set()
  3146. objs = self.collection.get_selected()
  3147. if len(objs) < 2:
  3148. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3149. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3150. return 'fail'
  3151. for obj in objs:
  3152. geo_type_set.add(obj.multigeo)
  3153. # if len(geo_type_list) == 1 means that all list elements are the same
  3154. if len(geo_type_set) != 1:
  3155. self.inform.emit('[ERROR] %s' %
  3156. _("Failed join. The Geometry objects are of different types.\n"
  3157. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3158. "convert from one to another and retry joining \n"
  3159. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3160. "the result may not be what was expected. \n"
  3161. "Check the generated GCODE."))
  3162. return
  3163. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3164. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3165. if True in geo_type_set:
  3166. def initialize(geo_obj, app):
  3167. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3168. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3169. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3170. for v in geo_obj.tools.values():
  3171. v['data']['name'] = obj_name_multi
  3172. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3173. else:
  3174. def initialize(geo_obj, app):
  3175. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3176. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3177. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3178. for v in geo_obj.tools.values():
  3179. v['data']['name'] = obj_name_single
  3180. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3181. self.should_we_save = True
  3182. def on_edit_join_exc(self):
  3183. """
  3184. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3185. a new Excellon.
  3186. :return: None
  3187. """
  3188. self.defaults.report_usage("on_edit_join_exc()")
  3189. objs = self.collection.get_selected()
  3190. for obj in objs:
  3191. if not isinstance(obj, ExcellonObject):
  3192. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3193. return
  3194. if len(objs) < 2:
  3195. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3196. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3197. return 'fail'
  3198. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3199. def initialize(exc_obj, app):
  3200. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3201. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3202. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3203. self.should_we_save = True
  3204. def on_edit_join_grb(self):
  3205. """
  3206. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3207. a new Gerber object.
  3208. :return: None
  3209. """
  3210. self.defaults.report_usage("on_edit_join_grb()")
  3211. objs = self.collection.get_selected()
  3212. for obj in objs:
  3213. if not isinstance(obj, GerberObject):
  3214. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3215. return
  3216. if len(objs) < 2:
  3217. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3218. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3219. return 'fail'
  3220. def initialize(grb_obj, app):
  3221. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3222. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3223. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3224. self.should_we_save = True
  3225. def on_convert_singlegeo_to_multigeo(self):
  3226. """
  3227. Called for converting a Geometry object from single-geo to multi-geo.
  3228. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3229. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3230. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3231. the solid-geometry of that tool.
  3232. :return: None
  3233. """
  3234. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3235. obj = self.collection.get_active()
  3236. if obj is None:
  3237. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3238. return
  3239. if not isinstance(obj, GeometryObject):
  3240. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3241. return
  3242. obj.multigeo = True
  3243. for tooluid, dict_value in obj.tools.items():
  3244. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3245. if not isinstance(obj.solid_geometry, list):
  3246. obj.solid_geometry = [obj.solid_geometry]
  3247. # obj.solid_geometry[:] = []
  3248. obj.plot()
  3249. self.should_we_save = True
  3250. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3251. def on_convert_multigeo_to_singlegeo(self):
  3252. """
  3253. Called for converting a Geometry object from multi-geo to single-geo.
  3254. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3255. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3256. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3257. the solid-geometry of that tool.
  3258. :return: None
  3259. """
  3260. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3261. obj = self.collection.get_active()
  3262. if obj is None:
  3263. self.inform.emit('[ERROR_NOTCL] %s' %
  3264. _("Failed. Select a Geometry Object and try again."))
  3265. return
  3266. if not isinstance(obj, GeometryObject):
  3267. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3268. (_("Expected a GeometryObject, got"), type(obj)))
  3269. return
  3270. obj.multigeo = False
  3271. total_solid_geometry = []
  3272. for tooluid, dict_value in obj.tools.items():
  3273. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3274. # clear the original geometry
  3275. dict_value['solid_geometry'][:] = []
  3276. obj.solid_geometry = deepcopy(total_solid_geometry)
  3277. obj.plot()
  3278. self.should_we_save = True
  3279. self.inform.emit('[success] %s' %
  3280. _("A Geometry object was converted to SingleGeo type."))
  3281. def on_defaults_dict_change(self, field):
  3282. """
  3283. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3284. Edit -> Preferences tab window.
  3285. :param field: the key of the self.defaults dictionary that was changed.
  3286. :return: None
  3287. """
  3288. self.preferencesUiManager.defaults_write_form_field(field=field)
  3289. if field == "units":
  3290. self.set_screen_units(self.defaults['units'])
  3291. def set_screen_units(self, units):
  3292. """
  3293. Set the FlatCAM units on the status bar.
  3294. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3295. :return: None
  3296. """
  3297. self.ui.units_label.setText("[" + units.lower() + "]")
  3298. def on_toggle_units_click(self):
  3299. try:
  3300. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3301. except (TypeError, AttributeError):
  3302. pass
  3303. if self.defaults["units"] == 'MM':
  3304. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3305. else:
  3306. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3307. self.on_toggle_units(no_pref=True)
  3308. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3309. lambda: self.on_toggle_units(no_pref=False))
  3310. def on_toggle_units(self, no_pref=False):
  3311. """
  3312. Callback for the Units radio-button change in the Preferences tab.
  3313. Changes the application's default units adn for the project too.
  3314. If changing the project's units, the change propagates to all of
  3315. the objects in the project.
  3316. :return: None
  3317. """
  3318. self.defaults.report_usage("on_toggle_units")
  3319. if self.toggle_units_ignore:
  3320. return
  3321. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3322. # If option is the same, then ignore
  3323. if new_units == self.defaults["units"].upper():
  3324. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3325. return
  3326. # Keys in self.defaults for which to scale their values
  3327. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3328. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3329. "tools_iso_tool_vtipdia",
  3330. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3331. "gerber_editor_ma_high",
  3332. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3333. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3334. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3335. "excellon_feedrate_probe", "excellon_milling_dia",
  3336. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3337. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3338. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3339. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3340. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3341. "geometry_extracut_length", "geometry_z_pdepth",
  3342. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3343. 'cncjob_tooldia',
  3344. 'tools_paintoffset', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3345. "tools_paintnewdia",
  3346. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3347. "tools_nccnewdia", "tools_ncc_offset_value",
  3348. "tools_2sided_drilldia",
  3349. "tools_film_boundary", "tools_film_scale_stroke",
  3350. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3351. "tools_cutout_depthperpass",
  3352. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3353. "tools_panelize_spacing_rows",
  3354. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3355. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3356. "tools_transform_buffer_dis",
  3357. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3358. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3359. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3360. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3361. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3362. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3363. "tools_cr_h2h_val", "tools_cr_dh_val",
  3364. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3365. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3366. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3367. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3368. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3369. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3370. "tools_copper_thieving_mask_clearance",
  3371. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3372. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3373. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3374. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3375. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3376. "tools_invert_margin",
  3377. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3378. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3379. def scale_defaults(sfactor):
  3380. for dim in dimensions:
  3381. if dim in [
  3382. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3383. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3384. 'tools_transform_mirror_point'
  3385. ]:
  3386. if self.defaults[dim] is None or self.defaults[dim] == '':
  3387. continue
  3388. try:
  3389. coordinates = self.defaults[dim].split(",")
  3390. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3391. coords_xy[0] *= sfactor
  3392. coords_xy[1] *= sfactor
  3393. self.defaults[dim] = "%.*f, %.*f" % (
  3394. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3395. except Exception as e:
  3396. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3397. elif dim in [
  3398. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3399. ]:
  3400. if self.defaults[dim] is None or self.defaults[dim] == '':
  3401. continue
  3402. try:
  3403. self.defaults[dim] = float(self.defaults[dim])
  3404. tools_diameters = [self.defaults[dim]]
  3405. except ValueError:
  3406. try:
  3407. tools_string = self.defaults[dim].split(",")
  3408. tools_diameters = [eval(a) for a in tools_string if a != '']
  3409. except Exception as e:
  3410. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3411. continue
  3412. self.defaults[dim] = ''
  3413. td_len = len(tools_diameters)
  3414. if td_len > 1:
  3415. for t in range(td_len):
  3416. tools_diameters[t] *= sfactor
  3417. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3418. else:
  3419. tools_diameters[0] *= sfactor
  3420. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3421. elif dim in ['global_gridx', 'global_gridy']:
  3422. # format the number of decimals to the one specified in self.decimals
  3423. try:
  3424. val = float(self.defaults[dim]) * sfactor
  3425. except Exception as e:
  3426. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3427. continue
  3428. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3429. else:
  3430. # the number of decimals for the rest is kept unchanged
  3431. if self.defaults[dim]:
  3432. try:
  3433. val = float(self.defaults[dim]) * sfactor
  3434. except Exception as e:
  3435. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3436. continue
  3437. self.defaults[dim] = val
  3438. # The scaling factor depending on choice of units.
  3439. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3440. # Changing project units. Warn user.
  3441. msgbox = QtWidgets.QMessageBox()
  3442. msgbox.setWindowTitle(_("Toggle Units"))
  3443. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3444. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3445. msgbox.setText(_("Changing the units of the project\n"
  3446. "will scale all objects.\n\n"
  3447. "Do you want to continue?"))
  3448. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3449. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3450. msgbox.setDefaultButton(bt_ok)
  3451. msgbox.exec_()
  3452. response = msgbox.clickedButton()
  3453. if response == bt_ok:
  3454. if no_pref is False:
  3455. self.preferencesUiManager.defaults_read_form()
  3456. scale_defaults(factor)
  3457. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3458. self.defaults["units"] = new_units
  3459. # update the defaults from form, some may assume that the conversion is enough and it's not
  3460. self.on_options_app2project()
  3461. # update the objects
  3462. for obj in self.collection.get_list():
  3463. obj.convert_units(new_units)
  3464. # make that the properties stored in the object are also updated
  3465. self.app_obj.object_changed.emit(obj)
  3466. # rebuild the object UI
  3467. obj.build_ui()
  3468. # change this only if the workspace is active
  3469. if self.defaults['global_workspace'] is True:
  3470. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3471. # adjust the grid values on the main toolbar
  3472. val_x = float(self.defaults['global_gridx']) * factor
  3473. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3474. current = self.collection.get_active()
  3475. if current is not None:
  3476. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3477. if not isinstance(current, GeometryObject):
  3478. current.to_form()
  3479. # replot all objects
  3480. self.plot_all()
  3481. # set the status labels to reflect the current FlatCAM units
  3482. self.set_screen_units(new_units)
  3483. # signal to the app that we changed the object properties and it should save the project
  3484. self.should_we_save = True
  3485. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3486. else:
  3487. # Undo toggling
  3488. self.toggle_units_ignore = True
  3489. if self.defaults['units'].upper() == 'MM':
  3490. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3491. else:
  3492. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3493. self.toggle_units_ignore = False
  3494. # store the grid values so they are not changed in the next step
  3495. val_x = float(self.defaults['global_gridx'])
  3496. val_y = float(self.defaults['global_gridy'])
  3497. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3498. self.preferencesUiManager.defaults_read_form()
  3499. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3500. # in self.defaults from the GUI elements but
  3501. # I don't want it for the grid values, so I update them here
  3502. self.defaults['global_gridx'] = val_x
  3503. self.defaults['global_gridy'] = val_y
  3504. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3505. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3506. def on_deselect_all(self):
  3507. self.collection.set_all_inactive()
  3508. self.delete_selection_shape()
  3509. def on_workspace_modified(self):
  3510. # self.save_defaults(silent=True)
  3511. self.plotcanvas.delete_workspace()
  3512. self.preferencesUiManager.defaults_read_form()
  3513. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3514. def on_workspace(self):
  3515. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3516. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3517. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3518. else:
  3519. self.plotcanvas.delete_workspace()
  3520. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3521. self.preferencesUiManager.defaults_read_form()
  3522. # self.save_defaults(silent=True)
  3523. def on_workspace_toggle(self):
  3524. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3525. try:
  3526. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3527. except TypeError:
  3528. pass
  3529. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3530. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3531. self.on_workspace()
  3532. def on_cursor_type(self, val):
  3533. """
  3534. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3535. :return: None
  3536. """
  3537. self.app_cursor.enabled = False
  3538. if val == 'small':
  3539. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3540. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3541. self.app_cursor = self.plotcanvas.new_cursor()
  3542. else:
  3543. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3544. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3545. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3546. if self.ui.grid_snap_btn.isChecked():
  3547. self.app_cursor.enabled = True
  3548. else:
  3549. self.app_cursor.enabled = False
  3550. def on_tool_add_keypress(self):
  3551. # ## Current application units in Upper Case
  3552. self.units = self.defaults['units'].upper()
  3553. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3554. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3555. if notebook_widget_name == 'selected_tab':
  3556. if self.collection.get_active().kind == 'geometry':
  3557. # Tool add works for Geometry only if Advanced is True in Preferences
  3558. if self.defaults["global_app_level"] == 'a':
  3559. tool_add_popup = FCInputDialog(title="New Tool ...",
  3560. text='Enter a Tool Diameter:',
  3561. min=0.0000, max=99.9999, decimals=4)
  3562. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3563. val, ok = tool_add_popup.get_value()
  3564. if ok:
  3565. if float(val) == 0:
  3566. self.inform.emit('[WARNING_NOTCL] %s' %
  3567. _("Please enter a tool diameter with non-zero value, in Float format."))
  3568. return
  3569. self.collection.get_active().on_tool_add(dia=float(val))
  3570. else:
  3571. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3572. else:
  3573. msgbox = QtWidgets.QMessageBox()
  3574. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3575. "Go to Preferences -> General - Show Advanced Options."))
  3576. msgbox.setWindowTitle("Tool adding ...")
  3577. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3578. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3579. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3580. msgbox.setDefaultButton(bt_ok)
  3581. msgbox.exec_()
  3582. # work only if the notebook tab on focus is the Tools_Tab
  3583. if notebook_widget_name == 'tool_tab':
  3584. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3585. # and only if the tool is NCC Tool
  3586. if tool_widget == self.ncclear_tool.toolName:
  3587. self.ncclear_tool.on_add_tool_by_key()
  3588. # and only if the tool is Paint Area Tool
  3589. elif tool_widget == self.paint_tool.toolName:
  3590. self.paint_tool.on_add_tool_by_key()
  3591. # and only if the tool is Solder Paste Dispensing Tool
  3592. elif tool_widget == self.paste_tool.toolName:
  3593. self.paste_tool.on_add_tool_by_key()
  3594. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3595. # See description below.
  3596. def on_delete_keypress(self):
  3597. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3598. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3599. if notebook_widget_name == 'selected_tab':
  3600. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3601. self.collection.get_active().on_tool_delete()
  3602. # work only if the notebook tab on focus is the Tools_Tab
  3603. elif notebook_widget_name == 'tool_tab':
  3604. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3605. # and only if the tool is NCC Tool
  3606. if tool_widget == self.ncclear_tool.toolName:
  3607. self.ncclear_tool.on_tool_delete()
  3608. # and only if the tool is Paint Tool
  3609. elif tool_widget == self.paint_tool.toolName:
  3610. self.paint_tool.on_tool_delete()
  3611. # and only if the tool is Solder Paste Dispensing Tool
  3612. elif tool_widget == self.paste_tool.toolName:
  3613. self.paste_tool.on_tool_delete()
  3614. # and only if the tool is Isolation Tool
  3615. elif tool_widget == self.isolation_tool.toolName:
  3616. self.isolation_tool.on_tool_delete()
  3617. else:
  3618. self.on_delete()
  3619. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3620. # some screens you have to be careful where you hover with your mouse.
  3621. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3622. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3623. # Complicated, I know :)
  3624. def on_delete(self, force_deletion=False):
  3625. """
  3626. Delete the currently selected FlatCAMObjs.
  3627. :param force_deletion: used by Tcl command
  3628. :return: None
  3629. """
  3630. self.defaults.report_usage("on_delete()")
  3631. response = None
  3632. bt_ok = None
  3633. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3634. # a geometry object before we update it.
  3635. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3636. and self.grb_editor.editor_active is False:
  3637. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3638. msgbox = QtWidgets.QMessageBox()
  3639. msgbox.setWindowTitle(_("Delete objects"))
  3640. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3641. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3642. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3643. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3644. "the selected objects?"))
  3645. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3646. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3647. msgbox.setDefaultButton(bt_ok)
  3648. msgbox.exec_()
  3649. response = msgbox.clickedButton()
  3650. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3651. response = bt_ok
  3652. if response == bt_ok:
  3653. if self.collection.get_active():
  3654. self.log.debug("App.on_delete()")
  3655. for obj_active in self.collection.get_selected():
  3656. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3657. if obj_active.kind == 'gerber':
  3658. for el in obj_active.mark_shapes:
  3659. obj_active.mark_shapes[el].clear(update=True)
  3660. obj_active.mark_shapes[el].enabled = False
  3661. # obj_active.mark_shapes[el] = None
  3662. del el
  3663. elif obj_active.kind == 'cncjob':
  3664. try:
  3665. obj_active.text_col.enabled = False
  3666. del obj_active.text_col
  3667. obj_active.annotation.clear(update=True)
  3668. del obj_active.annotation
  3669. except AttributeError as e:
  3670. log.debug(
  3671. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3672. )
  3673. while self.collection.get_selected():
  3674. self.delete_first_selected()
  3675. # make sure that the selection shape is deleted, too
  3676. self.delete_selection_shape()
  3677. # if there are no longer objects delete also the exclusion areas shapes
  3678. if not self.collection.get_list():
  3679. self.exc_areas.clear_shapes()
  3680. self.inform.emit('%s...' % _("Object(s) deleted"))
  3681. else:
  3682. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3683. else:
  3684. self.inform.emit(_("Save the work in Editor and try again ..."))
  3685. def delete_first_selected(self):
  3686. # Keep this for later
  3687. try:
  3688. sel_obj = self.collection.get_active()
  3689. name = sel_obj.options["name"]
  3690. isPlotted = sel_obj.options["plot"]
  3691. except AttributeError:
  3692. self.log.debug("Nothing selected for deletion")
  3693. return
  3694. if self.is_legacy is True:
  3695. # Remove plot only if the object was plotted otherwise delaxes will fail
  3696. if isPlotted:
  3697. try:
  3698. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3699. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3700. except Exception as e:
  3701. log.debug("App.delete_first_selected() --> %s" % str(e))
  3702. self.plotcanvas.auto_adjust_axes()
  3703. # Remove from dictionary
  3704. self.collection.delete_active()
  3705. # Clear form
  3706. self.setup_component_editor()
  3707. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3708. def on_set_origin(self):
  3709. """
  3710. Set the origin to the left mouse click position
  3711. :return: None
  3712. """
  3713. # display the message for the user
  3714. # and ask him to click on the desired position
  3715. self.defaults.report_usage("on_set_origin()")
  3716. def origin_replot():
  3717. def worker_task():
  3718. with self.proc_container.new('%s...' % _("Plotting")):
  3719. for obj in self.collection.get_list():
  3720. obj.plot()
  3721. self.plotcanvas.fit_view()
  3722. if self.is_legacy:
  3723. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3724. else:
  3725. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3726. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3727. self.inform.emit(_('Click to set the origin ...'))
  3728. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3729. # first disconnect it as it may have been used by something else
  3730. try:
  3731. self.replot_signal.disconnect()
  3732. except TypeError:
  3733. pass
  3734. self.replot_signal[list].connect(origin_replot)
  3735. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3736. """
  3737. :param event:
  3738. :param location:
  3739. :param noplot:
  3740. :param use_thread:
  3741. :return:
  3742. """
  3743. noplot_sig = noplot
  3744. def worker_task():
  3745. with self.proc_container.new(_("Setting Origin...")):
  3746. obj_list = self.collection.get_list()
  3747. for obj in obj_list:
  3748. obj.offset((x, y))
  3749. self.app_obj.object_changed.emit(obj)
  3750. # Update the object bounding box options
  3751. a, b, c, d = obj.bounds()
  3752. obj.options['xmin'] = a
  3753. obj.options['ymin'] = b
  3754. obj.options['xmax'] = c
  3755. obj.options['ymax'] = d
  3756. self.inform.emit('[success] %s...' % _('Origin set'))
  3757. for obj in obj_list:
  3758. out_name = obj.options["name"]
  3759. if obj.kind == 'gerber':
  3760. obj.source_file = self.export_gerber(
  3761. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3762. elif obj.kind == 'excellon':
  3763. obj.source_file = self.export_excellon(
  3764. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3765. if noplot_sig is False:
  3766. self.replot_signal.emit([])
  3767. if location is not None:
  3768. if len(location) != 2:
  3769. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3770. return 'fail'
  3771. x, y = location
  3772. if use_thread is True:
  3773. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3774. else:
  3775. worker_task()
  3776. self.should_we_save = True
  3777. return
  3778. if event is not None and event.button == 1:
  3779. if self.is_legacy is False:
  3780. event_pos = event.pos
  3781. else:
  3782. event_pos = (event.xdata, event.ydata)
  3783. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3784. if self.grid_status():
  3785. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3786. else:
  3787. pos = pos_canvas
  3788. x = 0 - pos[0]
  3789. y = 0 - pos[1]
  3790. if use_thread is True:
  3791. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3792. else:
  3793. worker_task()
  3794. self.should_we_save = True
  3795. def on_move2origin(self, use_thread=True):
  3796. """
  3797. Move selected objects to origin.
  3798. :param use_thread: Control if to use threaded operation. Boolean.
  3799. :return:
  3800. """
  3801. def worker_task():
  3802. with self.proc_container.new(_("Moving to Origin...")):
  3803. obj_list = self.collection.get_selected()
  3804. if not obj_list:
  3805. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3806. return
  3807. xminlist = []
  3808. yminlist = []
  3809. # first get a bounding box to fit all
  3810. for obj in obj_list:
  3811. xmin, ymin, xmax, ymax = obj.bounds()
  3812. xminlist.append(xmin)
  3813. yminlist.append(ymin)
  3814. # get the minimum x,y for all objects selected
  3815. x = min(xminlist)
  3816. y = min(yminlist)
  3817. for obj in obj_list:
  3818. obj.offset((-x, -y))
  3819. self.app_obj.object_changed.emit(obj)
  3820. # Update the object bounding box options
  3821. a, b, c, d = obj.bounds()
  3822. obj.options['xmin'] = a
  3823. obj.options['ymin'] = b
  3824. obj.options['xmax'] = c
  3825. obj.options['ymax'] = d
  3826. for obj in obj_list:
  3827. obj.plot()
  3828. for obj in obj_list:
  3829. out_name = obj.options["name"]
  3830. if obj.kind == 'gerber':
  3831. obj.source_file = self.export_gerber(
  3832. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3833. elif obj.kind == 'excellon':
  3834. obj.source_file = self.export_excellon(
  3835. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3836. self.inform.emit('[success] %s...' % _('Origin set'))
  3837. if use_thread is True:
  3838. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3839. else:
  3840. worker_task()
  3841. self.should_we_save = True
  3842. def on_jump_to(self, custom_location=None, fit_center=True):
  3843. """
  3844. Jump to a location by setting the mouse cursor location.
  3845. :param custom_location: Jump to a specified point. (x, y) tuple.
  3846. :param fit_center: If to fit view. Boolean.
  3847. :return:
  3848. """
  3849. self.defaults.report_usage("on_jump_to()")
  3850. if not custom_location:
  3851. dia_box_location = None
  3852. try:
  3853. dia_box_location = eval(self.clipboard.text())
  3854. except Exception:
  3855. pass
  3856. if type(dia_box_location) == tuple:
  3857. dia_box_location = str(dia_box_location)
  3858. else:
  3859. dia_box_location = None
  3860. # dia_box = Dialog_box(title=_("Jump to ..."),
  3861. # label=_("Enter the coordinates in format X,Y:"),
  3862. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3863. # initial_text=dia_box_location)
  3864. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3865. label=_("Enter the coordinates in format X,Y:"),
  3866. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3867. initial_text=dia_box_location,
  3868. reference=self.defaults['global_jump_ref'])
  3869. if dia_box.ok is True:
  3870. try:
  3871. location = eval(dia_box.location)
  3872. if not isinstance(location, tuple):
  3873. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3874. return
  3875. if dia_box.reference == 'rel':
  3876. rel_x = self.mouse[0] + location[0]
  3877. rel_y = self.mouse[1] + location[1]
  3878. location = (rel_x, rel_y)
  3879. self.defaults['global_jump_ref'] = dia_box.reference
  3880. except Exception:
  3881. return
  3882. else:
  3883. return
  3884. else:
  3885. location = custom_location
  3886. self.jump_signal.emit(location)
  3887. if fit_center:
  3888. self.plotcanvas.fit_center(loc=location)
  3889. cursor = QtGui.QCursor()
  3890. if self.is_legacy is False:
  3891. # I don't know where those differences come from but they are constant for the current
  3892. # execution of the application and they are multiples of a value around 0.0263mm.
  3893. # In a random way sometimes they are more sometimes they are less
  3894. # if units == 'MM':
  3895. # cal_factor = 0.0263
  3896. # else:
  3897. # cal_factor = 0.0263 / 25.4
  3898. cal_location = (location[0], location[1])
  3899. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3900. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3901. j_pos = (
  3902. int(canvas_origin.x() + round(jump_loc[0])),
  3903. int(canvas_origin.y() + round(jump_loc[1]))
  3904. )
  3905. cursor.setPos(j_pos[0], j_pos[1])
  3906. else:
  3907. # find the canvas origin which is in the top left corner
  3908. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3909. # determine the coordinates for the lowest left point of the canvas
  3910. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3911. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3912. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3913. # canvas) and the point (width, height) is in the top-right location
  3914. loc = self.plotcanvas.axes.transData.transform_point(location)
  3915. j_pos = (
  3916. int(x0 + loc[0]),
  3917. int(y0 - loc[1])
  3918. )
  3919. cursor.setPos(j_pos[0], j_pos[1])
  3920. self.plotcanvas.mouse = [location[0], location[1]]
  3921. if self.defaults["global_cursor_color_enabled"] is True:
  3922. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3923. else:
  3924. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3925. if self.grid_status():
  3926. # Update cursor
  3927. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3928. symbol='++', edge_color=self.cursor_color_3D,
  3929. edge_width=self.defaults["global_cursor_width"],
  3930. size=self.defaults["global_cursor_size"])
  3931. # Set the relative position label
  3932. dx = location[0] - float(self.rel_point1[0])
  3933. dy = location[1] - float(self.rel_point1[1])
  3934. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3935. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3936. # Set the position label
  3937. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3938. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3939. units = self.defaults["units"].lower()
  3940. self.plotcanvas.text_hud.text = \
  3941. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3942. dx, units, dy, units, location[0], units, location[1], units)
  3943. self.inform.emit('[success] %s' % _("Done."))
  3944. return location
  3945. def on_locate(self, obj, fit_center=True):
  3946. """
  3947. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3948. :param obj: The object on which to locate certain points
  3949. :param fit_center: If to fit view. Boolean.
  3950. :return: A point location. (x, y) tuple.
  3951. """
  3952. self.defaults.report_usage("on_locate()")
  3953. if obj is None:
  3954. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3955. return 'fail'
  3956. class DialogBoxChoice(QtWidgets.QDialog):
  3957. def __init__(self, title=None, icon=None, choice='bl'):
  3958. """
  3959. :param title: string with the window title
  3960. """
  3961. super(DialogBoxChoice, self).__init__()
  3962. self.ok = False
  3963. self.setWindowIcon(icon)
  3964. self.setWindowTitle(str(title))
  3965. self.form = QtWidgets.QFormLayout(self)
  3966. self.ref_radio = RadioSet([
  3967. {"label": _("Bottom-Left"), "value": "bl"},
  3968. {"label": _("Top-Left"), "value": "tl"},
  3969. {"label": _("Bottom-Right"), "value": "br"},
  3970. {"label": _("Top-Right"), "value": "tr"},
  3971. {"label": _("Center"), "value": "c"}
  3972. ], orientation='vertical', stretch=False)
  3973. self.ref_radio.set_value(choice)
  3974. self.form.addRow(self.ref_radio)
  3975. self.button_box = QtWidgets.QDialogButtonBox(
  3976. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3977. Qt.Horizontal, parent=self)
  3978. self.form.addRow(self.button_box)
  3979. self.button_box.accepted.connect(self.accept)
  3980. self.button_box.rejected.connect(self.reject)
  3981. if self.exec_() == QtWidgets.QDialog.Accepted:
  3982. self.ok = True
  3983. self.location_point = self.ref_radio.get_value()
  3984. else:
  3985. self.ok = False
  3986. self.location_point = None
  3987. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3988. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3989. choice=self.defaults['global_locate_pt'])
  3990. if dia_box.ok is True:
  3991. try:
  3992. location_point = dia_box.location_point
  3993. self.defaults['global_locate_pt'] = dia_box.location_point
  3994. except Exception:
  3995. return
  3996. else:
  3997. return
  3998. loc_b = obj.bounds()
  3999. if location_point == 'bl':
  4000. location = (loc_b[0], loc_b[1])
  4001. elif location_point == 'tl':
  4002. location = (loc_b[0], loc_b[3])
  4003. elif location_point == 'br':
  4004. location = (loc_b[2], loc_b[1])
  4005. elif location_point == 'tr':
  4006. location = (loc_b[2], loc_b[3])
  4007. else:
  4008. # center
  4009. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4010. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4011. location = (cx, cy)
  4012. self.locate_signal.emit(location, location_point)
  4013. if fit_center:
  4014. self.plotcanvas.fit_center(loc=location)
  4015. cursor = QtGui.QCursor()
  4016. if self.is_legacy is False:
  4017. # I don't know where those differences come from but they are constant for the current
  4018. # execution of the application and they are multiples of a value around 0.0263mm.
  4019. # In a random way sometimes they are more sometimes they are less
  4020. # if units == 'MM':
  4021. # cal_factor = 0.0263
  4022. # else:
  4023. # cal_factor = 0.0263 / 25.4
  4024. cal_location = (location[0], location[1])
  4025. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4026. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4027. j_pos = (
  4028. int(canvas_origin.x() + round(jump_loc[0])),
  4029. int(canvas_origin.y() + round(jump_loc[1]))
  4030. )
  4031. cursor.setPos(j_pos[0], j_pos[1])
  4032. else:
  4033. # find the canvas origin which is in the top left corner
  4034. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4035. # determine the coordinates for the lowest left point of the canvas
  4036. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4037. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4038. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4039. # canvas) and the point (width, height) is in the top-right location
  4040. loc = self.plotcanvas.axes.transData.transform_point(location)
  4041. j_pos = (
  4042. int(x0 + loc[0]),
  4043. int(y0 - loc[1])
  4044. )
  4045. cursor.setPos(j_pos[0], j_pos[1])
  4046. self.plotcanvas.mouse = [location[0], location[1]]
  4047. if self.defaults["global_cursor_color_enabled"] is True:
  4048. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4049. else:
  4050. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4051. if self.grid_status():
  4052. # Update cursor
  4053. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4054. symbol='++', edge_color=self.cursor_color_3D,
  4055. edge_width=self.defaults["global_cursor_width"],
  4056. size=self.defaults["global_cursor_size"])
  4057. # Set the relative position label
  4058. self.dx = location[0] - float(self.rel_point1[0])
  4059. self.dy = location[1] - float(self.rel_point1[1])
  4060. # Set the position label
  4061. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4062. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4063. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4064. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4065. units = self.defaults["units"].lower()
  4066. self.plotcanvas.text_hud.text = \
  4067. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4068. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4069. self.inform.emit('[success] %s' % _("Done."))
  4070. return location
  4071. def on_copy_command(self):
  4072. """
  4073. Will copy a selection of objects, creating new objects.
  4074. :return:
  4075. """
  4076. self.defaults.report_usage("on_copy_command()")
  4077. def initialize(obj_init, app):
  4078. """
  4079. :param obj_init: the new object
  4080. :type obj_init: class
  4081. :param app: An instance of the App class
  4082. :type app: App
  4083. :return: None
  4084. :rtype:
  4085. """
  4086. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4087. try:
  4088. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4089. except AttributeError:
  4090. pass
  4091. try:
  4092. obj_init.apertures = deepcopy(obj.apertures)
  4093. except AttributeError:
  4094. pass
  4095. try:
  4096. if obj.tools:
  4097. obj_init.tools = deepcopy(obj.tools)
  4098. except Exception as err:
  4099. log.debug("App.on_copy_command() --> %s" % str(err))
  4100. try:
  4101. obj_init.source_file = deepcopy(obj.source_file)
  4102. except (AttributeError, TypeError):
  4103. pass
  4104. def initialize_excellon(obj_init, app):
  4105. obj_init.source_file = deepcopy(obj.source_file)
  4106. obj_init.tools = deepcopy(obj.tools)
  4107. # drills are offset, so they need to be deep copied
  4108. obj_init.drills = deepcopy(obj.drills)
  4109. # slots are offset, so they need to be deep copied
  4110. obj_init.slots = deepcopy(obj.slots)
  4111. obj_init.create_geometry()
  4112. def initialize_script(obj_init, app_obj):
  4113. obj_init.source_file = deepcopy(obj.source_file)
  4114. def initialize_document(obj_init, app_obj):
  4115. obj_init.source_file = deepcopy(obj.source_file)
  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("excellon", str(obj_name) + "_copy", initialize_excellon)
  4121. elif isinstance(obj, GerberObject):
  4122. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4123. elif isinstance(obj, GeometryObject):
  4124. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4125. elif isinstance(obj, ScriptObject):
  4126. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4127. elif isinstance(obj, DocumentObject):
  4128. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4129. except Exception as e:
  4130. return "Operation failed: %s" % str(e)
  4131. def on_copy_object2(self, custom_name):
  4132. def initialize_geometry(obj_init, app):
  4133. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4134. try:
  4135. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4136. except AttributeError:
  4137. pass
  4138. try:
  4139. obj_init.apertures = deepcopy(obj.apertures)
  4140. except AttributeError:
  4141. pass
  4142. try:
  4143. if obj.tools:
  4144. obj_init.tools = deepcopy(obj.tools)
  4145. except Exception as ee:
  4146. log.debug("on_copy_object2() --> %s" % str(ee))
  4147. def initialize_gerber(obj_init, app):
  4148. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4149. obj_init.apertures = deepcopy(obj.apertures)
  4150. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4151. def initialize_excellon(obj_init, app):
  4152. obj_init.tools = deepcopy(obj.tools)
  4153. # drills are offset, so they need to be deep copied
  4154. obj_init.drills = deepcopy(obj.drills)
  4155. # slots are offset, so they need to be deep copied
  4156. obj_init.slots = deepcopy(obj.slots)
  4157. obj_init.create_geometry()
  4158. for obj in self.collection.get_selected():
  4159. obj_name = obj.options["name"]
  4160. try:
  4161. if isinstance(obj, ExcellonObject):
  4162. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4163. elif isinstance(obj, GerberObject):
  4164. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4165. elif isinstance(obj, GeometryObject):
  4166. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4167. except Exception as er:
  4168. return "Operation failed: %s" % str(er)
  4169. def on_rename_object(self, text):
  4170. """
  4171. Will rename an object.
  4172. :param text: New name for the object.
  4173. :return:
  4174. """
  4175. self.defaults.report_usage("on_rename_object()")
  4176. named_obj = self.collection.get_active()
  4177. for obj in named_obj:
  4178. if obj is list:
  4179. self.on_rename_object(text)
  4180. else:
  4181. try:
  4182. obj.options['name'] = text
  4183. except Exception as e:
  4184. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4185. def convert_any2geo(self):
  4186. """
  4187. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4188. :return:
  4189. """
  4190. self.defaults.report_usage("convert_any2geo()")
  4191. def initialize(obj_init, app):
  4192. obj_init.solid_geometry = obj.solid_geometry
  4193. try:
  4194. obj_init.follow_geometry = obj.follow_geometry
  4195. except AttributeError:
  4196. pass
  4197. try:
  4198. obj_init.apertures = obj.apertures
  4199. except AttributeError:
  4200. pass
  4201. try:
  4202. if obj.tools:
  4203. obj_init.tools = obj.tools
  4204. except AttributeError:
  4205. pass
  4206. def initialize_excellon(obj_init, app):
  4207. # objs = self.collection.get_selected()
  4208. # GeometryObject.merge(objs, obj)
  4209. solid_geo = []
  4210. for tool in obj.tools:
  4211. for geo in obj.tools[tool]['solid_geometry']:
  4212. solid_geo.append(geo)
  4213. obj_init.solid_geometry = deepcopy(solid_geo)
  4214. if not self.collection.get_selected():
  4215. log.warning("App.convert_any2geo --> No object selected")
  4216. self.inform.emit('[WARNING_NOTCL] %s' %
  4217. _("No object is selected. Select an object and try again."))
  4218. return
  4219. for obj in self.collection.get_selected():
  4220. obj_name = obj.options["name"]
  4221. try:
  4222. if obj.kind == 'excellon':
  4223. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4224. else:
  4225. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4226. except Exception as e:
  4227. return "Operation failed: %s" % str(e)
  4228. def convert_any2gerber(self):
  4229. """
  4230. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4231. :return:
  4232. """
  4233. def initialize_geometry(obj_init, app):
  4234. apertures = {}
  4235. apid = 0
  4236. apertures[str(apid)] = {}
  4237. apertures[str(apid)]['geometry'] = []
  4238. for obj_orig in obj.solid_geometry:
  4239. new_elem = {}
  4240. new_elem['solid'] = obj_orig
  4241. try:
  4242. new_elem['follow'] = obj_orig.exterior
  4243. except AttributeError:
  4244. pass
  4245. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4246. apertures[str(apid)]['size'] = 0.0
  4247. apertures[str(apid)]['type'] = 'C'
  4248. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4249. obj_init.apertures = deepcopy(apertures)
  4250. def initialize_excellon(obj_init, app):
  4251. apertures = {}
  4252. apid = 10
  4253. for tool in obj.tools:
  4254. apertures[str(apid)] = {}
  4255. apertures[str(apid)]['geometry'] = []
  4256. for geo in obj.tools[tool]['solid_geometry']:
  4257. new_el = {}
  4258. new_el['solid'] = geo
  4259. new_el['follow'] = geo.exterior
  4260. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4261. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4262. apertures[str(apid)]['type'] = 'C'
  4263. apid += 1
  4264. # create solid_geometry
  4265. solid_geometry = []
  4266. for apid in apertures:
  4267. for geo_el in apertures[apid]['geometry']:
  4268. solid_geometry.append(geo_el['solid'])
  4269. solid_geometry = MultiPolygon(solid_geometry)
  4270. solid_geometry = solid_geometry.buffer(0.0000001)
  4271. obj_init.solid_geometry = deepcopy(solid_geometry)
  4272. obj_init.apertures = deepcopy(apertures)
  4273. # clear the working objects (perhaps not necessary due of Python GC)
  4274. apertures.clear()
  4275. if not self.collection.get_selected():
  4276. log.warning("App.convert_any2gerber --> No object selected")
  4277. self.inform.emit('[WARNING_NOTCL] %s' %
  4278. _("No object is selected. Select an object and try again."))
  4279. return
  4280. for obj in self.collection.get_selected():
  4281. obj_name = obj.options["name"]
  4282. try:
  4283. if obj.kind == 'excellon':
  4284. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4285. elif obj.kind == 'geometry':
  4286. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4287. else:
  4288. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4289. except Exception as e:
  4290. return "Operation failed: %s" % str(e)
  4291. def convert_any2excellon(self):
  4292. """
  4293. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4294. :return:
  4295. """
  4296. def initialize_geometry(obj_init, app):
  4297. tools = {}
  4298. tooluid = 1
  4299. obj_init.solid_geometry = []
  4300. for geo in obj.solid_geometry:
  4301. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4302. continue
  4303. minx, miny, maxx, maxy = geo.bounds
  4304. new_dia = min([maxx-minx, maxy-miny])
  4305. new_drill = geo.centroid
  4306. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4307. current_tooldias = []
  4308. if tools:
  4309. for tool in tools:
  4310. if tools[tool] and 'tooldia' in tools[tool]:
  4311. current_tooldias.append(tools[tool]['tooldia'])
  4312. if new_dia in current_tooldias:
  4313. for tool in tools:
  4314. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float('%.*f' % (self.decimals,
  4315. new_dia)):
  4316. tools[tool]['drills'].append(new_drill)
  4317. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4318. else:
  4319. tools[tooluid] = {}
  4320. tools[tooluid]['tooldia'] = new_dia
  4321. tools[tooluid]['drills'] = [new_drill]
  4322. tools[tooluid]['slots'] = []
  4323. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4324. tooluid += 1
  4325. try:
  4326. obj_init.solid_geometry.append(new_drill_geo)
  4327. except (TypeError, AttributeError):
  4328. obj_init.solid_geometry = [new_drill_geo]
  4329. obj_init.tools = deepcopy(tools)
  4330. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4331. def initialize_gerber(obj_init, app):
  4332. tools = {}
  4333. tooluid = 1
  4334. obj_init.solid_geometry = []
  4335. for apid in obj.apertures:
  4336. if 'geometry' in obj.apertures[apid]:
  4337. for geo_dict in obj.apertures[apid]['geometry']:
  4338. if 'follow' in geo_dict:
  4339. if isinstance(geo_dict['follow'], Point):
  4340. geo = geo_dict['solid']
  4341. minx, miny, maxx, maxy = geo.bounds
  4342. new_dia = min([maxx - minx, maxy - miny])
  4343. new_drill = geo.centroid
  4344. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4345. current_tooldias = []
  4346. if tools:
  4347. for tool in tools:
  4348. if tools[tool] and 'tooldia' in tools[tool]:
  4349. current_tooldias.append(
  4350. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4351. )
  4352. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4353. for tool in tools:
  4354. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4355. '%.*f' % (self.decimals, new_dia)):
  4356. if new_drill not in tools[tool]['drills']:
  4357. tools[tool]['drills'].append(new_drill)
  4358. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4359. else:
  4360. tools[tooluid] = {}
  4361. tools[tooluid]['tooldia'] = new_dia
  4362. tools[tooluid]['drills'] = [new_drill]
  4363. tools[tooluid]['slots'] = []
  4364. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4365. tooluid += 1
  4366. try:
  4367. obj_init.solid_geometry.append(new_drill_geo)
  4368. except (TypeError, AttributeError):
  4369. obj_init.solid_geometry = [new_drill_geo]
  4370. elif isinstance(geo_dict['follow'], LineString):
  4371. geo_coords = list(geo_dict['follow'].coords)
  4372. # slots can have only a start and stop point and no intermediate points
  4373. if len(geo_coords) != 2:
  4374. continue
  4375. geo = geo_dict['solid']
  4376. try:
  4377. new_dia = obj.apertures[apid]['size']
  4378. except Exception:
  4379. continue
  4380. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4381. new_slot_geo = geo
  4382. current_tooldias = []
  4383. if tools:
  4384. for tool in tools:
  4385. if tools[tool] and 'tooldia' in tools[tool]:
  4386. current_tooldias.append(
  4387. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4388. )
  4389. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4390. for tool in tools:
  4391. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4392. '%.*f' % (self.decimals, new_dia)):
  4393. if new_slot not in tools[tool]['slots']:
  4394. tools[tool]['slots'].append(new_slot)
  4395. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4396. else:
  4397. tools[tooluid] = {}
  4398. tools[tooluid]['tooldia'] = new_dia
  4399. tools[tooluid]['drills'] = []
  4400. tools[tooluid]['slots'] = [new_slot]
  4401. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4402. tooluid += 1
  4403. try:
  4404. obj_init.solid_geometry.append(new_slot_geo)
  4405. except (TypeError, AttributeError):
  4406. obj_init.solid_geometry = [new_slot_geo]
  4407. obj_init.tools = deepcopy(tools)
  4408. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4409. if not self.collection.get_selected():
  4410. log.warning("App.convert_any2excellon--> No object selected")
  4411. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4412. return
  4413. for obj in self.collection.get_selected():
  4414. obj_name = obj.options["name"]
  4415. try:
  4416. if obj.kind == 'gerber':
  4417. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4418. elif obj.kind == 'geometry':
  4419. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4420. else:
  4421. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4422. except Exception as e:
  4423. return "Operation failed: %s" % str(e)
  4424. def abort_all_tasks(self):
  4425. """
  4426. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4427. on the first possible occasion.
  4428. :return:
  4429. """
  4430. if self.abort_flag is False:
  4431. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4432. self.abort_flag = True
  4433. self.cleanup.emit()
  4434. def app_is_idle(self):
  4435. if self.abort_flag:
  4436. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4437. self.abort_flag = False
  4438. def on_selectall(self):
  4439. """
  4440. Will draw a selection box shape around the selected objects.
  4441. :return:
  4442. """
  4443. self.defaults.report_usage("on_selectall()")
  4444. # delete the possible selection box around a possible selected object
  4445. self.delete_selection_shape()
  4446. for name in self.collection.get_names():
  4447. self.collection.set_active(name)
  4448. curr_sel_obj = self.collection.get_by_name(name)
  4449. # create the selection box around the selected object
  4450. if self.defaults['global_selection_shape'] is True:
  4451. self.draw_selection_shape(curr_sel_obj)
  4452. def on_toggle_preferences(self):
  4453. pref_open = False
  4454. for idx in range(self.ui.plot_tab_area.count()):
  4455. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4456. pref_open = True
  4457. if pref_open:
  4458. for idx in range(self.ui.plot_tab_area.count()):
  4459. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4460. self.ui.plot_tab_area.removeTab(idx)
  4461. break
  4462. self.ui.pref_status_label.setStyleSheet("")
  4463. else:
  4464. self.on_preferences()
  4465. def on_preferences(self):
  4466. """
  4467. Adds the Preferences in a Tab in Plot Area
  4468. :return:
  4469. """
  4470. # add the tab if it was closed
  4471. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4472. # delete the absolute and relative position and messages in the infobar
  4473. # self.ui.position_label.setText("")
  4474. # self.ui.rel_position_label.setText("")
  4475. # hide coordinates toolbars in the infobar while in DB
  4476. self.ui.coords_toolbar.hide()
  4477. self.ui.delta_coords_toolbar.hide()
  4478. # Switch plot_area to preferences page
  4479. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4480. # self.ui.show()
  4481. self.ui.pref_status_label.setStyleSheet("""
  4482. QLabel
  4483. {
  4484. color: black;
  4485. background-color: lightseagreen;
  4486. }
  4487. """
  4488. )
  4489. # detect changes in the preferences
  4490. for idx in range(self.ui.pref_tab_area.count()):
  4491. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4492. try:
  4493. try:
  4494. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4495. except (TypeError, AttributeError):
  4496. pass
  4497. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4498. except AttributeError:
  4499. pass
  4500. try:
  4501. try:
  4502. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4503. except (TypeError, AttributeError):
  4504. pass
  4505. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4506. except AttributeError:
  4507. pass
  4508. try:
  4509. try:
  4510. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4511. except (TypeError, AttributeError):
  4512. pass
  4513. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4514. except AttributeError:
  4515. pass
  4516. try:
  4517. try:
  4518. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4519. except (TypeError, AttributeError):
  4520. pass
  4521. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4522. except AttributeError:
  4523. pass
  4524. try:
  4525. try:
  4526. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4527. except (TypeError, AttributeError):
  4528. pass
  4529. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4530. except AttributeError:
  4531. pass
  4532. def on_tools_database(self, source='app'):
  4533. """
  4534. Adds the Tools Database in a Tab in Plot Area.
  4535. :return:
  4536. """
  4537. for idx in range(self.ui.plot_tab_area.count()):
  4538. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4539. # there can be only one instance of Tools Database at one time
  4540. return
  4541. if source == 'app':
  4542. self.tools_db_tab = ToolsDB2(
  4543. app=self,
  4544. parent=self.ui,
  4545. callback_on_edited=self.on_tools_db_edited,
  4546. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4547. )
  4548. elif source == 'ncc':
  4549. self.tools_db_tab = ToolsDB2(
  4550. app=self,
  4551. parent=self.ui,
  4552. callback_on_edited=self.on_tools_db_edited,
  4553. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4554. )
  4555. elif source == 'paint':
  4556. self.tools_db_tab = ToolsDB2(
  4557. app=self,
  4558. parent=self.ui,
  4559. callback_on_edited=self.on_tools_db_edited,
  4560. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4561. )
  4562. elif source == 'iso':
  4563. self.tools_db_tab = ToolsDB2(
  4564. app=self,
  4565. parent=self.ui,
  4566. callback_on_edited=self.on_tools_db_edited,
  4567. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4568. )
  4569. # add the tab if it was closed
  4570. try:
  4571. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4572. self.tools_db_tab.setObjectName("database_tab")
  4573. except Exception as e:
  4574. log.debug("App.on_tools_database() --> %s" % str(e))
  4575. return
  4576. # delete the absolute and relative position and messages in the infobar
  4577. # self.ui.position_label.setText("")
  4578. # self.ui.rel_position_label.setText("")
  4579. # hide coordinates toolbars in the infobar while in DB
  4580. self.ui.coords_toolbar.hide()
  4581. self.ui.delta_coords_toolbar.hide()
  4582. # Switch plot_area to preferences page
  4583. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4584. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4585. self.tools_db_tab.ui_connect()
  4586. def on_tools_db_edited(self):
  4587. """
  4588. Executed whenever a tool is edited in Tools Database.
  4589. Will color the text of the Tools Database tab to Red color.
  4590. :return:
  4591. """
  4592. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4593. for idx in range(self.ui.plot_tab_area.count()):
  4594. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4595. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4596. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4597. self.tools_db_changed_flag = True
  4598. def on_geometry_tool_add_from_db_executed(self, tool):
  4599. """
  4600. Here add the tool from DB in the selected geometry object.
  4601. :return:
  4602. """
  4603. tool_from_db = deepcopy(tool)
  4604. obj = self.collection.get_active()
  4605. if obj.kind == 'geometry':
  4606. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4607. # close the tab and delete it
  4608. for idx in range(self.ui.plot_tab_area.count()):
  4609. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4610. wdg = self.ui.plot_tab_area.widget(idx)
  4611. wdg.deleteLater()
  4612. self.ui.plot_tab_area.removeTab(idx)
  4613. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4614. elif obj.kind == 'gerber':
  4615. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4616. # close the tab and delete it
  4617. for idx in range(self.ui.plot_tab_area.count()):
  4618. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4619. wdg = self.ui.plot_tab_area.widget(idx)
  4620. wdg.deleteLater()
  4621. self.ui.plot_tab_area.removeTab(idx)
  4622. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4623. else:
  4624. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4625. def on_plot_area_tab_closed(self, tab_obj_name):
  4626. """
  4627. Executed whenever a QTab is closed in the Plot Area.
  4628. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4629. :return:
  4630. """
  4631. if tab_obj_name == "preferences_tab":
  4632. self.preferencesUiManager.on_close_preferences_tab()
  4633. elif tab_obj_name == "database_tab":
  4634. # disconnect the signals from the table widget in tab
  4635. self.tools_db_tab.ui_disconnect()
  4636. if self.tools_db_changed_flag is True:
  4637. msgbox = QtWidgets.QMessageBox()
  4638. msgbox.setText(_("One or more Tools are edited.\n"
  4639. "Do you want to update the Tools Database?"))
  4640. msgbox.setWindowTitle(_("Save Tools Database"))
  4641. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4642. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4643. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4644. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4645. msgbox.setDefaultButton(bt_yes)
  4646. msgbox.exec_()
  4647. response = msgbox.clickedButton()
  4648. if response == bt_yes:
  4649. self.tools_db_tab.on_save_tools_db()
  4650. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4651. else:
  4652. self.tools_db_changed_flag = False
  4653. self.inform.emit('')
  4654. return
  4655. self.tools_db_tab.deleteLater()
  4656. elif tab_obj_name == "text_editor_tab":
  4657. self.toggle_codeeditor = False
  4658. elif tab_obj_name == "bookmarks_tab":
  4659. self.book_dialog_tab.rebuild_actions()
  4660. self.book_dialog_tab.deleteLater()
  4661. else:
  4662. pass
  4663. # restore the coords toolbars
  4664. self.ui.toggle_coords(checked=self.defaults["global_coords_show"])
  4665. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coords_show"])
  4666. def on_flipy(self):
  4667. """
  4668. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4669. :return:
  4670. """
  4671. self.defaults.report_usage("on_flipy()")
  4672. obj_list = self.collection.get_selected()
  4673. xminlist = []
  4674. yminlist = []
  4675. xmaxlist = []
  4676. ymaxlist = []
  4677. if not obj_list:
  4678. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4679. else:
  4680. try:
  4681. # first get a bounding box to fit all
  4682. for obj in obj_list:
  4683. xmin, ymin, xmax, ymax = obj.bounds()
  4684. xminlist.append(xmin)
  4685. yminlist.append(ymin)
  4686. xmaxlist.append(xmax)
  4687. ymaxlist.append(ymax)
  4688. # get the minimum x,y and maximum x,y for all objects selected
  4689. xminimal = min(xminlist)
  4690. yminimal = min(yminlist)
  4691. xmaximal = max(xmaxlist)
  4692. ymaximal = max(ymaxlist)
  4693. px = 0.5 * (xminimal + xmaximal)
  4694. py = 0.5 * (yminimal + ymaximal)
  4695. # execute mirroring
  4696. for obj in obj_list:
  4697. obj.mirror('X', [px, py])
  4698. obj.plot()
  4699. self.app_obj.object_changed.emit(obj)
  4700. self.inform.emit('[success] %s' %
  4701. _("Flip on Y axis done."))
  4702. except Exception as e:
  4703. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4704. return
  4705. def on_flipx(self):
  4706. """
  4707. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4708. :return:
  4709. """
  4710. self.defaults.report_usage("on_flipx()")
  4711. obj_list = self.collection.get_selected()
  4712. xminlist = []
  4713. yminlist = []
  4714. xmaxlist = []
  4715. ymaxlist = []
  4716. if not obj_list:
  4717. self.inform.emit('[WARNING_NOTCL] %s' %
  4718. _("No object selected to Flip on X axis."))
  4719. else:
  4720. try:
  4721. # first get a bounding box to fit all
  4722. for obj in obj_list:
  4723. xmin, ymin, xmax, ymax = obj.bounds()
  4724. xminlist.append(xmin)
  4725. yminlist.append(ymin)
  4726. xmaxlist.append(xmax)
  4727. ymaxlist.append(ymax)
  4728. # get the minimum x,y and maximum x,y for all objects selected
  4729. xminimal = min(xminlist)
  4730. yminimal = min(yminlist)
  4731. xmaximal = max(xmaxlist)
  4732. ymaximal = max(ymaxlist)
  4733. px = 0.5 * (xminimal + xmaximal)
  4734. py = 0.5 * (yminimal + ymaximal)
  4735. # execute mirroring
  4736. for obj in obj_list:
  4737. obj.mirror('Y', [px, py])
  4738. obj.plot()
  4739. self.app_obj.object_changed.emit(obj)
  4740. self.inform.emit('[success] %s' %
  4741. _("Flip on X axis done."))
  4742. except Exception as e:
  4743. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4744. return
  4745. def on_rotate(self, silent=False, preset=None):
  4746. """
  4747. Executed when Options -> Rotate Selection menu entry is clicked.
  4748. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4749. :param preset: A value to be used as predefined angle for rotation.
  4750. :return:
  4751. """
  4752. self.defaults.report_usage("on_rotate()")
  4753. obj_list = self.collection.get_selected()
  4754. xminlist = []
  4755. yminlist = []
  4756. xmaxlist = []
  4757. ymaxlist = []
  4758. if not obj_list:
  4759. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4760. else:
  4761. if silent is False:
  4762. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4763. min=-360, max=360, decimals=4,
  4764. init_val=float(self.defaults['tools_transform_rotate']))
  4765. num, ok = rotatebox.get_value()
  4766. else:
  4767. num = preset
  4768. ok = True
  4769. if ok:
  4770. try:
  4771. # first get a bounding box to fit all
  4772. for obj in obj_list:
  4773. xmin, ymin, xmax, ymax = obj.bounds()
  4774. xminlist.append(xmin)
  4775. yminlist.append(ymin)
  4776. xmaxlist.append(xmax)
  4777. ymaxlist.append(ymax)
  4778. # get the minimum x,y and maximum x,y for all objects selected
  4779. xminimal = min(xminlist)
  4780. yminimal = min(yminlist)
  4781. xmaximal = max(xmaxlist)
  4782. ymaximal = max(ymaxlist)
  4783. px = 0.5 * (xminimal + xmaximal)
  4784. py = 0.5 * (yminimal + ymaximal)
  4785. for sel_obj in obj_list:
  4786. sel_obj.rotate(-float(num), point=(px, py))
  4787. sel_obj.plot()
  4788. self.app_obj.object_changed.emit(sel_obj)
  4789. self.inform.emit('[success] %s' % _("Rotation done."))
  4790. except Exception as e:
  4791. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4792. return
  4793. def on_skewx(self):
  4794. """
  4795. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4796. :return:
  4797. """
  4798. self.defaults.report_usage("on_skewx()")
  4799. obj_list = self.collection.get_selected()
  4800. xminlist = []
  4801. yminlist = []
  4802. if not obj_list:
  4803. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4804. else:
  4805. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4806. min=-360, max=360, decimals=4,
  4807. init_val=float(self.defaults['tools_transform_skew_x']))
  4808. num, ok = skewxbox.get_value()
  4809. if ok:
  4810. # first get a bounding box to fit all
  4811. for obj in obj_list:
  4812. xmin, ymin, xmax, ymax = obj.bounds()
  4813. xminlist.append(xmin)
  4814. yminlist.append(ymin)
  4815. # get the minimum x,y and maximum x,y for all objects selected
  4816. xminimal = min(xminlist)
  4817. yminimal = min(yminlist)
  4818. for obj in obj_list:
  4819. obj.skew(num, 0, point=(xminimal, yminimal))
  4820. obj.plot()
  4821. self.app_obj.object_changed.emit(obj)
  4822. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4823. def on_skewy(self):
  4824. """
  4825. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4826. :return:
  4827. """
  4828. self.defaults.report_usage("on_skewy()")
  4829. obj_list = self.collection.get_selected()
  4830. xminlist = []
  4831. yminlist = []
  4832. if not obj_list:
  4833. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4834. else:
  4835. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4836. min=-360, max=360, decimals=4,
  4837. init_val=float(self.defaults['tools_transform_skew_y']))
  4838. num, ok = skewybox.get_value()
  4839. if ok:
  4840. # first get a bounding box to fit all
  4841. for obj in obj_list:
  4842. xmin, ymin, xmax, ymax = obj.bounds()
  4843. xminlist.append(xmin)
  4844. yminlist.append(ymin)
  4845. # get the minimum x,y and maximum x,y for all objects selected
  4846. xminimal = min(xminlist)
  4847. yminimal = min(yminlist)
  4848. for obj in obj_list:
  4849. obj.skew(0, num, point=(xminimal, yminimal))
  4850. obj.plot()
  4851. self.app_obj.object_changed.emit(obj)
  4852. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4853. def on_plots_updated(self):
  4854. """
  4855. Callback used to report when the plots have changed.
  4856. Adjust axes and zooms to fit.
  4857. :return: None
  4858. """
  4859. if self.is_legacy is False:
  4860. self.plotcanvas.update()
  4861. else:
  4862. self.plotcanvas.auto_adjust_axes()
  4863. self.on_zoom_fit()
  4864. self.collection.update_view()
  4865. # self.inform.emit(_("Plots updated ..."))
  4866. def on_toolbar_replot(self):
  4867. """
  4868. Callback for toolbar button. Re-plots all objects.
  4869. :return: None
  4870. """
  4871. self.log.debug("on_toolbar_replot()")
  4872. try:
  4873. obj = self.collection.get_active()
  4874. if obj:
  4875. obj.read_form()
  4876. else:
  4877. self.on_zoom_fit()
  4878. except AttributeError as e:
  4879. log.debug("on_toolbar_replot() -> %s" % str(e))
  4880. pass
  4881. self.plot_all()
  4882. def grid_status(self):
  4883. return True if self.ui.grid_snap_btn.isChecked() else False
  4884. def populate_cmenu_grids(self):
  4885. units = self.defaults['units'].lower()
  4886. # for act in self.ui.cmenu_gridmenu.actions():
  4887. # act.triggered.disconnect()
  4888. self.ui.cmenu_gridmenu.clear()
  4889. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4890. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4891. _("Grid On/Off"))
  4892. grid_toggle.setCheckable(True)
  4893. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4894. self.ui.cmenu_gridmenu.addSeparator()
  4895. for grid in sorted_list:
  4896. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4897. "%s" % str(grid))
  4898. action.triggered.connect(self.set_grid)
  4899. self.ui.cmenu_gridmenu.addSeparator()
  4900. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4901. _("Add"))
  4902. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4903. _("Delete"))
  4904. grid_add.triggered.connect(self.on_grid_add)
  4905. grid_delete.triggered.connect(self.on_grid_delete)
  4906. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4907. def set_grid(self):
  4908. menu_action = self.sender()
  4909. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4910. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4911. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4912. def on_grid_add(self):
  4913. # ## Current application units in lower Case
  4914. units = self.defaults['units'].lower()
  4915. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4916. text=_('Enter a Grid Value:'),
  4917. min=0.0000, max=99.9999, decimals=4)
  4918. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4919. val, ok = grid_add_popup.get_value()
  4920. if ok:
  4921. if float(val) == 0:
  4922. self.inform.emit('[WARNING_NOTCL] %s' %
  4923. _("Please enter a grid value with non-zero value, in Float format."))
  4924. return
  4925. else:
  4926. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4927. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4928. self.inform.emit('[success] %s...' % _("New Grid added"))
  4929. else:
  4930. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4931. else:
  4932. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4933. def on_grid_delete(self):
  4934. # ## Current application units in lower Case
  4935. units = self.defaults['units'].lower()
  4936. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4937. text='Enter a Grid Value:',
  4938. min=0.0000, max=99.9999, decimals=4)
  4939. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4940. val, ok = grid_del_popup.get_value()
  4941. if ok:
  4942. if float(val) == 0:
  4943. self.inform.emit('[WARNING_NOTCL] %s' %
  4944. _("Please enter a grid value with non-zero value, in Float format."))
  4945. return
  4946. else:
  4947. try:
  4948. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4949. except ValueError:
  4950. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4951. return
  4952. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4953. else:
  4954. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4955. def on_shortcut_list(self):
  4956. self.defaults.report_usage("on_shortcut_list()")
  4957. # add the tab if it was closed
  4958. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4959. # delete the absolute and relative position and messages in the infobar
  4960. # self.ui.position_label.setText("")
  4961. # self.ui.rel_position_label.setText("")
  4962. # hide coordinates toolbars in the infobar while in DB
  4963. self.ui.coords_toolbar.hide()
  4964. self.ui.delta_coords_toolbar.hide()
  4965. # Switch plot_area to preferences page
  4966. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4967. # self.ui.show()
  4968. def on_select_tab(self, name):
  4969. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4970. if self.ui.splitter.sizes()[0] == 0:
  4971. self.ui.splitter.setSizes([1, 1])
  4972. else:
  4973. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4974. self.ui.splitter.setSizes([0, 1])
  4975. if name == 'project':
  4976. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4977. elif name == 'selected':
  4978. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4979. elif name == 'tool':
  4980. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4981. def on_copy_name(self):
  4982. self.defaults.report_usage("on_copy_name()")
  4983. obj = self.collection.get_active()
  4984. try:
  4985. name = obj.options["name"]
  4986. except AttributeError:
  4987. log.debug("on_copy_name() --> No object selected to copy it's name")
  4988. self.inform.emit('[WARNING_NOTCL] %s' %
  4989. _(" No object selected to copy it's name"))
  4990. return
  4991. self.clipboard.setText(name)
  4992. self.inform.emit(_("Name copied on clipboard ..."))
  4993. def on_mouse_click_over_plot(self, event):
  4994. """
  4995. Default actions are:
  4996. :param event: Contains information about the event, like which button
  4997. was clicked, the pixel coordinates and the axes coordinates.
  4998. :return: None
  4999. """
  5000. self.pos = []
  5001. if self.is_legacy is False:
  5002. event_pos = event.pos
  5003. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5004. # # Set the mouse button for panning
  5005. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5006. else:
  5007. event_pos = (event.xdata, event.ydata)
  5008. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5009. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5010. # So it can receive key presses
  5011. self.plotcanvas.native.setFocus()
  5012. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5013. if self.grid_status():
  5014. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5015. else:
  5016. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5017. try:
  5018. if event.button == 1:
  5019. # Reset here the relative coordinates so there is a new reference on the click position
  5020. if self.rel_point1 is None:
  5021. self.rel_point1 = self.pos
  5022. else:
  5023. self.rel_point2 = copy(self.rel_point1)
  5024. self.rel_point1 = self.pos
  5025. self.on_mouse_move_over_plot(event, origin_click=True)
  5026. except Exception as e:
  5027. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5028. def on_mouse_double_click_over_plot(self, event):
  5029. if event.button == 1:
  5030. self.doubleclick = True
  5031. def on_mouse_move_over_plot(self, event, origin_click=None):
  5032. """
  5033. Callback for the mouse motion event over the plot.
  5034. :param event: Contains information about the event.
  5035. :param origin_click
  5036. :return: None
  5037. """
  5038. if self.is_legacy is False:
  5039. event_pos = event.pos
  5040. if self.defaults["global_pan_button"] == '2':
  5041. pan_button = 2
  5042. else:
  5043. pan_button = 3
  5044. self.event_is_dragging = event.is_dragging
  5045. else:
  5046. event_pos = (event.xdata, event.ydata)
  5047. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5048. if self.defaults["global_pan_button"] == '2':
  5049. pan_button = 3
  5050. else:
  5051. pan_button = 2
  5052. self.event_is_dragging = self.plotcanvas.is_dragging
  5053. # So it can receive key presses but not when the Tcl Shell is active
  5054. if not self.ui.shell_dock.isVisible():
  5055. if not self.plotcanvas.native.hasFocus():
  5056. self.plotcanvas.native.setFocus()
  5057. self.pos_jump = event_pos
  5058. self.ui.popMenu.mouse_is_panning = False
  5059. if origin_click is None:
  5060. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5061. if event.button == pan_button and self.event_is_dragging == 1:
  5062. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5063. if self.ui.popMenu.popup_active:
  5064. self.ui.popMenu.popup_active = False
  5065. return
  5066. self.ui.popMenu.mouse_is_panning = True
  5067. return
  5068. if self.rel_point1 is not None:
  5069. try: # May fail in case mouse not within axes
  5070. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5071. if pos_canvas[0] is None or pos_canvas[1] is None:
  5072. return
  5073. if self.grid_status():
  5074. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5075. # Update cursor
  5076. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5077. symbol='++', edge_color=self.cursor_color_3D,
  5078. edge_width=self.defaults["global_cursor_width"],
  5079. size=self.defaults["global_cursor_size"])
  5080. else:
  5081. pos = (pos_canvas[0], pos_canvas[1])
  5082. self.dx = pos[0] - float(self.rel_point1[0])
  5083. self.dy = pos[1] - float(self.rel_point1[1])
  5084. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5085. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5086. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5087. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5088. units = self.defaults["units"].lower()
  5089. self.plotcanvas.text_hud.text = \
  5090. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5091. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5092. self.mouse = [pos[0], pos[1]]
  5093. if self.defaults['global_selection_shape'] is False:
  5094. self.selection_type = None
  5095. return
  5096. # if the mouse is moved and the LMB is clicked then the action is a selection
  5097. if self.event_is_dragging == 1 and event.button == 1:
  5098. self.delete_selection_shape()
  5099. if self.dx < 0:
  5100. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5101. face_color=self.defaults['global_alt_sel_fill'])
  5102. self.selection_type = False
  5103. elif self.dx >= 0:
  5104. self.draw_moving_selection_shape(self.pos, pos)
  5105. self.selection_type = True
  5106. else:
  5107. self.selection_type = None
  5108. else:
  5109. self.selection_type = None
  5110. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5111. if self.defaults['global_hover']:
  5112. for obj in self.collection.get_list():
  5113. try:
  5114. # select the object(s) only if it is enabled (plotted)
  5115. if obj.options['plot']:
  5116. if obj not in self.collection.get_selected():
  5117. poly_obj = Polygon(
  5118. [(obj.options['xmin'], obj.options['ymin']),
  5119. (obj.options['xmax'], obj.options['ymin']),
  5120. (obj.options['xmax'], obj.options['ymax']),
  5121. (obj.options['xmin'], obj.options['ymax'])]
  5122. )
  5123. if Point(pos).within(poly_obj):
  5124. if obj.isHovering is False:
  5125. obj.isHovering = True
  5126. obj.notHovering = True
  5127. # create the selection box around the selected object
  5128. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5129. else:
  5130. if obj.notHovering is True:
  5131. obj.notHovering = False
  5132. obj.isHovering = False
  5133. self.delete_hover_shape()
  5134. except Exception:
  5135. # the Exception here will happen if we try to select on screen and we have an
  5136. # newly (and empty) just created Geometry or Excellon object that do not have the
  5137. # xmin, xmax, ymin, ymax options.
  5138. # In this case poly_obj creation (see above) will fail
  5139. pass
  5140. except Exception as e:
  5141. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5142. self.ui.position_label.setText("")
  5143. self.ui.rel_position_label.setText("")
  5144. self.mouse = None
  5145. def on_mouse_click_release_over_plot(self, event):
  5146. """
  5147. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5148. and has been registered in ''self.__init__()''.
  5149. :param event: contains information about the event.
  5150. :return:
  5151. """
  5152. if self.is_legacy is False:
  5153. event_pos = event.pos
  5154. right_button = 2
  5155. else:
  5156. event_pos = (event.xdata, event.ydata)
  5157. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5158. right_button = 3
  5159. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5160. if self.grid_status():
  5161. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5162. else:
  5163. pos = (pos_canvas[0], pos_canvas[1])
  5164. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5165. # canvas menu
  5166. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5167. self.ui.popMenu.mouse_is_panning = False
  5168. self.cursor = QtGui.QCursor()
  5169. self.populate_cmenu_grids()
  5170. self.ui.popMenu.popup(self.cursor.pos())
  5171. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5172. # selection and then select a type of selection ("enclosing" or "touching")
  5173. if event.button == 1: # left click
  5174. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5175. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5176. if modifiers == QtCore.Qt.ShiftModifier:
  5177. # do not auto open the Project Tab
  5178. self.click_noproject = True
  5179. self.clipboard.setText(
  5180. self.defaults["global_point_clipboard_format"] %
  5181. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5182. )
  5183. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5184. return
  5185. if self.doubleclick is True:
  5186. self.doubleclick = False
  5187. if self.collection.get_selected():
  5188. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5189. if self.ui.splitter.sizes()[0] == 0:
  5190. self.ui.splitter.setSizes([1, 1])
  5191. try:
  5192. # delete the selection shape(S) as it may be in the way
  5193. self.delete_selection_shape()
  5194. self.delete_hover_shape()
  5195. except Exception as e:
  5196. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5197. return
  5198. else:
  5199. # WORKAROUND for LEGACY MODE
  5200. if self.is_legacy is True:
  5201. # if there is no move on canvas then we have no dragging selection
  5202. if self.dx == 0 or self.dy == 0:
  5203. self.selection_type = None
  5204. if self.selection_type is not None:
  5205. try:
  5206. self.selection_area_handler(self.pos, pos, self.selection_type)
  5207. self.selection_type = None
  5208. except Exception as e:
  5209. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5210. return
  5211. else:
  5212. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5213. if key_modifier == QtCore.Qt.ShiftModifier:
  5214. mod_key = 'Shift'
  5215. elif key_modifier == QtCore.Qt.ControlModifier:
  5216. mod_key = 'Control'
  5217. else:
  5218. mod_key = None
  5219. try:
  5220. if self.command_active is None:
  5221. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5222. # deselect, and if it's not selected then it will be selected
  5223. # If there is no active command (self.command_active is None) then we check if we clicked
  5224. # on a object by checking the bounding limits against mouse click position
  5225. if mod_key == self.defaults["global_mselect_key"]:
  5226. self.select_objects(key='multisel')
  5227. else:
  5228. # If there is no active command (self.command_active is None) then we check if
  5229. # we clicked on a object by checking the bounding limits against mouse click position
  5230. self.select_objects()
  5231. self.delete_hover_shape()
  5232. except Exception as e:
  5233. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5234. return
  5235. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5236. """
  5237. :param start_pos: mouse position when the selection LMB click was done
  5238. :param end_pos: mouse position when the left mouse button is released
  5239. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5240. :return:
  5241. """
  5242. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5243. # delete previous selection shape
  5244. self.delete_selection_shape()
  5245. # make all objects inactive
  5246. self.collection.set_all_inactive()
  5247. for obj in self.collection.get_list():
  5248. try:
  5249. # select the object(s) only if it is enabled (plotted)
  5250. if obj.options['plot']:
  5251. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5252. (obj.options['xmax'], obj.options['ymin']),
  5253. (obj.options['xmax'], obj.options['ymax']),
  5254. (obj.options['xmin'], obj.options['ymax'])])
  5255. if sel_type is True:
  5256. if poly_obj.within(poly_selection):
  5257. # create the selection box around the selected object
  5258. if self.defaults['global_selection_shape'] is True:
  5259. self.draw_selection_shape(obj)
  5260. self.collection.set_active(obj.options['name'])
  5261. else:
  5262. if poly_selection.intersects(poly_obj):
  5263. # create the selection box around the selected object
  5264. if self.defaults['global_selection_shape'] is True:
  5265. self.draw_selection_shape(obj)
  5266. self.collection.set_active(obj.options['name'])
  5267. obj.selection_shape_drawn = True
  5268. except Exception as e:
  5269. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5270. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5271. # In this case poly_obj creation (see above) will fail
  5272. log.debug("App.selection_area_handler() --> %s" % str(e))
  5273. def select_objects(self, key=None):
  5274. """
  5275. Will select objects clicked on canvas
  5276. :param key: for future use in cumulative selection
  5277. :return:
  5278. """
  5279. # list where we store the overlapped objects under our mouse left click position
  5280. if key is None:
  5281. self.objects_under_the_click_list = []
  5282. # Populate the list with the overlapped objects on the click position
  5283. curr_x, curr_y = self.pos
  5284. for obj in self.all_objects_list:
  5285. # ScriptObject and DocumentObject objects can't be selected
  5286. if obj.kind == 'script' or obj.kind == 'document':
  5287. continue
  5288. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5289. continue
  5290. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5291. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5292. if obj.options['name'] not in self.objects_under_the_click_list:
  5293. if obj.options['plot']:
  5294. # add objects to the objects_under_the_click list only if the object is plotted
  5295. # (active and not disabled)
  5296. self.objects_under_the_click_list.append(obj.options['name'])
  5297. try:
  5298. if self.objects_under_the_click_list:
  5299. curr_sel_obj = self.collection.get_active()
  5300. # case when there is only an object under the click and we toggle it
  5301. if len(self.objects_under_the_click_list) == 1:
  5302. if curr_sel_obj is None:
  5303. self.collection.set_active(self.objects_under_the_click_list[0])
  5304. curr_sel_obj = self.collection.get_active()
  5305. # create the selection box around the selected object
  5306. if self.defaults['global_selection_shape'] is True:
  5307. self.draw_selection_shape(curr_sel_obj)
  5308. curr_sel_obj.selection_shape_drawn = True
  5309. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5310. self.collection.on_objects_selection(False)
  5311. self.delete_selection_shape()
  5312. curr_sel_obj.selection_shape_drawn = False
  5313. self.collection.set_active(self.objects_under_the_click_list[0])
  5314. curr_sel_obj = self.collection.get_active()
  5315. # create the selection box around the selected object
  5316. if self.defaults['global_selection_shape'] is True:
  5317. self.draw_selection_shape(curr_sel_obj)
  5318. curr_sel_obj.selection_shape_drawn = True
  5319. self.selected_message(curr_sel_obj=curr_sel_obj)
  5320. elif curr_sel_obj.selection_shape_drawn is False:
  5321. if self.defaults['global_selection_shape'] is True:
  5322. self.draw_selection_shape(curr_sel_obj)
  5323. curr_sel_obj.selection_shape_drawn = True
  5324. else:
  5325. self.collection.on_objects_selection(False)
  5326. self.delete_selection_shape()
  5327. if self.call_source != 'app':
  5328. self.call_source = 'app'
  5329. self.selected_message(curr_sel_obj=curr_sel_obj)
  5330. else:
  5331. # If there is no selected object
  5332. # make active the first element of the overlapped objects list
  5333. if self.collection.get_active() is None:
  5334. self.collection.set_active(self.objects_under_the_click_list[0])
  5335. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5336. name_sel_obj = self.collection.get_active().options['name']
  5337. # In case that there is a selected object but it is not in the overlapped object list
  5338. # make that object inactive and activate the first element in the overlapped object list
  5339. if name_sel_obj not in self.objects_under_the_click_list:
  5340. self.collection.set_inactive(name_sel_obj)
  5341. name_sel_obj = self.objects_under_the_click_list[0]
  5342. self.collection.set_active(name_sel_obj)
  5343. else:
  5344. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5345. self.collection.set_all_inactive()
  5346. self.collection.set_active(
  5347. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5348. curr_sel_obj = self.collection.get_active()
  5349. # delete the possible selection box around a possible selected object
  5350. self.delete_selection_shape()
  5351. curr_sel_obj.selection_shape_drawn = False
  5352. # create the selection box around the selected object
  5353. if self.defaults['global_selection_shape'] is True:
  5354. self.draw_selection_shape(curr_sel_obj)
  5355. curr_sel_obj.selection_shape_drawn = True
  5356. self.selected_message(curr_sel_obj=curr_sel_obj)
  5357. else:
  5358. # deselect everything
  5359. self.collection.on_objects_selection(False)
  5360. # delete the possible selection box around a possible selected object
  5361. self.delete_selection_shape()
  5362. for o in self.collection.get_list():
  5363. o.selection_shape_drawn = False
  5364. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5365. # only when working on App
  5366. if self.call_source == 'app':
  5367. if self.click_noproject is False:
  5368. # if the Tool Tab is in focus don't change focus to Project Tab
  5369. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5370. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5371. else:
  5372. # restore auto open the Project Tab
  5373. self.click_noproject = False
  5374. # delete any text in the status bar, implicitly the last object name that was selected
  5375. # self.inform.emit("")
  5376. else:
  5377. self.call_source = 'app'
  5378. except Exception as e:
  5379. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5380. def selected_message(self, curr_sel_obj):
  5381. if curr_sel_obj:
  5382. if curr_sel_obj.kind == 'gerber':
  5383. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5384. color='green',
  5385. name=str(curr_sel_obj.options['name']),
  5386. tx=_("selected"))
  5387. )
  5388. elif curr_sel_obj.kind == 'excellon':
  5389. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5390. color='brown',
  5391. name=str(curr_sel_obj.options['name']),
  5392. tx=_("selected"))
  5393. )
  5394. elif curr_sel_obj.kind == 'cncjob':
  5395. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5396. color='blue',
  5397. name=str(curr_sel_obj.options['name']),
  5398. tx=_("selected"))
  5399. )
  5400. elif curr_sel_obj.kind == 'geometry':
  5401. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5402. color='red',
  5403. name=str(curr_sel_obj.options['name']),
  5404. tx=_("selected"))
  5405. )
  5406. def delete_hover_shape(self):
  5407. self.hover_shapes.clear()
  5408. self.hover_shapes.redraw()
  5409. def draw_hover_shape(self, sel_obj, color=None):
  5410. """
  5411. :param sel_obj: The object for which the hover shape must be drawn
  5412. :param color: The color of the hover shape
  5413. :return: None
  5414. """
  5415. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5416. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5417. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5418. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5419. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5420. if self.defaults['units'].upper() == 'MM':
  5421. hover_rect = hover_rect.buffer(-0.1)
  5422. hover_rect = hover_rect.buffer(0.2)
  5423. else:
  5424. hover_rect = hover_rect.buffer(-0.00393)
  5425. hover_rect = hover_rect.buffer(0.00787)
  5426. # if color:
  5427. # face = Color(color)
  5428. # face.alpha = 0.2
  5429. # outline = Color(color, alpha=0.8)
  5430. # else:
  5431. # face = Color(self.defaults['global_sel_fill'])
  5432. # face.alpha = 0.2
  5433. # outline = self.defaults['global_sel_line']
  5434. if color:
  5435. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5436. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5437. else:
  5438. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5439. outline = self.defaults['global_sel_line']
  5440. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5441. if self.is_legacy is True:
  5442. self.hover_shapes.redraw()
  5443. def delete_selection_shape(self):
  5444. self.move_tool.sel_shapes.clear()
  5445. self.move_tool.sel_shapes.redraw()
  5446. def draw_selection_shape(self, sel_obj, color=None):
  5447. """
  5448. Will draw a selection shape around the selected object.
  5449. :param sel_obj: The object for which the selection shape must be drawn
  5450. :param color: The color for the selection shape.
  5451. :return: None
  5452. """
  5453. if sel_obj is None:
  5454. return
  5455. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5456. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5457. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5458. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5459. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5460. if self.defaults['units'].upper() == 'MM':
  5461. sel_rect = sel_rect.buffer(-0.1)
  5462. sel_rect = sel_rect.buffer(0.2)
  5463. else:
  5464. sel_rect = sel_rect.buffer(-0.00393)
  5465. sel_rect = sel_rect.buffer(0.00787)
  5466. if color:
  5467. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5468. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5469. else:
  5470. if self.is_legacy is False:
  5471. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5472. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5473. else:
  5474. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5475. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5476. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5477. color=outline,
  5478. face_color=face,
  5479. update=True,
  5480. layer=0,
  5481. tolerance=None))
  5482. if self.is_legacy is True:
  5483. self.move_tool.sel_shapes.redraw()
  5484. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5485. """
  5486. Will draw a selection shape when dragging mouse on canvas.
  5487. :param old_coords: Old coordinates
  5488. :param coords: New coordinates
  5489. :param kwargs: Keyword arguments
  5490. :return:
  5491. """
  5492. if 'color' in kwargs:
  5493. color = kwargs['color']
  5494. else:
  5495. color = self.defaults['global_sel_line']
  5496. if 'face_color' in kwargs:
  5497. face_color = kwargs['face_color']
  5498. else:
  5499. face_color = self.defaults['global_sel_fill']
  5500. if 'face_alpha' in kwargs:
  5501. face_alpha = kwargs['face_alpha']
  5502. else:
  5503. face_alpha = 0.3
  5504. x0, y0 = old_coords
  5505. x1, y1 = coords
  5506. pt1 = (x0, y0)
  5507. pt2 = (x1, y0)
  5508. pt3 = (x1, y1)
  5509. pt4 = (x0, y1)
  5510. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5511. # color_t = Color(face_color)
  5512. # color_t.alpha = face_alpha
  5513. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5514. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5515. layer=0, tolerance=None)
  5516. if self.is_legacy is True:
  5517. self.move_tool.sel_shapes.redraw()
  5518. def on_file_new_click(self):
  5519. """
  5520. Callback for menu item File -> New.
  5521. Executed on clicking the Menu -> File -> New Project
  5522. :return:
  5523. """
  5524. if self.collection.get_list() and self.should_we_save:
  5525. msgbox = QtWidgets.QMessageBox()
  5526. # msgbox.setText("<B>Save changes ...</B>")
  5527. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5528. "Creating a New project will delete them.\n"
  5529. "Do you want to Save the project?"))
  5530. msgbox.setWindowTitle(_("Save changes"))
  5531. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5532. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5533. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5534. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5535. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5536. msgbox.setDefaultButton(bt_yes)
  5537. msgbox.exec_()
  5538. response = msgbox.clickedButton()
  5539. if response == bt_yes:
  5540. self.on_file_saveprojectas()
  5541. elif response == bt_cancel:
  5542. return
  5543. elif response == bt_no:
  5544. self.on_file_new()
  5545. else:
  5546. self.on_file_new()
  5547. self.inform.emit('[success] %s...' % _("New Project created"))
  5548. def on_file_new(self, cli=None):
  5549. """
  5550. Returns the application to its startup state. This method is thread-safe.
  5551. :param cli: Boolean. If True this method was run from command line
  5552. :return: None
  5553. """
  5554. self.defaults.report_usage("on_file_new")
  5555. # Remove everything from memory
  5556. App.log.debug("on_file_new()")
  5557. # close any editor that might be open
  5558. if self.call_source != 'app':
  5559. self.editor2object(cleanup=True)
  5560. # ## EDITOR section
  5561. self.geo_editor = AppGeoEditor(self)
  5562. self.exc_editor = AppExcEditor(self)
  5563. self.grb_editor = AppGerberEditor(self)
  5564. # Clear pool
  5565. self.clear_pool()
  5566. for obj in self.collection.get_list():
  5567. # delete shapes left drawn from mark shape_collections, if any
  5568. if isinstance(obj, GerberObject):
  5569. try:
  5570. for el in obj.mark_shapes:
  5571. obj.mark_shapes[el].clear(update=True)
  5572. obj.mark_shapes[el].enabled = False
  5573. del el
  5574. except AttributeError:
  5575. pass
  5576. # also delete annotation shapes, if any
  5577. elif isinstance(obj, CNCJobObject):
  5578. try:
  5579. obj.text_col.enabled = False
  5580. del obj.text_col
  5581. obj.annotation.clear(update=True)
  5582. del obj.annotation
  5583. except AttributeError:
  5584. pass
  5585. # delete the exclusion areas
  5586. self.exc_areas.clear_shapes()
  5587. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5588. self.shell.init_tcl()
  5589. # delete any selection shape on canvas
  5590. self.delete_selection_shape()
  5591. # delete all FlatCAM objects
  5592. self.collection.delete_all()
  5593. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5594. self.setup_component_editor()
  5595. # Clear project filename
  5596. self.project_filename = None
  5597. # Load the application defaults
  5598. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5599. # Re-fresh project options
  5600. self.on_options_app2project()
  5601. # Init FlatCAMTools
  5602. self.init_tools()
  5603. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  5604. if cli is None:
  5605. # we need to go in reverse because once we remove a tab then the index changes
  5606. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5607. # and so on. Therefore the deletion should be done in reverse
  5608. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5609. for index in range(wdg_count, -1, -1):
  5610. try:
  5611. self.ui.plot_tab_area.closeTab(index)
  5612. except Exception as e:
  5613. log.debug("App.on_file_new() --> %s" % str(e))
  5614. # # And then add again the Plot Area
  5615. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5616. self.ui.plot_tab_area.protectTab(0)
  5617. # take the focus of the Notebook on Project Tab.
  5618. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5619. self.set_ui_title(name=_("New Project - Not saved"))
  5620. def obj_properties(self):
  5621. """
  5622. Will launch the object Properties Tool
  5623. :return:
  5624. """
  5625. self.defaults.report_usage("obj_properties()")
  5626. self.properties_tool.run(toggle=False)
  5627. def on_project_context_save(self):
  5628. """
  5629. Wrapper, will save the object function of it's type
  5630. :return:
  5631. """
  5632. sel_objects = self.collection.get_selected()
  5633. len_objects = len(sel_objects)
  5634. cnt = 0
  5635. if len_objects > 1:
  5636. for o in sel_objects:
  5637. if o.kind == 'cncjob':
  5638. cnt += 1
  5639. if len_objects == cnt:
  5640. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5641. _filter_ = self.defaults['cncjob_save_filters'] + \
  5642. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5643. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5644. try:
  5645. filename, _f = FCFileSaveDialog.get_saved_filename(
  5646. caption=_("Export Code ..."),
  5647. directory=dir_file_to_save,
  5648. ext_filter=_filter_
  5649. )
  5650. except TypeError:
  5651. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."),
  5652. ext_filter=_filter_)
  5653. filename = filename.rpartition('/')[0]
  5654. for ob in sel_objects:
  5655. ob.read_form()
  5656. fname = '%s/%s' % (filename, ob.options['name'])
  5657. ob.export_gcode_handler(fname, is_gcode=True)
  5658. return
  5659. obj = self.collection.get_active()
  5660. if type(obj) == GeometryObject:
  5661. self.on_file_exportdxf()
  5662. elif type(obj) == ExcellonObject:
  5663. self.on_file_saveexcellon()
  5664. elif type(obj) == CNCJobObject:
  5665. obj.on_exportgcode_button_click()
  5666. elif type(obj) == GerberObject:
  5667. self.on_file_savegerber()
  5668. elif type(obj) == ScriptObject:
  5669. self.on_file_savescript()
  5670. elif type(obj) == DocumentObject:
  5671. self.on_file_savedocument()
  5672. def obj_move(self):
  5673. """
  5674. Callback for the Move menu entry in various Context Menu's.
  5675. :return:
  5676. """
  5677. self.defaults.report_usage("obj_move()")
  5678. self.move_tool.run(toggle=False)
  5679. def on_fileopengerber(self, signal, name=None):
  5680. """
  5681. File menu callback for opening a Gerber.
  5682. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5683. :param name:
  5684. :return: None
  5685. """
  5686. self.defaults.report_usage("on_fileopengerber")
  5687. App.log.debug("on_fileopengerber()")
  5688. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  5689. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  5690. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  5691. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  5692. "*.outline);;" \
  5693. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5694. "*.mil);;" \
  5695. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5696. "Allegro Files (*.art);;" \
  5697. "Mentor Files (*.pho *.gdo);;" \
  5698. "All Files (*.*)"
  5699. if name is None:
  5700. try:
  5701. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5702. directory=self.get_last_folder(),
  5703. filter=_filter_,
  5704. initialFilter=self.last_op_gerber_filter)
  5705. except TypeError:
  5706. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5707. filenames = [str(filename) for filename in filenames]
  5708. self.last_op_gerber_filter = _f
  5709. else:
  5710. filenames = [name]
  5711. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5712. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5713. _("Opening Gerber file.")),
  5714. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5715. color=QtGui.QColor("gray"))
  5716. if len(filenames) == 0:
  5717. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5718. else:
  5719. for filename in filenames:
  5720. if filename != '':
  5721. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5722. def on_fileopenexcellon(self, signal, name=None):
  5723. """
  5724. File menu callback for opening an Excellon file.
  5725. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5726. :param name:
  5727. :return: None
  5728. """
  5729. self.defaults.report_usage("on_fileopenexcellon")
  5730. App.log.debug("on_fileopenexcellon()")
  5731. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5732. "All Files (*.*)"
  5733. if name is None:
  5734. try:
  5735. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5736. directory=self.get_last_folder(),
  5737. filter=_filter_,
  5738. initialFilter=self.last_op_excellon_filter)
  5739. except TypeError:
  5740. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5741. filenames = [str(filename) for filename in filenames]
  5742. self.last_op_excellon_filter = _f
  5743. else:
  5744. filenames = [str(name)]
  5745. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5746. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5747. _("Opening Excellon file.")),
  5748. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5749. color=QtGui.QColor("gray"))
  5750. if len(filenames) == 0:
  5751. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5752. else:
  5753. for filename in filenames:
  5754. if filename != '':
  5755. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5756. def on_fileopengcode(self, signal, name=None):
  5757. """
  5758. File menu call back for opening gcode.
  5759. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5760. :param name:
  5761. :return:
  5762. """
  5763. self.defaults.report_usage("on_fileopengcode")
  5764. App.log.debug("on_fileopengcode()")
  5765. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5766. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5767. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5768. "All Files (*.*)"
  5769. if name is None:
  5770. try:
  5771. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5772. directory=self.get_last_folder(),
  5773. filter=_filter_,
  5774. initialFilter=self.last_op_gcode_filter)
  5775. except TypeError:
  5776. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5777. filenames = [str(filename) for filename in filenames]
  5778. self.last_op_gcode_filter = _f
  5779. else:
  5780. filenames = [name]
  5781. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5782. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5783. _("Opening G-Code file.")),
  5784. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5785. color=QtGui.QColor("gray"))
  5786. if len(filenames) == 0:
  5787. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5788. else:
  5789. for filename in filenames:
  5790. if filename != '':
  5791. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5792. def on_file_openproject(self, signal):
  5793. """
  5794. File menu callback for opening a project.
  5795. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5796. :return: None
  5797. """
  5798. self.defaults.report_usage("on_file_openproject")
  5799. App.log.debug("on_file_openproject()")
  5800. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5801. try:
  5802. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5803. directory=self.get_last_folder(), filter=_filter_)
  5804. except TypeError:
  5805. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5806. # The Qt methods above will return a QString which can cause problems later.
  5807. # So far json.dump() will fail to serialize it.
  5808. # TODO: Improve the serialization methods and remove this fix.
  5809. filename = str(filename)
  5810. if filename == "":
  5811. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5812. else:
  5813. # self.worker_task.emit({'fcn': self.open_project,
  5814. # 'params': [filename]})
  5815. # The above was failing because open_project() is not
  5816. # thread safe. The new_project()
  5817. self.open_project(filename)
  5818. def on_fileopenhpgl2(self, signal, name=None):
  5819. """
  5820. File menu callback for opening a HPGL2.
  5821. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5822. :param name:
  5823. :return: None
  5824. """
  5825. self.defaults.report_usage("on_fileopenhpgl2")
  5826. App.log.debug("on_fileopenhpgl2()")
  5827. _filter_ = "HPGL2 Files (*.plt);;" \
  5828. "All Files (*.*)"
  5829. if name is None:
  5830. try:
  5831. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5832. directory=self.get_last_folder(),
  5833. filter=_filter_)
  5834. except TypeError:
  5835. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5836. filenames = [str(filename) for filename in filenames]
  5837. else:
  5838. filenames = [name]
  5839. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5840. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5841. _("Opening HPGL2 file.")),
  5842. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5843. color=QtGui.QColor("gray"))
  5844. if len(filenames) == 0:
  5845. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5846. else:
  5847. for filename in filenames:
  5848. if filename != '':
  5849. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5850. def on_file_openconfig(self, signal):
  5851. """
  5852. File menu callback for opening a config file.
  5853. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5854. :return: None
  5855. """
  5856. self.defaults.report_usage("on_file_openconfig")
  5857. App.log.debug("on_file_openconfig()")
  5858. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5859. try:
  5860. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5861. directory=self.data_path, filter=_filter_)
  5862. except TypeError:
  5863. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5864. filter=_filter_)
  5865. if filename == "":
  5866. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5867. else:
  5868. self.open_config_file(filename)
  5869. def on_file_exportsvg(self):
  5870. """
  5871. Callback for menu item File->Export SVG.
  5872. :return: None
  5873. """
  5874. self.defaults.report_usage("on_file_exportsvg")
  5875. App.log.debug("on_file_exportsvg()")
  5876. obj = self.collection.get_active()
  5877. if obj is None:
  5878. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5879. msg = _("Please Select a Geometry object to export")
  5880. msgbox = QtWidgets.QMessageBox()
  5881. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5882. msgbox.setInformativeText(msg)
  5883. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5884. msgbox.setDefaultButton(bt_ok)
  5885. msgbox.exec_()
  5886. return
  5887. # Check for more compatible types and add as required
  5888. if (not isinstance(obj, GeometryObject)
  5889. and not isinstance(obj, GerberObject)
  5890. and not isinstance(obj, CNCJobObject)
  5891. and not isinstance(obj, ExcellonObject)):
  5892. msg = '[ERROR_NOTCL] %s' % \
  5893. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5894. msgbox = QtWidgets.QMessageBox()
  5895. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5896. msgbox.setInformativeText(msg)
  5897. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5898. msgbox.setDefaultButton(bt_ok)
  5899. msgbox.exec_()
  5900. return
  5901. name = obj.options["name"]
  5902. _filter = "SVG File (*.svg);;All Files (*.*)"
  5903. try:
  5904. filename, _f = FCFileSaveDialog.get_saved_filename(
  5905. caption=_("Export SVG"),
  5906. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5907. ext_filter=_filter)
  5908. except TypeError:
  5909. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5910. filename = str(filename)
  5911. if filename == "":
  5912. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5913. return
  5914. else:
  5915. self.export_svg(name, filename)
  5916. if self.defaults["global_open_style"] is False:
  5917. self.file_opened.emit("SVG", filename)
  5918. self.file_saved.emit("SVG", filename)
  5919. def on_file_exportpng(self):
  5920. self.defaults.report_usage("on_file_exportpng")
  5921. App.log.debug("on_file_exportpng()")
  5922. self.date = str(datetime.today()).rpartition('.')[0]
  5923. self.date = ''.join(c for c in self.date if c not in ':-')
  5924. self.date = self.date.replace(' ', '_')
  5925. data = None
  5926. if self.is_legacy is False:
  5927. image = _screenshot(alpha=False)
  5928. data = np.asarray(image)
  5929. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5930. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5931. return
  5932. filter_ = "PNG File (*.png);;All Files (*.*)"
  5933. try:
  5934. filename, _f = FCFileSaveDialog.get_saved_filename(
  5935. caption=_("Export PNG Image"),
  5936. directory=self.get_last_save_folder() + '/png_' + self.date,
  5937. ext_filter=filter_)
  5938. except TypeError:
  5939. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  5940. filename = str(filename)
  5941. if filename == "":
  5942. self.inform.emit(_("Cancelled."))
  5943. return
  5944. else:
  5945. if self.is_legacy is False:
  5946. write_png(filename, data)
  5947. else:
  5948. self.plotcanvas.figure.savefig(filename)
  5949. if self.defaults["global_open_style"] is False:
  5950. self.file_opened.emit("png", filename)
  5951. self.file_saved.emit("png", filename)
  5952. def on_file_savegerber(self):
  5953. """
  5954. Callback for menu item in Project context menu.
  5955. :return: None
  5956. """
  5957. self.defaults.report_usage("on_file_savegerber")
  5958. App.log.debug("on_file_savegerber()")
  5959. obj = self.collection.get_active()
  5960. if obj is None:
  5961. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5962. return
  5963. # Check for more compatible types and add as required
  5964. if not isinstance(obj, GerberObject):
  5965. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5966. return
  5967. name = self.collection.get_active().options["name"]
  5968. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5969. try:
  5970. filename, _f = FCFileSaveDialog.get_saved_filename(
  5971. caption="Save Gerber source file",
  5972. directory=self.get_last_save_folder() + '/' + name,
  5973. ext_filter=_filter)
  5974. except TypeError:
  5975. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  5976. filename = str(filename)
  5977. if filename == "":
  5978. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5979. return
  5980. else:
  5981. self.save_source_file(name, filename)
  5982. if self.defaults["global_open_style"] is False:
  5983. self.file_opened.emit("Gerber", filename)
  5984. self.file_saved.emit("Gerber", filename)
  5985. def on_file_savescript(self):
  5986. """
  5987. Callback for menu item in Project context menu.
  5988. :return: None
  5989. """
  5990. self.defaults.report_usage("on_file_savescript")
  5991. App.log.debug("on_file_savescript()")
  5992. obj = self.collection.get_active()
  5993. if obj is None:
  5994. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5995. return
  5996. # Check for more compatible types and add as required
  5997. if not isinstance(obj, ScriptObject):
  5998. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5999. return
  6000. name = self.collection.get_active().options["name"]
  6001. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6002. try:
  6003. filename, _f = FCFileSaveDialog.get_saved_filename(
  6004. caption="Save Script source file",
  6005. directory=self.get_last_save_folder() + '/' + name,
  6006. ext_filter=_filter)
  6007. except TypeError:
  6008. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  6009. filename = str(filename)
  6010. if filename == "":
  6011. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6012. return
  6013. else:
  6014. self.save_source_file(name, filename)
  6015. if self.defaults["global_open_style"] is False:
  6016. self.file_opened.emit("Script", filename)
  6017. self.file_saved.emit("Script", filename)
  6018. def on_file_savedocument(self):
  6019. """
  6020. Callback for menu item in Project context menu.
  6021. :return: None
  6022. """
  6023. self.defaults.report_usage("on_file_savedocument")
  6024. App.log.debug("on_file_savedocument()")
  6025. obj = self.collection.get_active()
  6026. if obj is None:
  6027. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6028. return
  6029. # Check for more compatible types and add as required
  6030. if not isinstance(obj, ScriptObject):
  6031. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6032. return
  6033. name = self.collection.get_active().options["name"]
  6034. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6035. try:
  6036. filename, _f = FCFileSaveDialog.get_saved_filename(
  6037. caption="Save Document source file",
  6038. directory=self.get_last_save_folder() + '/' + name,
  6039. ext_filter=_filter)
  6040. except TypeError:
  6041. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  6042. ext_filter=_filter)
  6043. filename = str(filename)
  6044. if filename == "":
  6045. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6046. return
  6047. else:
  6048. self.save_source_file(name, filename)
  6049. if self.defaults["global_open_style"] is False:
  6050. self.file_opened.emit("Document", filename)
  6051. self.file_saved.emit("Document", filename)
  6052. def on_file_saveexcellon(self):
  6053. """
  6054. Callback for menu item in project context menu.
  6055. :return: None
  6056. """
  6057. self.defaults.report_usage("on_file_saveexcellon")
  6058. App.log.debug("on_file_saveexcellon()")
  6059. obj = self.collection.get_active()
  6060. if obj is None:
  6061. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6062. return
  6063. # Check for more compatible types and add as required
  6064. if not isinstance(obj, ExcellonObject):
  6065. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6066. return
  6067. name = self.collection.get_active().options["name"]
  6068. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6069. try:
  6070. filename, _f = FCFileSaveDialog.get_saved_filename(
  6071. caption=_("Save Excellon source file"),
  6072. directory=self.get_last_save_folder() + '/' + name,
  6073. ext_filter=_filter)
  6074. except TypeError:
  6075. filename, _f = FCFileSaveDialog.get_saved_filename(
  6076. caption=_("Save Excellon source file"), ext_filter=_filter)
  6077. filename = str(filename)
  6078. if filename == "":
  6079. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6080. return
  6081. else:
  6082. self.save_source_file(name, filename)
  6083. if self.defaults["global_open_style"] is False:
  6084. self.file_opened.emit("Excellon", filename)
  6085. self.file_saved.emit("Excellon", filename)
  6086. def on_file_exportexcellon(self):
  6087. """
  6088. Callback for menu item File->Export->Excellon.
  6089. :return: None
  6090. """
  6091. self.defaults.report_usage("on_file_exportexcellon")
  6092. App.log.debug("on_file_exportexcellon()")
  6093. obj = self.collection.get_active()
  6094. if obj is None:
  6095. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6096. return
  6097. # Check for more compatible types and add as required
  6098. if not isinstance(obj, ExcellonObject):
  6099. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6100. return
  6101. name = self.collection.get_active().options["name"]
  6102. _filter = self.defaults["excellon_save_filters"]
  6103. try:
  6104. filename, _f = FCFileSaveDialog.get_saved_filename(
  6105. caption=_("Export Excellon"),
  6106. directory=self.get_last_save_folder() + '/' + name,
  6107. ext_filter=_filter)
  6108. except TypeError:
  6109. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  6110. filename = str(filename)
  6111. if filename == "":
  6112. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6113. return
  6114. else:
  6115. used_extension = filename.rpartition('.')[2]
  6116. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6117. self.export_excellon(name, filename)
  6118. if self.defaults["global_open_style"] is False:
  6119. self.file_opened.emit("Excellon", filename)
  6120. self.file_saved.emit("Excellon", filename)
  6121. def on_file_exportgerber(self):
  6122. """
  6123. Callback for menu item File->Export->Gerber.
  6124. :return: None
  6125. """
  6126. self.defaults.report_usage("on_file_exportgerber")
  6127. App.log.debug("on_file_exportgerber()")
  6128. obj = self.collection.get_active()
  6129. if obj is None:
  6130. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6131. return
  6132. # Check for more compatible types and add as required
  6133. if not isinstance(obj, GerberObject):
  6134. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6135. return
  6136. name = self.collection.get_active().options["name"]
  6137. _filter_ = self.defaults['gerber_save_filters']
  6138. try:
  6139. filename, _f = FCFileSaveDialog.get_saved_filename(
  6140. caption=_("Export Gerber"),
  6141. directory=self.get_last_save_folder() + '/' + name,
  6142. ext_filter=_filter_)
  6143. except TypeError:
  6144. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  6145. filename = str(filename)
  6146. if filename == "":
  6147. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6148. return
  6149. else:
  6150. used_extension = filename.rpartition('.')[2]
  6151. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6152. self.export_gerber(name, filename)
  6153. if self.defaults["global_open_style"] is False:
  6154. self.file_opened.emit("Gerber", filename)
  6155. self.file_saved.emit("Gerber", filename)
  6156. def on_file_exportdxf(self):
  6157. """
  6158. Callback for menu item File->Export DXF.
  6159. :return: None
  6160. """
  6161. self.defaults.report_usage("on_file_exportdxf")
  6162. App.log.debug("on_file_exportdxf()")
  6163. obj = self.collection.get_active()
  6164. if obj is None:
  6165. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6166. msg = _("Please Select a Geometry object to export")
  6167. msgbox = QtWidgets.QMessageBox()
  6168. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6169. msgbox.setInformativeText(msg)
  6170. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6171. msgbox.setDefaultButton(bt_ok)
  6172. msgbox.exec_()
  6173. return
  6174. # Check for more compatible types and add as required
  6175. if not isinstance(obj, GeometryObject):
  6176. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6177. msgbox = QtWidgets.QMessageBox()
  6178. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6179. msgbox.setInformativeText(msg)
  6180. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6181. msgbox.setDefaultButton(bt_ok)
  6182. msgbox.exec_()
  6183. return
  6184. name = self.collection.get_active().options["name"]
  6185. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6186. try:
  6187. filename, _f = FCFileSaveDialog.get_saved_filename(
  6188. caption=_("Export DXF"),
  6189. directory=self.get_last_save_folder() + '/' + name,
  6190. ext_filter=_filter_)
  6191. except TypeError:
  6192. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  6193. filename = str(filename)
  6194. if filename == "":
  6195. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6196. return
  6197. else:
  6198. self.export_dxf(name, filename)
  6199. if self.defaults["global_open_style"] is False:
  6200. self.file_opened.emit("DXF", filename)
  6201. self.file_saved.emit("DXF", filename)
  6202. def on_file_importsvg(self, type_of_obj):
  6203. """
  6204. Callback for menu item File->Import SVG.
  6205. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6206. :type type_of_obj: str
  6207. :return: None
  6208. """
  6209. self.defaults.report_usage("on_file_importsvg")
  6210. App.log.debug("on_file_importsvg()")
  6211. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6212. try:
  6213. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6214. directory=self.get_last_folder(), filter=_filter_)
  6215. except TypeError:
  6216. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6217. filter=_filter_)
  6218. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6219. type_of_obj = "geometry"
  6220. filenames = [str(filename) for filename in filenames]
  6221. if len(filenames) == 0:
  6222. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6223. else:
  6224. for filename in filenames:
  6225. if filename != '':
  6226. self.worker_task.emit({'fcn': self.import_svg,
  6227. 'params': [filename, type_of_obj]})
  6228. def on_file_importdxf(self, type_of_obj):
  6229. """
  6230. Callback for menu item File->Import DXF.
  6231. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6232. :type type_of_obj: str
  6233. :return: None
  6234. """
  6235. self.defaults.report_usage("on_file_importdxf")
  6236. App.log.debug("on_file_importdxf()")
  6237. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6238. try:
  6239. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6240. directory=self.get_last_folder(),
  6241. filter=_filter_)
  6242. except TypeError:
  6243. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6244. filter=_filter_)
  6245. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6246. type_of_obj = "geometry"
  6247. filenames = [str(filename) for filename in filenames]
  6248. if len(filenames) == 0:
  6249. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6250. else:
  6251. for filename in filenames:
  6252. if filename != '':
  6253. self.worker_task.emit({'fcn': self.import_dxf,
  6254. 'params': [filename, type_of_obj]})
  6255. # ###############################################################################################################
  6256. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6257. # ###############################################################################################################
  6258. def init_code_editor(self, name):
  6259. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  6260. # add the tab if it was closed
  6261. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6262. self.text_editor_tab.setObjectName('text_editor_tab')
  6263. # delete the absolute and relative position and messages in the infobar
  6264. # self.ui.position_label.setText("")
  6265. # self.ui.rel_position_label.setText("")
  6266. # hide coordinates toolbars in the infobar while in DB
  6267. self.ui.coords_toolbar.hide()
  6268. self.ui.delta_coords_toolbar.hide()
  6269. # first clear previous text in text editor (if any)
  6270. self.text_editor_tab.code_editor.clear()
  6271. self.text_editor_tab.code_editor.setReadOnly(False)
  6272. self.toggle_codeeditor = True
  6273. self.text_editor_tab.code_editor.completer_enable = False
  6274. self.text_editor_tab.buttonRun.hide()
  6275. # make sure to keep a reference to the code editor
  6276. self.reference_code_editor = self.text_editor_tab.code_editor
  6277. # Switch plot_area to CNCJob tab
  6278. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6279. def on_view_source(self):
  6280. """
  6281. Called when the user wants to see the source file of the selected object
  6282. :return:
  6283. """
  6284. try:
  6285. obj = self.collection.get_active()
  6286. except Exception as e:
  6287. log.debug("App.on_view_source() --> %s" % str(e))
  6288. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6289. return 'fail'
  6290. if obj is None:
  6291. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6292. return 'fail'
  6293. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6294. self.proc_container.view.set_busy(_("Loading..."))
  6295. flt = "All Files (*.*)"
  6296. if obj.kind == 'gerber':
  6297. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6298. elif obj.kind == 'excellon':
  6299. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6300. elif obj.kind == 'cncjob':
  6301. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6302. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  6303. # add the tab if it was closed
  6304. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6305. self.source_editor_tab.setObjectName('source_editor_tab')
  6306. # delete the absolute and relative position and messages in the infobar
  6307. # self.ui.position_label.setText("")
  6308. # self.ui.rel_position_label.setText("")
  6309. # hide coordinates toolbars in the infobar while in DB
  6310. self.ui.coords_toolbar.hide()
  6311. self.ui.delta_coords_toolbar.hide()
  6312. # first clear previous text in text editor (if any)
  6313. self.source_editor_tab.code_editor.clear()
  6314. self.source_editor_tab.code_editor.setReadOnly(False)
  6315. self.source_editor_tab.code_editor.completer_enable = False
  6316. self.source_editor_tab.buttonRun.hide()
  6317. # Switch plot_area to CNCJob tab
  6318. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6319. try:
  6320. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6321. except TypeError:
  6322. pass
  6323. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6324. try:
  6325. self.source_editor_tab.buttonSave.clicked.disconnect()
  6326. except TypeError:
  6327. pass
  6328. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6329. # then append the text from GCode to the text editor
  6330. if obj.kind == 'cncjob':
  6331. try:
  6332. file = obj.export_gcode(
  6333. preamble=self.defaults["cncjob_prepend"],
  6334. postamble=self.defaults["cncjob_append"],
  6335. to_file=True)
  6336. if file == 'fail':
  6337. return 'fail'
  6338. except AttributeError:
  6339. self.inform.emit('[WARNING_NOTCL] %s' %
  6340. _("There is no selected object for which to see it's source file code."))
  6341. return 'fail'
  6342. else:
  6343. try:
  6344. file = StringIO(obj.source_file)
  6345. except (AttributeError, TypeError):
  6346. self.inform.emit('[WARNING_NOTCL] %s' %
  6347. _("There is no selected object for which to see it's source file code."))
  6348. return 'fail'
  6349. self.source_editor_tab.t_frame.hide()
  6350. try:
  6351. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6352. # for line in file:
  6353. # QtWidgets.QApplication.processEvents()
  6354. # proc_line = str(line).strip('\n')
  6355. # self.source_editor_tab.code_editor.append(proc_line)
  6356. except Exception as e:
  6357. log.debug('App.on_view_source() -->%s' % str(e))
  6358. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6359. return
  6360. self.source_editor_tab.handleTextChanged()
  6361. self.source_editor_tab.t_frame.show()
  6362. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6363. self.proc_container.view.set_idle()
  6364. # self.ui.show()
  6365. def on_toggle_code_editor(self):
  6366. self.defaults.report_usage("on_toggle_code_editor()")
  6367. if self.toggle_codeeditor is False:
  6368. self.init_code_editor(name=_("Code Editor"))
  6369. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6370. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6371. self.text_editor_tab.buttonSave.clicked.disconnect()
  6372. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6373. else:
  6374. for idx in range(self.ui.plot_tab_area.count()):
  6375. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6376. self.ui.plot_tab_area.closeTab(idx)
  6377. break
  6378. self.toggle_codeeditor = False
  6379. def on_code_editor_close(self):
  6380. self.toggle_codeeditor = False
  6381. def goto_text_line(self):
  6382. """
  6383. Will scroll a text to the specified text line.
  6384. :return: None
  6385. """
  6386. dia_box = Dialog_box(title=_("Go to Line ..."),
  6387. label=_("Line:"),
  6388. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6389. initial_text='')
  6390. try:
  6391. line = int(dia_box.location) - 1
  6392. except (ValueError, TypeError):
  6393. line = 0
  6394. if dia_box.ok:
  6395. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6396. # at the top of the window
  6397. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6398. # get the document() of the AppTextEditor
  6399. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6400. # create a Text Cursor based on the searched line
  6401. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6402. # set cursor of the code editor with the cursor at the searcehd line
  6403. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6404. def on_filenewscript(self, silent=False):
  6405. """
  6406. Will create a new script file and open it in the Code Editor
  6407. :param silent: if True will not display status messages
  6408. :return: None
  6409. """
  6410. if silent is False:
  6411. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6412. # delete the absolute and relative position and messages in the infobar
  6413. # self.ui.position_label.setText("")
  6414. # self.ui.rel_position_label.setText("")
  6415. # hide coordinates toolbars in the infobar while in DB
  6416. self.ui.coords_toolbar.hide()
  6417. self.ui.delta_coords_toolbar.hide()
  6418. self.app_obj.new_script_object()
  6419. # script_text = script_obj.source_file
  6420. #
  6421. # self.proc_container.view.set_busy(_("Loading..."))
  6422. # script_obj.script_editor_tab.t_frame.hide()
  6423. #
  6424. # script_obj.script_editor_tab.t_frame.show()
  6425. # self.proc_container.view.set_idle()
  6426. def on_fileopenscript(self, name=None, silent=False):
  6427. """
  6428. Will open a Tcl script file into the Code Editor
  6429. :param silent: if True will not display status messages
  6430. :param name: name of a Tcl script file to open
  6431. :return: None
  6432. """
  6433. self.defaults.report_usage("on_fileopenscript")
  6434. App.log.debug("on_fileopenscript()")
  6435. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6436. "All Files (*.*)"
  6437. if name:
  6438. filenames = [name]
  6439. else:
  6440. try:
  6441. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6442. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6443. except TypeError:
  6444. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6445. if len(filenames) == 0:
  6446. if silent is False:
  6447. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6448. else:
  6449. for filename in filenames:
  6450. if filename != '':
  6451. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6452. def on_fileopenscript_example(self, name=None, silent=False):
  6453. """
  6454. Will open a Tcl script file into the Code Editor
  6455. :param silent: if True will not display status messages
  6456. :param name: name of a Tcl script file to open
  6457. :return:
  6458. """
  6459. self.defaults.report_usage("on_fileopenscript_example")
  6460. log.debug("on_fileopenscript_example()")
  6461. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6462. "All Files (*.*)"
  6463. # test if the app was frozen and choose the path for the configuration file
  6464. if getattr(sys, "frozen", False) is True:
  6465. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6466. else:
  6467. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6468. if name:
  6469. filenames = [name]
  6470. else:
  6471. try:
  6472. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6473. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6474. except TypeError:
  6475. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6476. if len(filenames) == 0:
  6477. if silent is False:
  6478. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6479. else:
  6480. for filename in filenames:
  6481. if filename != '':
  6482. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6483. def on_filerunscript(self, name=None, silent=False):
  6484. """
  6485. File menu callback for loading and running a TCL script.
  6486. :param silent: if True will not display status messages
  6487. :param name: name of a Tcl script file to be run by FlatCAM
  6488. :return: None
  6489. """
  6490. self.defaults.report_usage("on_filerunscript")
  6491. App.log.debug("on_file_runscript()")
  6492. if name:
  6493. filename = name
  6494. if self.cmd_line_headless != 1:
  6495. self.splash.showMessage('%s: %ssec\n%s' %
  6496. (_("Canvas initialization started.\n"
  6497. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6498. _("Executing ScriptObject file.")
  6499. ),
  6500. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6501. color=QtGui.QColor("gray"))
  6502. else:
  6503. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6504. "All Files (*.*)"
  6505. try:
  6506. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6507. directory=self.get_last_folder(), filter=_filter_)
  6508. except TypeError:
  6509. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6510. # The Qt methods above will return a QString which can cause problems later.
  6511. # So far json.dump() will fail to serialize it.
  6512. filename = str(filename)
  6513. if filename == "":
  6514. if silent is False:
  6515. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6516. else:
  6517. if self.cmd_line_headless != 1:
  6518. if self.ui.shell_dock.isHidden():
  6519. self.ui.shell_dock.show()
  6520. try:
  6521. with open(filename, "r") as tcl_script:
  6522. cmd_line_shellfile_content = tcl_script.read()
  6523. if self.cmd_line_headless != 1:
  6524. self.shell.exec_command(cmd_line_shellfile_content)
  6525. else:
  6526. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6527. if silent is False:
  6528. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6529. except Exception as e:
  6530. log.debug("App.on_filerunscript() -> %s" % str(e))
  6531. sys.exit(2)
  6532. def on_file_saveproject(self, silent=False):
  6533. """
  6534. Callback for menu item File->Save Project. Saves the project to
  6535. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6536. if set to None. The project is saved by calling ``self.save_project()``.
  6537. :param silent: if True will not display status messages
  6538. :return: None
  6539. """
  6540. self.defaults.report_usage("on_file_saveproject")
  6541. if self.project_filename is None:
  6542. self.on_file_saveprojectas()
  6543. else:
  6544. self.worker_task.emit({'fcn': self.save_project,
  6545. 'params': [self.project_filename, silent]})
  6546. if self.defaults["global_open_style"] is False:
  6547. self.file_opened.emit("project", self.project_filename)
  6548. self.file_saved.emit("project", self.project_filename)
  6549. self.set_ui_title(name=self.project_filename)
  6550. self.should_we_save = False
  6551. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6552. """
  6553. Callback for menu item File->Save Project As... Opens a file
  6554. chooser and saves the project to the given file via
  6555. ``self.save_project()``.
  6556. :param make_copy if to be create a copy of the project; boolean
  6557. :param use_thread: if to be run in a separate thread; boolean
  6558. :param quit_action: if to be followed by quiting the application; boolean
  6559. :return: None
  6560. """
  6561. self.defaults.report_usage("on_file_saveprojectas")
  6562. self.date = str(datetime.today()).rpartition('.')[0]
  6563. self.date = ''.join(c for c in self.date if c not in ':-')
  6564. self.date = self.date.replace(' ', '_')
  6565. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6566. try:
  6567. filename, _f = FCFileSaveDialog.get_saved_filename(
  6568. caption=_("Save Project As ..."),
  6569. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6570. proj=_("Project")),
  6571. ext_filter=filter_
  6572. )
  6573. except TypeError:
  6574. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6575. filename = str(filename)
  6576. if filename == '':
  6577. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6578. return
  6579. if use_thread is True:
  6580. self.worker_task.emit({'fcn': self.save_project,
  6581. 'params': [filename, quit_action]})
  6582. else:
  6583. self.save_project(filename, quit_action)
  6584. # self.save_project(filename)
  6585. if self.defaults["global_open_style"] is False:
  6586. self.file_opened.emit("project", filename)
  6587. self.file_saved.emit("project", filename)
  6588. if not make_copy:
  6589. self.project_filename = filename
  6590. self.set_ui_title(name=self.project_filename)
  6591. self.should_we_save = False
  6592. def on_file_save_objects_pdf(self, use_thread=True):
  6593. self.date = str(datetime.today()).rpartition('.')[0]
  6594. self.date = ''.join(c for c in self.date if c not in ':-')
  6595. self.date = self.date.replace(' ', '_')
  6596. try:
  6597. obj_selection = self.collection.get_selected()
  6598. if len(obj_selection) == 1:
  6599. obj_name = str(obj_selection[0].options['name'])
  6600. else:
  6601. obj_name = _("FlatCAM objects print")
  6602. except AttributeError as err:
  6603. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6604. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6605. return
  6606. if not obj_selection:
  6607. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6608. return
  6609. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6610. try:
  6611. filename, _f = FCFileSaveDialog.get_saved_filename(
  6612. caption=_("Save Object as PDF ..."),
  6613. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6614. obj_name=obj_name,
  6615. date=self.date),
  6616. ext_filter=filter_
  6617. )
  6618. except TypeError:
  6619. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6620. filename = str(filename)
  6621. if filename == '':
  6622. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6623. return
  6624. if use_thread is True:
  6625. self.proc_container.new(_("Printing PDF ... Please wait."))
  6626. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6627. else:
  6628. self.save_pdf(filename, obj_selection)
  6629. # self.save_project(filename)
  6630. if self.defaults["global_open_style"] is False:
  6631. self.file_opened.emit("pdf", filename)
  6632. self.file_saved.emit("pdf", filename)
  6633. def save_pdf(self, file_name, obj_selection):
  6634. p_size = self.defaults['global_workspaceT']
  6635. orientation = self.defaults['global_workspace_orientation']
  6636. color = 'black'
  6637. transparency_level = 1.0
  6638. self.pagesize = {}
  6639. self.pagesize.update(
  6640. {
  6641. 'Bounds': None,
  6642. 'A0': (841 * mm, 1189 * mm),
  6643. 'A1': (594 * mm, 841 * mm),
  6644. 'A2': (420 * mm, 594 * mm),
  6645. 'A3': (297 * mm, 420 * mm),
  6646. 'A4': (210 * mm, 297 * mm),
  6647. 'A5': (148 * mm, 210 * mm),
  6648. 'A6': (105 * mm, 148 * mm),
  6649. 'A7': (74 * mm, 105 * mm),
  6650. 'A8': (52 * mm, 74 * mm),
  6651. 'A9': (37 * mm, 52 * mm),
  6652. 'A10': (26 * mm, 37 * mm),
  6653. 'B0': (1000 * mm, 1414 * mm),
  6654. 'B1': (707 * mm, 1000 * mm),
  6655. 'B2': (500 * mm, 707 * mm),
  6656. 'B3': (353 * mm, 500 * mm),
  6657. 'B4': (250 * mm, 353 * mm),
  6658. 'B5': (176 * mm, 250 * mm),
  6659. 'B6': (125 * mm, 176 * mm),
  6660. 'B7': (88 * mm, 125 * mm),
  6661. 'B8': (62 * mm, 88 * mm),
  6662. 'B9': (44 * mm, 62 * mm),
  6663. 'B10': (31 * mm, 44 * mm),
  6664. 'C0': (917 * mm, 1297 * mm),
  6665. 'C1': (648 * mm, 917 * mm),
  6666. 'C2': (458 * mm, 648 * mm),
  6667. 'C3': (324 * mm, 458 * mm),
  6668. 'C4': (229 * mm, 324 * mm),
  6669. 'C5': (162 * mm, 229 * mm),
  6670. 'C6': (114 * mm, 162 * mm),
  6671. 'C7': (81 * mm, 114 * mm),
  6672. 'C8': (57 * mm, 81 * mm),
  6673. 'C9': (40 * mm, 57 * mm),
  6674. 'C10': (28 * mm, 40 * mm),
  6675. # American paper sizes
  6676. 'LETTER': (8.5 * inch, 11 * inch),
  6677. 'LEGAL': (8.5 * inch, 14 * inch),
  6678. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6679. # From https://en.wikipedia.org/wiki/Paper_size
  6680. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6681. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6682. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6683. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6684. 'LEDGER': (17 * inch, 11 * inch),
  6685. }
  6686. )
  6687. exported_svg = []
  6688. for obj in obj_selection:
  6689. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6690. scale_factor_x=None, scale_factor_y=None,
  6691. skew_factor_x=None, skew_factor_y=None,
  6692. mirror=None)
  6693. if obj.kind.lower() == 'gerber':
  6694. # color = self.defaults["gerber_plot_fill"][:-2]
  6695. color = obj.fill_color[:-2]
  6696. elif obj.kind.lower() == 'excellon':
  6697. color = '#C40000'
  6698. elif obj.kind.lower() == 'geometry':
  6699. color = self.defaults["global_draw_color"]
  6700. # Change the attributes of the exported SVG
  6701. # We don't need stroke-width
  6702. # We set opacity to maximum
  6703. # We set the colour to WHITE
  6704. root = ET.fromstring(svg_obj)
  6705. for child in root:
  6706. child.set('fill', str(color))
  6707. child.set('opacity', str(transparency_level))
  6708. child.set('stroke', str(color))
  6709. exported_svg.append(ET.tostring(root))
  6710. xmin = Inf
  6711. ymin = Inf
  6712. xmax = -Inf
  6713. ymax = -Inf
  6714. for obj in obj_selection:
  6715. try:
  6716. gxmin, gymin, gxmax, gymax = obj.bounds()
  6717. xmin = min([xmin, gxmin])
  6718. ymin = min([ymin, gymin])
  6719. xmax = max([xmax, gxmax])
  6720. ymax = max([ymax, gymax])
  6721. except Exception as e:
  6722. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6723. # Determine bounding area for svg export
  6724. bounds = [xmin, ymin, xmax, ymax]
  6725. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6726. # This contain the measure units
  6727. uom = obj_selection[0].units.lower()
  6728. # Define a boundary around SVG of about 1.0mm (~39mils)
  6729. if uom in "mm":
  6730. boundary = 1.0
  6731. else:
  6732. boundary = 0.0393701
  6733. # Convert everything to strings for use in the xml doc
  6734. svgwidth = str(size[0] + (2 * boundary))
  6735. svgheight = str(size[1] + (2 * boundary))
  6736. minx = str(bounds[0] - boundary)
  6737. miny = str(bounds[1] + boundary + size[1])
  6738. # Add a SVG Header and footer to the svg output from shapely
  6739. # The transform flips the Y Axis so that everything renders
  6740. # properly within svg apps such as inkscape
  6741. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6742. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6743. svg_header += 'width="' + svgwidth + uom + '" '
  6744. svg_header += 'height="' + svgheight + uom + '" '
  6745. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6746. svg_header += '>'
  6747. svg_header += '<g transform="scale(1,-1)">'
  6748. svg_footer = '</g> </svg>'
  6749. svg_elem = str(svg_header)
  6750. for svg_item in exported_svg:
  6751. svg_elem += str(svg_item)
  6752. svg_elem += str(svg_footer)
  6753. # Parse the xml through a xml parser just to add line feeds
  6754. # and to make it look more pretty for the output
  6755. doc = parse_xml_string(svg_elem)
  6756. doc_final = doc.toprettyxml()
  6757. try:
  6758. if self.defaults['units'].upper() == 'IN':
  6759. unit = inch
  6760. else:
  6761. unit = mm
  6762. doc_final = StringIO(doc_final)
  6763. drawing = svg2rlg(doc_final)
  6764. if p_size == 'Bounds':
  6765. renderPDF.drawToFile(drawing, file_name)
  6766. else:
  6767. if orientation == 'p':
  6768. page_size = portrait(self.pagesize[p_size])
  6769. else:
  6770. page_size = landscape(self.pagesize[p_size])
  6771. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6772. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6773. renderPDF.draw(drawing, my_canvas, 0, 0)
  6774. my_canvas.save()
  6775. except Exception as e:
  6776. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6777. return 'fail'
  6778. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6779. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6780. """
  6781. Exports a Geometry Object to an SVG file.
  6782. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6783. :param filename: Path to the SVG file to save to.
  6784. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6785. :return:
  6786. """
  6787. self.defaults.report_usage("export_svg()")
  6788. if filename is None:
  6789. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6790. is not None else self.defaults["global_last_folder"]
  6791. self.log.debug("export_svg()")
  6792. try:
  6793. obj = self.collection.get_by_name(str(obj_name))
  6794. except Exception:
  6795. # TODO: The return behavior has not been established... should raise exception?
  6796. return "Could not retrieve object: %s" % obj_name
  6797. with self.proc_container.new(_("Exporting SVG")) as proc:
  6798. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6799. # Determine bounding area for svg export
  6800. bounds = obj.bounds()
  6801. size = obj.size()
  6802. # Convert everything to strings for use in the xml doc
  6803. svgwidth = str(size[0])
  6804. svgheight = str(size[1])
  6805. minx = str(bounds[0])
  6806. miny = str(bounds[1] - size[1])
  6807. uom = obj.units.lower()
  6808. # Add a SVG Header and footer to the svg output from shapely
  6809. # The transform flips the Y Axis so that everything renders
  6810. # properly within svg apps such as inkscape
  6811. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6812. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6813. svg_header += 'width="' + svgwidth + uom + '" '
  6814. svg_header += 'height="' + svgheight + uom + '" '
  6815. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6816. svg_header += '<g transform="scale(1,-1)">'
  6817. svg_footer = '</g> </svg>'
  6818. svg_elem = svg_header + exported_svg + svg_footer
  6819. # Parse the xml through a xml parser just to add line feeds
  6820. # and to make it look more pretty for the output
  6821. svgcode = parse_xml_string(svg_elem)
  6822. svgcode = svgcode.toprettyxml()
  6823. try:
  6824. with open(filename, 'w') as fp:
  6825. fp.write(svgcode)
  6826. except PermissionError:
  6827. self.inform.emit('[WARNING] %s' %
  6828. _("Permission denied, saving not possible.\n"
  6829. "Most likely another app is holding the file open and not accessible."))
  6830. return 'fail'
  6831. if self.defaults["global_open_style"] is False:
  6832. self.file_opened.emit("SVG", filename)
  6833. self.file_saved.emit("SVG", filename)
  6834. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6835. def save_source_file(self, obj_name, filename, use_thread=True):
  6836. """
  6837. Exports a FlatCAM Object to an Gerber/Excellon file.
  6838. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6839. :param filename: Path to the Gerber file to save to.
  6840. :param use_thread: if to be run in a separate thread
  6841. :return:
  6842. """
  6843. self.defaults.report_usage("save source file()")
  6844. if filename is None:
  6845. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6846. is not None else self.defaults["global_last_folder"]
  6847. self.log.debug("save source file()")
  6848. obj = self.collection.get_by_name(obj_name)
  6849. file_string = StringIO(obj.source_file)
  6850. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6851. if file_string.getvalue() == '':
  6852. self.inform.emit('[ERROR_NOTCL] %s' %
  6853. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6854. return 'fail'
  6855. try:
  6856. with open(filename, 'w') as file:
  6857. file.writelines('G04*\n')
  6858. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6859. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6860. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6861. file.writelines('G04 Created on : %s*\n' % time_string)
  6862. for line in file_string:
  6863. file.writelines(line)
  6864. except PermissionError:
  6865. self.inform.emit('[WARNING] %s' %
  6866. _("Permission denied, saving not possible.\n"
  6867. "Most likely another app is holding the file open and not accessible."))
  6868. return 'fail'
  6869. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6870. """
  6871. Exports a Excellon Object to an Excellon file.
  6872. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6873. :param filename: Path to the Excellon file to save to.
  6874. :param local_use:
  6875. :param use_thread: if to be run in a separate thread
  6876. :return:
  6877. """
  6878. self.defaults.report_usage("export_excellon()")
  6879. if filename is None:
  6880. if self.defaults["global_last_save_folder"]:
  6881. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6882. else:
  6883. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6884. self.log.debug("export_excellon()")
  6885. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6886. self.defaults["excellon_exp_decimals"]
  6887. )
  6888. if local_use is None:
  6889. try:
  6890. obj = self.collection.get_by_name(str(obj_name))
  6891. except Exception:
  6892. return "Could not retrieve object: %s" % obj_name
  6893. else:
  6894. obj = local_use
  6895. if not isinstance(obj, ExcellonObject):
  6896. self.inform.emit('[ERROR_NOTCL] %s' %
  6897. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6898. return
  6899. # updated units
  6900. eunits = self.defaults["excellon_exp_units"]
  6901. ewhole = self.defaults["excellon_exp_integer"]
  6902. efract = self.defaults["excellon_exp_decimals"]
  6903. ezeros = self.defaults["excellon_exp_zeros"]
  6904. eformat = self.defaults["excellon_exp_format"]
  6905. slot_type = self.defaults["excellon_exp_slot_type"]
  6906. fc_units = self.defaults['units'].upper()
  6907. if fc_units == 'MM':
  6908. factor = 1 if eunits == 'METRIC' else 0.03937
  6909. else:
  6910. factor = 25.4 if eunits == 'METRIC' else 1
  6911. def make_excellon():
  6912. try:
  6913. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6914. header = 'M48\n'
  6915. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6916. (str(self.version), str(self.version_date))
  6917. header += ';Filename: %s' % str(obj_name) + '\n'
  6918. header += ';Created on : %s' % time_str + '\n'
  6919. if eformat == 'dec':
  6920. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6921. header += eunits + '\n'
  6922. for tool in obj.tools:
  6923. if eunits == 'METRIC':
  6924. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6925. tool=str(tool),
  6926. dec=2)
  6927. else:
  6928. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6929. tool=str(tool),
  6930. dec=4)
  6931. else:
  6932. if ezeros == 'LZ':
  6933. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6934. form='ndec', e_zeros='LZ', factor=factor,
  6935. slot_type=slot_type)
  6936. header += '%s,%s\n' % (eunits, 'LZ')
  6937. header += format_exc
  6938. for tool in obj.tools:
  6939. if eunits == 'METRIC':
  6940. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6941. float(obj.tools[tool]['tooldia']) * factor,
  6942. tool=str(tool),
  6943. dec=2)
  6944. else:
  6945. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6946. float(obj.tools[tool]['tooldia']) * factor,
  6947. tool=str(tool),
  6948. dec=4)
  6949. else:
  6950. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6951. form='ndec', e_zeros='TZ', factor=factor,
  6952. slot_type=slot_type)
  6953. header += '%s,%s\n' % (eunits, 'TZ')
  6954. header += format_exc
  6955. for tool in obj.tools:
  6956. if eunits == 'METRIC':
  6957. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6958. float(obj.tools[tool]['tooldia']) * factor,
  6959. tool=str(tool),
  6960. dec=2)
  6961. else:
  6962. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6963. float(obj.tools[tool]['tooldia']) * factor,
  6964. tool=str(tool),
  6965. dec=4)
  6966. header += '%\n'
  6967. footer = 'M30\n'
  6968. exported_excellon = header
  6969. exported_excellon += excellon_code
  6970. exported_excellon += footer
  6971. if local_use is None:
  6972. try:
  6973. with open(filename, 'w') as fp:
  6974. fp.write(exported_excellon)
  6975. except PermissionError:
  6976. self.inform.emit('[WARNING] %s' %
  6977. _("Permission denied, saving not possible.\n"
  6978. "Most likely another app is holding the file open and not accessible."))
  6979. return 'fail'
  6980. if self.defaults["global_open_style"] is False:
  6981. self.file_opened.emit("Excellon", filename)
  6982. self.file_saved.emit("Excellon", filename)
  6983. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6984. else:
  6985. return exported_excellon
  6986. except Exception as e:
  6987. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6988. return 'fail'
  6989. if use_thread is True:
  6990. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6991. def job_thread_exc(app_obj):
  6992. ret = make_excellon()
  6993. if ret == 'fail':
  6994. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6995. return
  6996. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6997. else:
  6998. eret = make_excellon()
  6999. if eret == 'fail':
  7000. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7001. return 'fail'
  7002. if local_use is not None:
  7003. return eret
  7004. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7005. """
  7006. Exports a Gerber Object to an Gerber file.
  7007. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7008. :param filename: Path to the Gerber file to save to.
  7009. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7010. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7011. :param use_thread: if to be run in a separate thread
  7012. :return:
  7013. """
  7014. self.defaults.report_usage("export_gerber()")
  7015. if filename is None:
  7016. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7017. is not None else self.defaults["global_last_folder"]
  7018. self.log.debug("export_gerber()")
  7019. if local_use is None:
  7020. try:
  7021. obj = self.collection.get_by_name(str(obj_name))
  7022. except Exception:
  7023. return "Could not retrieve object: %s" % obj_name
  7024. else:
  7025. obj = local_use
  7026. # updated units
  7027. gunits = self.defaults["gerber_exp_units"]
  7028. gwhole = self.defaults["gerber_exp_integer"]
  7029. gfract = self.defaults["gerber_exp_decimals"]
  7030. gzeros = self.defaults["gerber_exp_zeros"]
  7031. fc_units = self.defaults['units'].upper()
  7032. if fc_units == 'MM':
  7033. factor = 1 if gunits == 'MM' else 0.03937
  7034. else:
  7035. factor = 25.4 if gunits == 'MM' else 1
  7036. def make_gerber():
  7037. try:
  7038. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7039. header = 'G04*\n'
  7040. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7041. (str(self.version), str(self.version_date))
  7042. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7043. header += 'G04 Created on : %s*' % time_str + '\n'
  7044. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7045. header += "%MO{units}*%\n".format(units=gunits)
  7046. for apid in obj.apertures:
  7047. if obj.apertures[apid]['type'] == 'C':
  7048. header += "%ADD{apid}{type},{size}*%\n".format(
  7049. apid=str(apid),
  7050. type='C',
  7051. size=(factor * obj.apertures[apid]['size'])
  7052. )
  7053. elif obj.apertures[apid]['type'] == 'R':
  7054. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7055. apid=str(apid),
  7056. type='R',
  7057. width=(factor * obj.apertures[apid]['width']),
  7058. height=(factor * obj.apertures[apid]['height'])
  7059. )
  7060. elif obj.apertures[apid]['type'] == 'O':
  7061. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7062. apid=str(apid),
  7063. type='O',
  7064. width=(factor * obj.apertures[apid]['width']),
  7065. height=(factor * obj.apertures[apid]['height'])
  7066. )
  7067. header += '\n'
  7068. # obsolete units but some software may need it
  7069. if gunits == 'IN':
  7070. header += 'G70*\n'
  7071. else:
  7072. header += 'G71*\n'
  7073. # Absolute Mode
  7074. header += 'G90*\n'
  7075. header += 'G01*\n'
  7076. # positive polarity
  7077. header += '%LPD*%\n'
  7078. footer = 'M02*\n'
  7079. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7080. exported_gerber = header
  7081. exported_gerber += gerber_code
  7082. exported_gerber += footer
  7083. if local_use is None:
  7084. try:
  7085. with open(filename, 'w') as fp:
  7086. fp.write(exported_gerber)
  7087. except PermissionError:
  7088. self.inform.emit('[WARNING] %s' %
  7089. _("Permission denied, saving not possible.\n"
  7090. "Most likely another app is holding the file open and not accessible."))
  7091. return 'fail'
  7092. if self.defaults["global_open_style"] is False:
  7093. self.file_opened.emit("Gerber", filename)
  7094. self.file_saved.emit("Gerber", filename)
  7095. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7096. else:
  7097. return exported_gerber
  7098. except Exception as e:
  7099. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7100. return 'fail'
  7101. if use_thread is True:
  7102. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7103. def job_thread_grb(app_obj):
  7104. ret = make_gerber()
  7105. if ret == 'fail':
  7106. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7107. return
  7108. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7109. else:
  7110. gret = make_gerber()
  7111. if gret == 'fail':
  7112. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7113. return 'fail'
  7114. if local_use is not None:
  7115. return gret
  7116. def export_dxf(self, obj_name, filename, use_thread=True):
  7117. """
  7118. Exports a Geometry Object to an DXF file.
  7119. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7120. :param filename: Path to the DXF file to save to.
  7121. :param use_thread: if to be run in a separate thread
  7122. :return:
  7123. """
  7124. self.defaults.report_usage("export_dxf()")
  7125. if filename is None:
  7126. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7127. is not None else self.defaults["global_last_folder"]
  7128. self.log.debug("export_dxf()")
  7129. try:
  7130. obj = self.collection.get_by_name(str(obj_name))
  7131. except Exception:
  7132. # TODO: The return behavior has not been established... should raise exception?
  7133. return "Could not retrieve object: %s" % obj_name
  7134. def make_dxf():
  7135. try:
  7136. dxf_code = obj.export_dxf()
  7137. dxf_code.saveas(filename)
  7138. if self.defaults["global_open_style"] is False:
  7139. self.file_opened.emit("DXF", filename)
  7140. self.file_saved.emit("DXF", filename)
  7141. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7142. except Exception:
  7143. return 'fail'
  7144. if use_thread is True:
  7145. with self.proc_container.new(_("Exporting DXF")) as proc:
  7146. def job_thread_exc(app_obj):
  7147. ret_dxf_val = make_dxf()
  7148. if ret_dxf_val == 'fail':
  7149. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7150. return
  7151. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7152. else:
  7153. ret = make_dxf()
  7154. if ret == 'fail':
  7155. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7156. return
  7157. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7158. """
  7159. Adds a new Geometry Object to the projects and populates
  7160. it with shapes extracted from the SVG file.
  7161. :param plot: If True then the resulting object will be plotted on canvas
  7162. :param filename: Path to the SVG file.
  7163. :param geo_type: Type of FlatCAM object that will be created from SVG
  7164. :param outname: The name given to the resulting FlatCAM object
  7165. :return:
  7166. """
  7167. self.defaults.report_usage("import_svg()")
  7168. log.debug("App.import_svg()")
  7169. obj_type = ""
  7170. if geo_type is None or geo_type == "geometry":
  7171. obj_type = "geometry"
  7172. elif geo_type == "gerber":
  7173. obj_type = "gerber"
  7174. else:
  7175. self.inform.emit('[ERROR_NOTCL] %s' %
  7176. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7177. return
  7178. units = self.defaults['units'].upper()
  7179. def obj_init(geo_obj, app_obj):
  7180. geo_obj.import_svg(filename, obj_type, units=units)
  7181. geo_obj.multigeo = False
  7182. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7183. with self.proc_container.new(_("Importing SVG")) as proc:
  7184. # Object name
  7185. name = outname or filename.split('/')[-1].split('\\')[-1]
  7186. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7187. if ret == 'fail':
  7188. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7189. return 'fail'
  7190. # Register recent file
  7191. self.file_opened.emit("svg", filename)
  7192. # appGUI feedback
  7193. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7194. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7195. """
  7196. Adds a new Geometry Object to the projects and populates
  7197. it with shapes extracted from the DXF file.
  7198. :param filename: Path to the DXF file.
  7199. :param geo_type: Type of FlatCAM object that will be created from DXF
  7200. :param outname: Name for the imported Geometry
  7201. :param plot: If True then the resulting object will be plotted on canvas
  7202. :return:
  7203. """
  7204. log.debug(" ********* Importing SVG as: %s ********* " % geo_type.capitalize())
  7205. obj_type = ""
  7206. if geo_type is None or geo_type == "geometry":
  7207. obj_type = "geometry"
  7208. elif geo_type == "gerber":
  7209. obj_type = geo_type
  7210. else:
  7211. self.inform.emit('[ERROR_NOTCL] %s' %
  7212. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7213. return
  7214. units = self.defaults['units'].upper()
  7215. def obj_init(geo_obj, app_obj):
  7216. if obj_type == "geometry":
  7217. geo_obj.import_dxf_as_geo(filename, units=units)
  7218. elif obj_type == "gerber":
  7219. geo_obj.import_dxf_as_gerber(filename, units=units)
  7220. else:
  7221. return "fail"
  7222. geo_obj.multigeo = True
  7223. with self.proc_container.new(_("Importing DXF")):
  7224. # Object name
  7225. name = outname or filename.split('/')[-1].split('\\')[-1]
  7226. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7227. if ret == 'fail':
  7228. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7229. return 'fail'
  7230. # Register recent file
  7231. self.file_opened.emit("dxf", filename)
  7232. # appGUI feedback
  7233. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7234. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7235. """
  7236. Opens a Gerber file, parses it and creates a new object for
  7237. it in the program. Thread-safe.
  7238. :param outname: Name of the resulting object. None causes the
  7239. name to be that of the file. Str.
  7240. :param filename: Gerber file filename
  7241. :type filename: str
  7242. :param plot: boolean, to plot or not the resulting object
  7243. :param from_tcl: True if run from Tcl Shell
  7244. :return: None
  7245. """
  7246. # How the object should be initialized
  7247. def obj_init(gerber_obj, app_obj):
  7248. assert isinstance(gerber_obj, GerberObject), \
  7249. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7250. # Opening the file happens here
  7251. try:
  7252. gerber_obj.parse_file(filename)
  7253. except IOError:
  7254. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7255. return "fail"
  7256. except ParseError as err:
  7257. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7258. app_obj.log.error(str(err))
  7259. return "fail"
  7260. except Exception as e:
  7261. log.debug("App.open_gerber() --> %s" % str(e))
  7262. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7263. msg += traceback.format_exc()
  7264. app_obj.inform.emit(msg)
  7265. return "fail"
  7266. if gerber_obj.is_empty():
  7267. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7268. _("Object is not Gerber file or empty. Aborting object creation."))
  7269. return "fail"
  7270. App.log.debug("open_gerber()")
  7271. with self.proc_container.new(_("Opening Gerber")):
  7272. # Object name
  7273. name = outname or filename.split('/')[-1].split('\\')[-1]
  7274. # # ## Object creation # ##
  7275. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7276. if ret_val == 'fail':
  7277. if from_tcl:
  7278. filename = self.defaults['global_tcl_path'] + '/' + name
  7279. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7280. if ret_val == 'fail':
  7281. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7282. return 'fail'
  7283. # Register recent file
  7284. self.file_opened.emit("gerber", filename)
  7285. # appGUI feedback
  7286. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7287. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7288. """
  7289. Opens an Excellon file, parses it and creates a new object for
  7290. it in the program. Thread-safe.
  7291. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7292. :param filename: Excellon file filename
  7293. :type filename: str
  7294. :param plot: boolean, to plot or not the resulting object
  7295. :param from_tcl: True if run from Tcl Shell
  7296. :return: None
  7297. """
  7298. App.log.debug("open_excellon()")
  7299. # How the object should be initialized
  7300. def obj_init(excellon_obj, app_obj):
  7301. try:
  7302. ret = excellon_obj.parse_file(filename=filename)
  7303. if ret == "fail":
  7304. log.debug("Excellon parsing failed.")
  7305. self.inform.emit('[ERROR_NOTCL] %s' %
  7306. _("This is not Excellon file."))
  7307. return "fail"
  7308. except IOError:
  7309. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7310. (_("Cannot open file"), filename))
  7311. log.debug("Could not open Excellon object.")
  7312. return "fail"
  7313. except Exception:
  7314. msg = '[ERROR_NOTCL] %s' % \
  7315. _("An internal error has occurred. See shell.\n")
  7316. msg += traceback.format_exc()
  7317. app_obj.inform.emit(msg)
  7318. return "fail"
  7319. ret = excellon_obj.create_geometry()
  7320. if ret == 'fail':
  7321. log.debug("Could not create geometry for Excellon object.")
  7322. return "fail"
  7323. for tool in excellon_obj.tools:
  7324. if excellon_obj.tools[tool]['solid_geometry']:
  7325. return
  7326. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7327. return "fail"
  7328. with self.proc_container.new(_("Opening Excellon.")):
  7329. # Object name
  7330. name = outname or filename.split('/')[-1].split('\\')[-1]
  7331. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7332. if ret_val == 'fail':
  7333. if from_tcl:
  7334. filename = self.defaults['global_tcl_path'] + '/' + name
  7335. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7336. if ret_val == 'fail':
  7337. self.inform.emit('[ERROR_NOTCL] %s' %
  7338. _('Open Excellon file failed. Probable not an Excellon file.'))
  7339. return
  7340. # Register recent file
  7341. self.file_opened.emit("excellon", filename)
  7342. # appGUI feedback
  7343. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7344. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7345. """
  7346. Opens a G-gcode file, parses it and creates a new object for
  7347. it in the program. Thread-safe.
  7348. :param filename: G-code file filename
  7349. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7350. :param force_parsing:
  7351. :param plot: If True plot the object on canvas
  7352. :param from_tcl: True if run from Tcl Shell
  7353. :return: None
  7354. """
  7355. App.log.debug("open_gcode()")
  7356. # How the object should be initialized
  7357. def obj_init(job_obj, app_obj_):
  7358. """
  7359. :param job_obj: the resulting object
  7360. :type app_obj_: App
  7361. """
  7362. assert isinstance(app_obj_, App), \
  7363. "Initializer expected App, got %s" % type(app_obj_)
  7364. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7365. try:
  7366. f = open(filename)
  7367. gcode = f.read()
  7368. f.close()
  7369. except IOError:
  7370. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7371. return "fail"
  7372. job_obj.gcode = gcode
  7373. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7374. if gcode_ret == "fail":
  7375. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7376. return "fail"
  7377. job_obj.create_geometry()
  7378. with self.proc_container.new(_("Opening G-Code.")):
  7379. # Object name
  7380. name = outname or filename.split('/')[-1].split('\\')[-1]
  7381. # New object creation and file processing
  7382. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7383. if ret_val == 'fail':
  7384. if from_tcl:
  7385. filename = self.defaults['global_tcl_path'] + '/' + name
  7386. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7387. if ret_val == 'fail':
  7388. self.inform.emit('[ERROR_NOTCL] %s' %
  7389. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7390. "Try to load it from File menu.\n "
  7391. "Attempting to create a FlatCAM CNCJob Object from "
  7392. "G-Code file failed during processing"))
  7393. return "fail"
  7394. # Register recent file
  7395. self.file_opened.emit("cncjob", filename)
  7396. # appGUI feedback
  7397. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7398. def open_hpgl2(self, filename, outname=None):
  7399. """
  7400. Opens a HPGL2 file, parses it and creates a new object for
  7401. it in the program. Thread-safe.
  7402. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7403. :param filename: HPGL2 file filename
  7404. :return: None
  7405. """
  7406. filename = filename
  7407. # How the object should be initialized
  7408. def obj_init(geo_obj, app_obj):
  7409. assert isinstance(geo_obj, GeometryObject), \
  7410. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7411. # Opening the file happens here
  7412. obj = HPGL2(self)
  7413. try:
  7414. HPGL2.parse_file(obj, filename)
  7415. except IOError:
  7416. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7417. return "fail"
  7418. except ParseError as err:
  7419. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7420. app_obj.log.error(str(err))
  7421. return "fail"
  7422. except Exception as e:
  7423. log.debug("App.open_hpgl2() --> %s" % str(e))
  7424. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7425. msg += traceback.format_exc()
  7426. app_obj.inform.emit(msg)
  7427. return "fail"
  7428. geo_obj.multigeo = True
  7429. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7430. geo_obj.tools = deepcopy(obj.tools)
  7431. geo_obj.source_file = deepcopy(obj.source_file)
  7432. del obj
  7433. if not geo_obj.solid_geometry:
  7434. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7435. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7436. return "fail"
  7437. App.log.debug("open_hpgl2()")
  7438. with self.proc_container.new(_("Opening HPGL2")):
  7439. # Object name
  7440. name = outname or filename.split('/')[-1].split('\\')[-1]
  7441. # # ## Object creation # ##
  7442. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7443. if ret == 'fail':
  7444. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7445. return 'fail'
  7446. # Register recent file
  7447. self.file_opened.emit("geometry", filename)
  7448. # appGUI feedback
  7449. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7450. def open_script(self, filename, outname=None, silent=False):
  7451. """
  7452. Opens a Script file, parses it and creates a new object for
  7453. it in the program. Thread-safe.
  7454. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7455. :param filename: Script file filename
  7456. :param silent: If True there will be no messages printed to StatusBar
  7457. :return: None
  7458. """
  7459. def obj_init(script_obj, app_obj):
  7460. assert isinstance(script_obj, ScriptObject), \
  7461. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7462. if silent is False:
  7463. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7464. try:
  7465. script_obj.parse_file(filename)
  7466. except IOError:
  7467. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7468. return "fail"
  7469. except ParseError as err:
  7470. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7471. app_obj.log.error(str(err))
  7472. return "fail"
  7473. except Exception as e:
  7474. log.debug("App.open_script() -> %s" % str(e))
  7475. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7476. msg += traceback.format_exc()
  7477. app_obj.inform.emit(msg)
  7478. return "fail"
  7479. App.log.debug("open_script()")
  7480. with self.proc_container.new(_("Opening TCL Script...")):
  7481. # Object name
  7482. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7483. # Object creation
  7484. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7485. if ret_val == 'fail':
  7486. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7487. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7488. if ret_val == 'fail':
  7489. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7490. return 'fail'
  7491. # Register recent file
  7492. self.file_opened.emit("script", filename)
  7493. # appGUI feedback
  7494. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7495. def open_config_file(self, filename, run_from_arg=None):
  7496. """
  7497. Loads a config file from the specified file.
  7498. :param filename: Name of the file from which to load.
  7499. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7500. :return: None
  7501. """
  7502. App.log.debug("Opening config file: " + filename)
  7503. if run_from_arg:
  7504. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7505. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7506. _("Opening FlatCAM Config file.")),
  7507. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7508. color=QtGui.QColor("gray"))
  7509. # # add the tab if it was closed
  7510. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7511. # # first clear previous text in text editor (if any)
  7512. # self.ui.text_editor_tab.code_editor.clear()
  7513. #
  7514. # # Switch plot_area to CNCJob tab
  7515. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7516. # close the Code editor if already open
  7517. if self.toggle_codeeditor:
  7518. self.on_toggle_code_editor()
  7519. self.on_toggle_code_editor()
  7520. try:
  7521. if filename:
  7522. f = QtCore.QFile(filename)
  7523. if f.open(QtCore.QIODevice.ReadOnly):
  7524. stream = QtCore.QTextStream(f)
  7525. code_edited = stream.readAll()
  7526. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7527. f.close()
  7528. except IOError:
  7529. App.log.error("Failed to open config file: %s" % filename)
  7530. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7531. (_("Failed to open config file"), filename))
  7532. return
  7533. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7534. """
  7535. Loads a project from the specified file.
  7536. 1) Loads and parses file
  7537. 2) Registers the file as recently opened.
  7538. 3) Calls on_file_new()
  7539. 4) Updates options
  7540. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7541. 6) Calls plot_all() if plot=True
  7542. :param filename: Name of the file from which to load.
  7543. :param run_from_arg: True if run for arguments
  7544. :param plot: If True plot all objects in the project
  7545. :param cli: Run from command line
  7546. :param from_tcl: True if run from Tcl Sehll
  7547. :return: None
  7548. """
  7549. App.log.debug("Opening project: " + filename)
  7550. # block autosaving while a project is loaded
  7551. self.block_autosave = True
  7552. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7553. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7554. if cli is None:
  7555. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7556. if run_from_arg:
  7557. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7558. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7559. _("Opening FlatCAM Project file.")),
  7560. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7561. color=QtGui.QColor("gray"))
  7562. # Open and parse an uncompressed Project file
  7563. try:
  7564. f = open(filename, 'r')
  7565. except IOError:
  7566. if from_tcl:
  7567. name = filename.split('/')[-1].split('\\')[-1]
  7568. filename = self.defaults['global_tcl_path'] + '/' + name
  7569. try:
  7570. f = open(filename, 'r')
  7571. except IOError:
  7572. log.error("Failed to open project file: %s" % filename)
  7573. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7574. return
  7575. else:
  7576. log.error("Failed to open project file: %s" % filename)
  7577. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7578. return
  7579. try:
  7580. d = json.load(f, object_hook=dict2obj)
  7581. except Exception as e:
  7582. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7583. (filename, str(e)))
  7584. f.close()
  7585. # Open and parse a compressed Project file
  7586. try:
  7587. with lzma.open(filename) as f:
  7588. file_content = f.read().decode('utf-8')
  7589. d = json.loads(file_content, object_hook=dict2obj)
  7590. except Exception as e:
  7591. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7592. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7593. return
  7594. # Clear the current project
  7595. # # NOT THREAD SAFE # ##
  7596. if run_from_arg is True:
  7597. pass
  7598. elif cli is True:
  7599. self.delete_selection_shape()
  7600. else:
  7601. self.on_file_new()
  7602. # Project options
  7603. self.options.update(d['options'])
  7604. self.project_filename = filename
  7605. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7606. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7607. if cli is None:
  7608. self.set_screen_units(self.options["units"])
  7609. # Re create objects
  7610. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7611. for obj in d['objs']:
  7612. def obj_init(obj_inst, app_inst):
  7613. try:
  7614. obj_inst.from_dict(obj)
  7615. except Exception as e:
  7616. print('App.open_project() --> ' + str(e))
  7617. return 'fail'
  7618. App.log.debug("Recreating from opened project an %s object: %s" %
  7619. (obj['kind'].capitalize(), obj['options']['name']))
  7620. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7621. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7622. if cli is None:
  7623. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7624. obj['kind'].upper(),
  7625. obj['options']['name']
  7626. )
  7627. )
  7628. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7629. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7630. self.should_we_save = False
  7631. self.file_opened.emit("project", filename)
  7632. # restore autosaving after a project was loaded
  7633. self.block_autosave = False
  7634. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7635. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7636. if cli is None:
  7637. self.set_ui_title(name=self.project_filename)
  7638. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7639. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7640. """
  7641. Re-generates all plots from all objects.
  7642. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7643. :param muted: if True don't print messages
  7644. :param use_thread: if True will use threading for plotting the objects
  7645. :return: None
  7646. """
  7647. self.log.debug("Plot_all()")
  7648. if muted is not True:
  7649. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7650. for plot_obj in self.collection.get_list():
  7651. def worker_task(obj):
  7652. with self.proc_container.new("Plotting"):
  7653. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7654. if fit_view is True:
  7655. self.app_obj.object_plotted.emit(obj)
  7656. if use_thread is True:
  7657. # Send to worker
  7658. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7659. else:
  7660. worker_task(plot_obj)
  7661. def register_folder(self, filename):
  7662. """
  7663. Register the last folder used by the app to open something
  7664. :param filename: the last folder is extracted from the filename
  7665. :return: None
  7666. """
  7667. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7668. def register_save_folder(self, filename):
  7669. """
  7670. Register the last folder used by the app to save something
  7671. :param filename: the last folder is extracted from the filename
  7672. :return: None
  7673. """
  7674. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7675. # def set_progress_bar(self, percentage, text=""):
  7676. # """
  7677. # Set a progress bar to a value (percentage)
  7678. #
  7679. # :param percentage: Value set to the progressbar
  7680. # :param text: Not used
  7681. # :return: None
  7682. # """
  7683. # self.ui.progress_bar.setValue(int(percentage))
  7684. def setup_recent_items(self):
  7685. """
  7686. Setup a dictionary with the recent files accessed, organized by type
  7687. :return:
  7688. """
  7689. icons = {
  7690. "gerber": self.resource_location + "/flatcam_icon16.png",
  7691. "excellon": self.resource_location + "/drill16.png",
  7692. 'geometry': self.resource_location + "/geometry16.png",
  7693. "cncjob": self.resource_location + "/cnc16.png",
  7694. "script": self.resource_location + "/script_new24.png",
  7695. "document": self.resource_location + "/notes16_1.png",
  7696. "project": self.resource_location + "/project16.png",
  7697. "svg": self.resource_location + "/geometry16.png",
  7698. "dxf": self.resource_location + "/dxf16.png",
  7699. "pdf": self.resource_location + "/pdf32.png",
  7700. "image": self.resource_location + "/image16.png"
  7701. }
  7702. try:
  7703. image_opener = self.image_tool.import_image
  7704. except AttributeError:
  7705. image_opener = None
  7706. openers = {
  7707. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7708. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7709. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7710. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7711. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7712. "document": None,
  7713. 'project': self.open_project,
  7714. 'svg': self.import_svg,
  7715. 'dxf': self.import_dxf,
  7716. 'image': image_opener,
  7717. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7718. }
  7719. # Open recent file for files
  7720. try:
  7721. f = open(self.data_path + '/recent.json')
  7722. except IOError:
  7723. App.log.error("Failed to load recent item list.")
  7724. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7725. return
  7726. try:
  7727. self.recent = json.load(f)
  7728. except json.errors.JSONDecodeError:
  7729. App.log.error("Failed to parse recent item list.")
  7730. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7731. f.close()
  7732. return
  7733. f.close()
  7734. # Open recent file for projects
  7735. try:
  7736. fp = open(self.data_path + '/recent_projects.json')
  7737. except IOError:
  7738. App.log.error("Failed to load recent project item list.")
  7739. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7740. return
  7741. try:
  7742. self.recent_projects = json.load(fp)
  7743. except json.errors.JSONDecodeError:
  7744. App.log.error("Failed to parse recent project item list.")
  7745. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7746. fp.close()
  7747. return
  7748. fp.close()
  7749. # Closure needed to create callbacks in a loop.
  7750. # Otherwise late binding occurs.
  7751. def make_callback(func, fname):
  7752. def opener():
  7753. func(fname)
  7754. return opener
  7755. def reset_recent_files():
  7756. # Reset menu
  7757. self.ui.recent.clear()
  7758. self.recent = []
  7759. try:
  7760. ff = open(self.data_path + '/recent.json', 'w')
  7761. except IOError:
  7762. App.log.error("Failed to open recent items file for writing.")
  7763. return
  7764. json.dump(self.recent, ff)
  7765. def reset_recent_projects():
  7766. # Reset menu
  7767. self.ui.recent_projects.clear()
  7768. self.recent_projects = []
  7769. try:
  7770. frp = open(self.data_path + '/recent_projects.json', 'w')
  7771. except IOError:
  7772. App.log.error("Failed to open recent projects items file for writing.")
  7773. return
  7774. json.dump(self.recent, frp)
  7775. # Reset menu
  7776. self.ui.recent.clear()
  7777. self.ui.recent_projects.clear()
  7778. # Create menu items for projects
  7779. for recent in self.recent_projects:
  7780. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7781. if recent['kind'] == 'project':
  7782. try:
  7783. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7784. # Attach callback
  7785. o = make_callback(openers[recent["kind"]], recent['filename'])
  7786. action.triggered.connect(o)
  7787. self.ui.recent_projects.addAction(action)
  7788. except KeyError:
  7789. App.log.error("Unsupported file type: %s" % recent["kind"])
  7790. # Last action in Recent Files menu is one that Clear the content
  7791. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7792. (_("Clear Recent projects")), self)
  7793. clear_action_proj.triggered.connect(reset_recent_projects)
  7794. self.ui.recent_projects.addSeparator()
  7795. self.ui.recent_projects.addAction(clear_action_proj)
  7796. # Create menu items for files
  7797. for recent in self.recent:
  7798. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7799. if recent['kind'] != 'project':
  7800. try:
  7801. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7802. # Attach callback
  7803. o = make_callback(openers[recent["kind"]], recent['filename'])
  7804. action.triggered.connect(o)
  7805. self.ui.recent.addAction(action)
  7806. except KeyError:
  7807. App.log.error("Unsupported file type: %s" % recent["kind"])
  7808. # Last action in Recent Files menu is one that Clear the content
  7809. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7810. (_("Clear Recent files")), self)
  7811. clear_action.triggered.connect(reset_recent_files)
  7812. self.ui.recent.addSeparator()
  7813. self.ui.recent.addAction(clear_action)
  7814. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7815. # self.ui.menufilerecent.set_submenu(recent_menu)
  7816. # recent_menu.show_all()
  7817. # self.ui.recent.show()
  7818. self.log.debug("Recent items list has been populated.")
  7819. def setup_component_editor(self):
  7820. """
  7821. Default text for the Selected tab when is not taken by the Object UI.
  7822. :return:
  7823. """
  7824. # label = QtWidgets.QLabel("Choose an item from Project")
  7825. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7826. sel_title = QtWidgets.QTextEdit(
  7827. _('<b>Shortcut Key List</b>'))
  7828. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7829. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7830. f_settings = QSettings("Open Source", "FlatCAM")
  7831. if f_settings.contains("notebook_font_size"):
  7832. fsize = f_settings.value('notebook_font_size', type=int)
  7833. else:
  7834. fsize = 12
  7835. tsize = fsize + int(fsize / 2)
  7836. # selected_text = (_('''
  7837. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7838. # </p>
  7839. #
  7840. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7841. # The normal flow when working in FlatCAM is the following:</span></p>
  7842. #
  7843. # <ol>
  7844. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7845. # file into
  7846. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7847. # even dragging and dropping the files on the appGUI.<br />
  7848. # <br />
  7849. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7850. # drop of the
  7851. # file into the FLATCAM appGUI or through the menu/toolbar links offered within the app.</span><br />
  7852. # &nbsp;</li>
  7853. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7854. # and then
  7855. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7856. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7857. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7858. # <br />
  7859. # If the selection of the object is done on the canvas by single click instead, and the
  7860. # <strong>SELECTED TAB</strong>
  7861. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7862. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7863. # it even if it was out of focus.<br />
  7864. # <br />
  7865. # You can change the parameters in this screen and the flow direction is like this:<br />
  7866. # <br />
  7867. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7868. # <strong> Geometry Object
  7869. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7870. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7871. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7872. # </ol>
  7873. #
  7874. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7875. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7876. # <strong>F3</strong>.</span></p>
  7877. #
  7878. # ''').format(fsize=fsize, tsize=tsize))
  7879. selected_text = '''
  7880. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7881. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7882. {s1}</span></p>
  7883. <ol>
  7884. <li><span style="font-size:{fsize}px">{s2}<br />
  7885. <br />
  7886. {s3}</span><br />
  7887. &nbsp;</li>
  7888. <li><span style="font-size:{fsize}px">{s4}<br />
  7889. &nbsp;</li>
  7890. <br />
  7891. <li><span style="font-size:{fsize}px">{s5}<br />
  7892. &nbsp;</li>
  7893. <br />
  7894. <li><span style="font-size:{fsize}px">{s6}<br />
  7895. <br />
  7896. {s7}</span></li>
  7897. </ol>
  7898. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7899. '''.format(
  7900. title=_("Selected Tab - Choose an Item from Project Tab"),
  7901. subtitle=_("Details"),
  7902. s1=_("The normal flow when working with the application is the following:"),
  7903. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into the application "
  7904. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7905. "files on the GUI."),
  7906. s3=_("You can also load a project by double clicking on the project file, "
  7907. "drag and drop of the file into the GUI or through the menu (or toolbar) "
  7908. "actions offered within the app."),
  7909. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7910. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7911. "SELECTED TAB will be updated with the object properties according to its kind: "
  7912. "Gerber, Excellon, Geometry or CNCJob object."),
  7913. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7914. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7915. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7916. "the SELECTED TAB and populate it even if it was out of focus."),
  7917. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7918. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7919. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7920. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7921. "(again, done in SELECTED TAB) --> Save GCode."),
  7922. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7923. "or through its own key shortcut: <b>F3</b>."),
  7924. tsize=tsize,
  7925. fsize=fsize
  7926. )
  7927. sel_title.setText(selected_text)
  7928. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7929. self.ui.selected_scroll_area.setWidget(sel_title)
  7930. def setup_obj_classes(self):
  7931. """
  7932. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7933. class.
  7934. :return: None
  7935. """
  7936. FlatCAMObj.app = self
  7937. ObjectCollection.app = self
  7938. Gerber.app = self
  7939. Excellon.app = self
  7940. Geometry.app = self
  7941. CNCjob.app = self
  7942. FCProcess.app = self
  7943. FCProcessContainer.app = self
  7944. OptionsGroupUI.app = self
  7945. def version_check(self):
  7946. """
  7947. Checks for the latest version of the program. Alerts the
  7948. user if theirs is outdated. This method is meant to be run
  7949. in a separate thread.
  7950. :return: None
  7951. """
  7952. self.log.debug("version_check()")
  7953. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7954. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7955. App.version_url,
  7956. str(self.defaults['global_serial']),
  7957. str(self.version),
  7958. str(self.os),
  7959. urllib.parse.urlencode(self.defaults["global_stats"])
  7960. )
  7961. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7962. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7963. # urllib.parse.urlencode(self.defaults["global_stats"])
  7964. else:
  7965. # no_stats dict; just so it won't break things on website
  7966. no_ststs_dict = {}
  7967. no_ststs_dict["global_ststs"] = {}
  7968. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7969. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7970. App.log.debug("Checking for updates @ %s" % full_url)
  7971. # ## Get the data
  7972. try:
  7973. f = urllib.request.urlopen(full_url)
  7974. except Exception:
  7975. # App.log.warning("Failed checking for latest version. Could not connect.")
  7976. self.log.warning("Failed checking for latest version. Could not connect.")
  7977. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7978. return
  7979. try:
  7980. data = json.load(f)
  7981. except Exception as e:
  7982. App.log.error("Could not parse information about latest version.")
  7983. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7984. App.log.debug("json.load(): %s" % str(e))
  7985. f.close()
  7986. return
  7987. f.close()
  7988. # ## Latest version?
  7989. if self.version >= data["version"]:
  7990. App.log.debug("FlatCAM is up to date!")
  7991. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7992. return
  7993. App.log.debug("Newer version available.")
  7994. self.message.emit(
  7995. _("Newer Version Available"),
  7996. '%s<br><br>><b>%s</b><br>%s' % (
  7997. _("There is a newer version of FlatCAM available for download:"),
  7998. str(data["name"]),
  7999. str(data["message"])
  8000. ),
  8001. _("info")
  8002. )
  8003. def on_plotcanvas_setup(self, container=None):
  8004. """
  8005. This is doing the setup for the plot area (canvas).
  8006. :param container: QT Widget where to install the canvas
  8007. :return: None
  8008. """
  8009. if container:
  8010. plot_container = container
  8011. else:
  8012. plot_container = self.ui.right_layout
  8013. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8014. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8015. self.is_legacy = True
  8016. self.defaults["global_graphic_engine"] = "2D"
  8017. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8018. else:
  8019. try:
  8020. self.plotcanvas = PlotCanvas(plot_container, self)
  8021. except Exception as er:
  8022. msg_txt = traceback.format_exc()
  8023. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8024. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8025. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8026. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8027. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8028. msg += msg_txt
  8029. self.inform.emit(msg)
  8030. return 'fail'
  8031. # So it can receive key presses
  8032. self.plotcanvas.native.setFocus()
  8033. if self.is_legacy is False:
  8034. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8035. # Set the mouse button for panning
  8036. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8037. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8038. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8039. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8040. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8041. # Keys over plot enabled
  8042. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8043. if self.defaults['global_cursor_type'] == 'small':
  8044. self.app_cursor = self.plotcanvas.new_cursor()
  8045. else:
  8046. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8047. if self.ui.grid_snap_btn.isChecked():
  8048. self.app_cursor.enabled = True
  8049. else:
  8050. self.app_cursor.enabled = False
  8051. if self.is_legacy is False:
  8052. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8053. else:
  8054. # will use the default Matplotlib axes
  8055. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8056. def on_zoom_fit(self):
  8057. """
  8058. Callback for zoom-fit request. This can be either from the corresponding
  8059. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8060. with axes limits from the geometry bounds of all objects.
  8061. :return: None
  8062. """
  8063. if self.is_legacy is False:
  8064. self.plotcanvas.fit_view()
  8065. else:
  8066. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8067. width = xmax - xmin
  8068. height = ymax - ymin
  8069. xmin -= 0.05 * width
  8070. xmax += 0.05 * width
  8071. ymin -= 0.05 * height
  8072. ymax += 0.05 * height
  8073. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8074. def on_zoom_in(self):
  8075. """
  8076. Callback for zoom-in request.
  8077. :return:
  8078. """
  8079. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8080. def on_zoom_out(self):
  8081. """
  8082. Callback for zoom-out request.
  8083. :return:
  8084. """
  8085. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8086. def disable_all_plots(self):
  8087. self.defaults.report_usage("disable_all_plots()")
  8088. self.disable_plots(self.collection.get_list())
  8089. self.inform.emit('[success] %s' %
  8090. _("All plots disabled."))
  8091. def disable_other_plots(self):
  8092. self.defaults.report_usage("disable_other_plots()")
  8093. self.disable_plots(self.collection.get_non_selected())
  8094. self.inform.emit('[success] %s' %
  8095. _("All non selected plots disabled."))
  8096. def enable_all_plots(self):
  8097. self.defaults.report_usage("enable_all_plots()")
  8098. self.enable_plots(self.collection.get_list())
  8099. self.inform.emit('[success] %s' %
  8100. _("All plots enabled."))
  8101. def on_enable_sel_plots(self):
  8102. log.debug("App.on_enable_sel_plot()")
  8103. object_list = self.collection.get_selected()
  8104. self.enable_plots(objects=object_list)
  8105. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8106. def on_disable_sel_plots(self):
  8107. log.debug("App.on_disable_sel_plot()")
  8108. # self.inform.emit(_("Disabling plots ..."))
  8109. object_list = self.collection.get_selected()
  8110. self.disable_plots(objects=object_list)
  8111. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8112. def enable_plots(self, objects):
  8113. """
  8114. Enable plots
  8115. :param objects: list of Objects to be enabled
  8116. :return:
  8117. """
  8118. log.debug("Enabling plots ...")
  8119. # self.inform.emit(_("Working ..."))
  8120. for obj in objects:
  8121. if obj.options['plot'] is False:
  8122. obj.options.set_change_callback(lambda x: None)
  8123. obj.options['plot'] = True
  8124. try:
  8125. # only the Gerber obj has on_plot_cb_click() method
  8126. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8127. # disable this cb while disconnected,
  8128. # in case the operation takes time the user is not allowed to change it
  8129. obj.ui.plot_cb.setDisabled(True)
  8130. except AttributeError:
  8131. pass
  8132. obj.set_form_item("plot")
  8133. try:
  8134. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8135. obj.ui.plot_cb.setDisabled(False)
  8136. except AttributeError:
  8137. pass
  8138. obj.options.set_change_callback(obj.on_options_change)
  8139. def worker_task(objs):
  8140. with self.proc_container.new(_("Enabling plots ...")):
  8141. for plot_obj in objs:
  8142. # obj.options['plot'] = True
  8143. if isinstance(plot_obj, CNCJobObject):
  8144. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8145. else:
  8146. plot_obj.plot(visible=True)
  8147. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8148. def disable_plots(self, objects):
  8149. """
  8150. Disables plots
  8151. :param objects: list of Objects to be disabled
  8152. :return:
  8153. """
  8154. # if no objects selected then do nothing
  8155. if not self.collection.get_selected():
  8156. return
  8157. log.debug("Disabling plots ...")
  8158. # self.inform.emit(_("Working ..."))
  8159. for obj in objects:
  8160. if obj.options['plot'] is True:
  8161. obj.options.set_change_callback(lambda x: None)
  8162. obj.options['plot'] = False
  8163. try:
  8164. # only the Gerber obj has on_plot_cb_click() method
  8165. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8166. obj.ui.plot_cb.setDisabled(True)
  8167. except AttributeError:
  8168. pass
  8169. obj.set_form_item("plot")
  8170. try:
  8171. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8172. obj.ui.plot_cb.setDisabled(False)
  8173. except AttributeError:
  8174. pass
  8175. obj.options.set_change_callback(obj.on_options_change)
  8176. try:
  8177. self.delete_selection_shape()
  8178. except Exception as e:
  8179. log.debug("App.disable_plots() --> %s" % str(e))
  8180. def worker_task(objs):
  8181. with self.proc_container.new(_("Disabling plots ...")):
  8182. for plot_obj in objs:
  8183. # obj.options['plot'] = True
  8184. if isinstance(plot_obj, CNCJobObject):
  8185. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8186. else:
  8187. plot_obj.plot(visible=False)
  8188. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8189. def toggle_plots(self, objects):
  8190. """
  8191. Toggle plots visibility
  8192. :param objects: list of Objects for which to be toggled the visibility
  8193. :return: None
  8194. """
  8195. # if no objects selected then do nothing
  8196. if not self.collection.get_selected():
  8197. return
  8198. log.debug("Toggling plots ...")
  8199. self.inform.emit(_("Working ..."))
  8200. for obj in objects:
  8201. if obj.options['plot'] is False:
  8202. obj.options['plot'] = True
  8203. else:
  8204. obj.options['plot'] = False
  8205. self.app_obj.plots_updated.emit()
  8206. def clear_plots(self):
  8207. """
  8208. Clear the plots
  8209. :return: None
  8210. """
  8211. objects = self.collection.get_list()
  8212. for obj in objects:
  8213. obj.clear(obj == objects[-1])
  8214. # Clear pool to free memory
  8215. self.clear_pool()
  8216. def on_set_color_action_triggered(self):
  8217. """
  8218. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8219. :return:
  8220. """
  8221. new_color = self.defaults['gerber_plot_fill']
  8222. clicked_action = self.sender()
  8223. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8224. act_name = clicked_action.text()
  8225. sel_obj_list = self.collection.get_selected()
  8226. if not sel_obj_list:
  8227. return
  8228. # a default value, I just chose this one
  8229. alpha_level = 'BF'
  8230. for sel_obj in sel_obj_list:
  8231. if sel_obj.kind == 'excellon':
  8232. alpha_level = str(hex(
  8233. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  8234. elif sel_obj.kind == 'gerber':
  8235. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  8236. elif sel_obj.kind == 'geometry':
  8237. alpha_level = 'FF'
  8238. else:
  8239. log.debug(
  8240. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8241. continue
  8242. sel_obj.alpha_level = alpha_level
  8243. if act_name == _('Red'):
  8244. new_color = '#FF0000' + alpha_level
  8245. if act_name == _('Blue'):
  8246. new_color = '#0000FF' + alpha_level
  8247. if act_name == _('Yellow'):
  8248. new_color = '#FFDF00' + alpha_level
  8249. if act_name == _('Green'):
  8250. new_color = '#00FF00' + alpha_level
  8251. if act_name == _('Purple'):
  8252. new_color = '#FF00FF' + alpha_level
  8253. if act_name == _('Brown'):
  8254. new_color = '#A52A2A' + alpha_level
  8255. if act_name == _('White'):
  8256. new_color = '#FFFFFF' + alpha_level
  8257. if act_name == _('Black'):
  8258. new_color = '#000000' + alpha_level
  8259. if act_name == _('Custom'):
  8260. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8261. c_dialog = QtWidgets.QColorDialog()
  8262. plot_fill_color = c_dialog.getColor(initial=new_color)
  8263. if plot_fill_color.isValid() is False:
  8264. return
  8265. new_color = str(plot_fill_color.name()) + alpha_level
  8266. if act_name == _("Default"):
  8267. for sel_obj in sel_obj_list:
  8268. if sel_obj.kind == 'excellon':
  8269. new_color = self.defaults['excellon_plot_fill']
  8270. new_line_color = self.defaults['excellon_plot_line']
  8271. elif sel_obj.kind == 'gerber':
  8272. new_color = self.defaults['gerber_plot_fill']
  8273. new_line_color = self.defaults['gerber_plot_line']
  8274. elif sel_obj.kind == 'geometry':
  8275. new_color = self.defaults['geometry_plot_line']
  8276. new_line_color = self.defaults['geometry_plot_line']
  8277. else:
  8278. log.debug(
  8279. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8280. continue
  8281. sel_obj.fill_color = new_color
  8282. sel_obj.outline_color = new_line_color
  8283. sel_obj.shapes.redraw(
  8284. update_colors=(new_color, new_line_color)
  8285. )
  8286. return
  8287. if act_name == _("Opacity"):
  8288. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8289. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8290. if ok_button:
  8291. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8292. for sel_obj in sel_obj_list:
  8293. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8294. sel_obj.shapes.redraw(
  8295. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8296. )
  8297. return
  8298. new_line_color = color_variant(new_color[:7], 0.7)
  8299. if act_name == _("White"):
  8300. new_line_color = color_variant("#dedede", 0.7)
  8301. for sel_obj in sel_obj_list:
  8302. sel_obj.fill_color = new_color
  8303. sel_obj.outline_color = new_line_color
  8304. sel_obj.shapes.redraw(
  8305. update_colors=(new_color, new_line_color)
  8306. )
  8307. def generate_cnc_job(self, objects):
  8308. """
  8309. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8310. :param objects: Selected objects in the Project Tab
  8311. :return:
  8312. """
  8313. self.defaults.report_usage("generate_cnc_job()")
  8314. # for obj in objects:
  8315. # obj.generatecncjob()
  8316. for obj in objects:
  8317. obj.on_generatecnc_button_click()
  8318. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8319. """
  8320. Saves the current project to the specified file.
  8321. :param filename: Name of the file in which to save.
  8322. :type filename: str
  8323. :param quit_action: if the project saving will be followed by an app quit; boolean
  8324. :param silent: if True will not display status messages
  8325. :param from_tcl True is run from Tcl Shell
  8326. :return: None
  8327. """
  8328. self.log.debug("save_project()")
  8329. self.save_in_progress = True
  8330. with self.proc_container.new(_("Saving FlatCAM Project")):
  8331. # Capture the latest changes
  8332. # Current object
  8333. try:
  8334. current_object = self.collection.get_active()
  8335. if current_object:
  8336. current_object.read_form()
  8337. except Exception as e:
  8338. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8339. pass
  8340. # Serialize the whole project
  8341. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8342. "options": self.options,
  8343. "version": self.version}
  8344. if self.defaults["global_save_compressed"] is True:
  8345. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8346. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8347. # # Write
  8348. f.write(g)
  8349. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8350. else:
  8351. # Open file
  8352. try:
  8353. f = open(filename, 'w')
  8354. except IOError:
  8355. App.log.error("Failed to open file for saving: %s", filename)
  8356. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8357. return
  8358. # Write
  8359. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8360. f.close()
  8361. # verification of the saved project
  8362. # Open and parse
  8363. try:
  8364. saved_f = open(filename, 'r')
  8365. except IOError:
  8366. if silent is False:
  8367. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8368. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8369. return
  8370. try:
  8371. saved_d = json.load(saved_f, object_hook=dict2obj)
  8372. except Exception:
  8373. if silent is False:
  8374. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8375. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8376. f.close()
  8377. return
  8378. saved_f.close()
  8379. if silent is False:
  8380. if 'version' in saved_d:
  8381. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8382. else:
  8383. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8384. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8385. tb_settings = QSettings("Open Source", "FlatCAM")
  8386. lock_state = self.ui.lock_action.isChecked()
  8387. tb_settings.setValue('toolbar_lock', lock_state)
  8388. # This will write the setting to the platform specific storage.
  8389. del tb_settings
  8390. # if quit:
  8391. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8392. # t.start()
  8393. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8394. def start_delayed_quit(self, delay, filename, should_quit=None):
  8395. """
  8396. :param delay: period of checking if project file size is more than zero; in seconds
  8397. :param filename: the name of the project file to be checked periodically for size more than zero
  8398. :param should_quit: if the task finished will be followed by an app quit; boolean
  8399. :return:
  8400. """
  8401. to_quit = should_quit
  8402. self.save_timer = QtCore.QTimer()
  8403. self.save_timer.setInterval(delay)
  8404. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8405. self.save_timer.start()
  8406. def check_project_file_size(self, filename, should_quit=None):
  8407. """
  8408. :param filename: the name of the project file to be checked periodically for size more than zero
  8409. :param should_quit: will quit the app if True; boolean
  8410. :return:
  8411. """
  8412. try:
  8413. if os.stat(filename).st_size > 0:
  8414. self.save_in_progress = False
  8415. self.save_timer.stop()
  8416. if should_quit:
  8417. self.app_quit.emit()
  8418. except Exception:
  8419. traceback.print_exc()
  8420. def save_project_auto(self):
  8421. """
  8422. Called periodically to save the project.
  8423. 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
  8424. # progress.
  8425. :return:
  8426. """
  8427. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8428. self.on_file_saveproject()
  8429. def save_project_auto_update(self):
  8430. """
  8431. Update the auto save time interval value.
  8432. :return:
  8433. """
  8434. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8435. try:
  8436. if self.autosave_timer.isActive():
  8437. self.autosave_timer.stop()
  8438. except Exception:
  8439. pass
  8440. if self.defaults['global_autosave'] is True:
  8441. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8442. self.autosave_timer.start()
  8443. def on_options_app2project(self):
  8444. """
  8445. Callback for Options->Transfer Options->App=>Project. Copies options
  8446. from application defaults to project defaults.
  8447. :return: None
  8448. """
  8449. self.defaults.report_usage("on_options_app2project")
  8450. self.preferencesUiManager.defaults_read_form()
  8451. self.options.update(self.defaults)
  8452. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8453. """
  8454. Shows a message on the FlatCAM Shell
  8455. :param msg: Message to display.
  8456. :param show: Opens the shell.
  8457. :param error: Shows the message as an error.
  8458. :param warning: Shows the message as an warning.
  8459. :param success: Shows the message as an success.
  8460. :param selected: Indicate that something was selected on canvas
  8461. :return: None
  8462. """
  8463. if show:
  8464. self.ui.shell_dock.show()
  8465. try:
  8466. if error:
  8467. self.shell.append_error(msg + "\n")
  8468. elif warning:
  8469. self.shell.append_warning(msg + "\n")
  8470. elif success:
  8471. self.shell.append_success(msg + "\n")
  8472. elif selected:
  8473. self.shell.append_selected(msg + "\n")
  8474. else:
  8475. self.shell.append_output(msg + "\n")
  8476. except AttributeError:
  8477. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8478. class ArgsThread(QtCore.QObject):
  8479. open_signal = pyqtSignal(list)
  8480. start = pyqtSignal()
  8481. stop = pyqtSignal()
  8482. if sys.platform == 'win32':
  8483. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8484. else:
  8485. address = ('/tmp/testipc', 'AF_UNIX')
  8486. def __init__(self):
  8487. super().__init__()
  8488. self.listener = None
  8489. self.thread_exit = False
  8490. self.start.connect(self.run)
  8491. self.stop.connect(self.close_listener)
  8492. def my_loop(self, address):
  8493. try:
  8494. self.listener = Listener(*address)
  8495. while self.thread_exit is False:
  8496. conn = self.listener.accept()
  8497. self.serve(conn)
  8498. except socket.error:
  8499. try:
  8500. conn = Client(*address)
  8501. conn.send(sys.argv)
  8502. conn.send('close')
  8503. # close the current instance only if there are args
  8504. if len(sys.argv) > 1:
  8505. try:
  8506. self.listener.close()
  8507. except Exception:
  8508. pass
  8509. sys.exit()
  8510. except ConnectionRefusedError:
  8511. if sys.platform == 'win32':
  8512. pass
  8513. else:
  8514. os.system('rm /tmp/testipc')
  8515. self.listener = Listener(*address)
  8516. while True:
  8517. conn = self.listener.accept()
  8518. self.serve(conn)
  8519. def serve(self, conn):
  8520. while self.thread_exit is False:
  8521. msg = conn.recv()
  8522. if msg == 'close':
  8523. break
  8524. self.open_signal.emit(msg)
  8525. conn.close()
  8526. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8527. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8528. @pyqtSlot()
  8529. def run(self):
  8530. self.my_loop(self.address)
  8531. @pyqtSlot()
  8532. def close_listener(self):
  8533. self.thread_exit = True
  8534. self.listener.close()
  8535. # end of file