app_Main.py 469 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432
  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 appEditors.appGCodeEditor import AppGCodeEditor
  70. from appParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from appProcess import *
  73. from appWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from appTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import appTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI and all other classes used by the program.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = "Unstable Version"
  138. # version = 8.994
  139. version_date = "2020/07/05"
  140. beta = True
  141. engine = '3D'
  142. # current date now
  143. date = str(datetime.today()).rpartition('.')[0]
  144. date = ''.join(c for c in date if c not in ':-')
  145. date = date.replace(' ', '_')
  146. # ###############################################################################################################
  147. # ############################################ URLS's ###########################################################
  148. # ###############################################################################################################
  149. # URL for update checks and statistics
  150. version_url = "http://flatcam.org/version"
  151. # App URL
  152. app_url = "http://flatcam.org"
  153. # Manual URL
  154. manual_url = "http://flatcam.org/manual/index.html"
  155. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  156. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  157. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  158. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  159. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  160. # this variable will hold the project status
  161. # if True it will mean that the project was modified and not saved
  162. should_we_save = False
  163. # flag is True if saving action has been triggered
  164. save_in_progress = False
  165. # ###############################################################################################################
  166. # ####################################### APP Signals ######################################################
  167. # ###############################################################################################################
  168. # Inform the user
  169. # Handled by: App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal([str], [str, bool])
  171. # Handled by: App.info_shell() --> Print on the shell
  172. inform_shell = QtCore.pyqtSignal(str)
  173. app_quit = QtCore.pyqtSignal()
  174. # General purpose background task
  175. worker_task = QtCore.pyqtSignal(dict)
  176. # File opened
  177. # Handled by:
  178. # * register_folder()
  179. # * register_recent()
  180. # Note: Setting the parameters to unicode does not seem
  181. # to have an effect. Then are received as Qstring
  182. # anyway.
  183. # File type and filename
  184. file_opened = QtCore.pyqtSignal(str, str)
  185. # File type and filename
  186. file_saved = QtCore.pyqtSignal(str, str)
  187. # Percentage of progress
  188. progress = QtCore.pyqtSignal(int)
  189. # Emitted when a new object has been added or deleted from/to the collection
  190. object_status_changed = QtCore.pyqtSignal(object, str, str)
  191. message = QtCore.pyqtSignal(str, str, str)
  192. # Emmited when shell command is finished(one command only)
  193. shell_command_finished = QtCore.pyqtSignal(object)
  194. # Emitted when multiprocess pool has been recreated
  195. pool_recreated = QtCore.pyqtSignal(object)
  196. # Emitted when an unhandled exception happens
  197. # in the worker task.
  198. thread_exception = QtCore.pyqtSignal(object)
  199. # used to signal that there are arguments for the app
  200. args_at_startup = QtCore.pyqtSignal(list)
  201. # a reusable signal to replot a list of objects
  202. # should be disconnected after use so it can be reused
  203. replot_signal = pyqtSignal(list)
  204. # signal emitted when jumping
  205. jump_signal = pyqtSignal(tuple)
  206. # signal emitted when jumping
  207. locate_signal = pyqtSignal(tuple, str)
  208. # close app signal
  209. close_app_signal = pyqtSignal()
  210. # will perform the cleanup operation after a Graceful Exit
  211. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  212. # graphic residues behind
  213. cleanup = pyqtSignal()
  214. def __init__(self, user_defaults=True):
  215. """
  216. Starts the application.
  217. :return: app
  218. :rtype: App
  219. """
  220. super().__init__()
  221. App.log.info("FlatCAM Starting...")
  222. # ############################################################################################################
  223. # ################# Setup the listening thread for another instance launching with args ######################
  224. # ############################################################################################################
  225. if sys.platform == 'win32' or sys.platform == 'linux':
  226. # make sure the thread is stored by using a self. otherwise it's garbage collected
  227. self.listen_th = QtCore.QThread()
  228. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  229. self.new_launch = ArgsThread()
  230. self.new_launch.open_signal[list].connect(self.on_startup_args)
  231. self.new_launch.moveToThread(self.listen_th)
  232. self.new_launch.start.emit()
  233. # ############################################################################################################
  234. # ########################################## OS-specific #####################################################
  235. # ############################################################################################################
  236. portable = False
  237. # Folder for user settings.
  238. if sys.platform == 'win32':
  239. if platform.architecture()[0] == '32bit':
  240. App.log.debug("Win32!")
  241. else:
  242. App.log.debug("Win64!")
  243. # #######################################################################################################
  244. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  245. # #######################################################################################################
  246. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  247. try:
  248. with open(config_file, 'r'):
  249. pass
  250. except FileNotFoundError:
  251. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r') as f:
  254. try:
  255. for line in f:
  256. param = str(line).replace('\n', '').rpartition('=')
  257. if param[0] == 'portable':
  258. try:
  259. portable = eval(param[2])
  260. except NameError:
  261. portable = False
  262. if param[0] == 'headless':
  263. if param[2].lower() == 'true':
  264. self.cmd_line_headless = 1
  265. else:
  266. self.cmd_line_headless = None
  267. except Exception as e:
  268. log.debug('App.__init__() -->%s' % str(e))
  269. return
  270. except FileNotFoundError as e:
  271. log.debug(str(e))
  272. pass
  273. if portable is False:
  274. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  275. else:
  276. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  277. self.os = 'windows'
  278. else: # Linux/Unix/MacOS
  279. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  280. self.os = 'unix'
  281. # ############################################################################################################
  282. # ################################# Setup folders and files ##################################################
  283. # ############################################################################################################
  284. if not os.path.exists(self.data_path):
  285. os.makedirs(self.data_path)
  286. App.log.debug('Created data folder: ' + self.data_path)
  287. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  288. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  289. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  290. if not os.path.exists(self.preprocessorpaths):
  291. os.makedirs(self.preprocessorpaths)
  292. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  293. # create tools_db.FlatDB file if there is none
  294. try:
  295. f = open(self.data_path + '/tools_db.FlatDB')
  296. f.close()
  297. except IOError:
  298. App.log.debug('Creating empty tools_db.FlatDB')
  299. f = open(self.data_path + '/tools_db.FlatDB', 'w')
  300. json.dump({}, f)
  301. f.close()
  302. # create current_defaults.FlatConfig file if there is none
  303. try:
  304. f = open(self.data_path + '/current_defaults.FlatConfig')
  305. f.close()
  306. except IOError:
  307. App.log.debug('Creating empty current_defaults.FlatConfig')
  308. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  309. json.dump({}, f)
  310. f.close()
  311. # the factory defaults are written only once at the first launch of the application after installation
  312. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  313. # create a recent files json file if there is none
  314. try:
  315. f = open(self.data_path + '/recent.json')
  316. f.close()
  317. except IOError:
  318. App.log.debug('Creating empty recent.json')
  319. f = open(self.data_path + '/recent.json', 'w')
  320. json.dump([], f)
  321. f.close()
  322. # create a recent projects json file if there is none
  323. try:
  324. fp = open(self.data_path + '/recent_projects.json')
  325. fp.close()
  326. except IOError:
  327. App.log.debug('Creating empty recent_projects.json')
  328. fp = open(self.data_path + '/recent_projects.json', 'w')
  329. json.dump([], fp)
  330. fp.close()
  331. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  332. # This will fail under cx_freeze ...
  333. self.app_home = os.path.dirname(os.path.realpath(__file__))
  334. log.debug("Application path is " + self.app_home)
  335. log.debug("Started in " + os.getcwd())
  336. # cx_freeze workaround
  337. if os.path.isfile(self.app_home):
  338. self.app_home = os.path.dirname(self.app_home)
  339. os.chdir(self.app_home)
  340. # ############################################################################################################
  341. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  342. # ############################################################################################################
  343. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  344. self.defaults["root_folder_path"] = self.app_home
  345. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  346. if user_defaults:
  347. self.defaults.load(filename=current_defaults_path)
  348. if self.defaults['units'] == 'MM':
  349. self.decimals = int(self.defaults['decimals_metric'])
  350. else:
  351. self.decimals = int(self.defaults['decimals_inch'])
  352. if self.defaults["global_gray_icons"] is False:
  353. self.resource_location = 'assets/resources'
  354. else:
  355. self.resource_location = 'assets/resources/dark_resources'
  356. self.current_units = self.defaults['units']
  357. # ###########################################################################################################
  358. # #################################### SETUP OBJECT CLASSES #################################################
  359. # ###########################################################################################################
  360. self.setup_obj_classes()
  361. # ###########################################################################################################
  362. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  363. # ###########################################################################################################
  364. self.pool = Pool()
  365. # ###########################################################################################################
  366. # ###################################### Clear GUI Settings - once at first start ###########################
  367. # ###########################################################################################################
  368. if self.defaults["first_run"] is True:
  369. # on first run clear the previous QSettings, therefore clearing the GUI settings
  370. qsettings = QSettings("Open Source", "FlatCAM")
  371. for key in qsettings.allKeys():
  372. qsettings.remove(key)
  373. # This will write the setting to the platform specific storage.
  374. del qsettings
  375. # ###########################################################################################################
  376. # ###################################### Setting the Splash Screen ##########################################
  377. # ###########################################################################################################
  378. splash_settings = QSettings("Open Source", "FlatCAM")
  379. if splash_settings.contains("splash_screen"):
  380. show_splash = splash_settings.value("splash_screen")
  381. else:
  382. splash_settings.setValue('splash_screen', 1)
  383. # This will write the setting to the platform specific storage.
  384. del splash_settings
  385. show_splash = 1
  386. if show_splash and self.cmd_line_headless != 1:
  387. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  388. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  389. # self.splash.setMask(splash_pix.mask())
  390. # move splashscreen to the current monitor
  391. desktop = QtWidgets.QApplication.desktop()
  392. screen = desktop.screenNumber(QtGui.QCursor.pos())
  393. current_screen_center = desktop.availableGeometry(screen).center()
  394. self.splash.move(current_screen_center - self.splash.rect().center())
  395. self.splash.show()
  396. self.splash.showMessage(_("FlatCAM is initializing ..."),
  397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  398. color=QtGui.QColor("gray"))
  399. else:
  400. show_splash = 0
  401. # ###########################################################################################################
  402. # ######################################### Initialize GUI ##################################################
  403. # ###########################################################################################################
  404. # FlatCAM colors used in plotting
  405. self.FC_light_green = '#BBF268BF'
  406. self.FC_dark_green = '#006E20BF'
  407. self.FC_light_blue = '#a5a5ffbf'
  408. self.FC_dark_blue = '#0000ffbf'
  409. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  410. if theme_settings.contains("theme"):
  411. theme = theme_settings.value('theme', type=str)
  412. else:
  413. theme = 'white'
  414. if self.defaults["global_cursor_color_enabled"]:
  415. self.cursor_color_3D = self.defaults["global_cursor_color"]
  416. else:
  417. if theme == 'white':
  418. self.cursor_color_3D = 'black'
  419. else:
  420. self.cursor_color_3D = 'gray'
  421. # update the defaults dict with the setting in QSetting
  422. self.defaults['global_theme'] = theme
  423. self.ui = MainGUI(self)
  424. # set FlatCAM units in the Status bar
  425. self.set_screen_units(self.defaults['units'])
  426. # ###########################################################################################################
  427. # ########################################### AUTOSAVE SETUP ################################################
  428. # ###########################################################################################################
  429. self.block_autosave = False
  430. self.autosave_timer = QtCore.QTimer(self)
  431. self.save_project_auto_update()
  432. self.autosave_timer.timeout.connect(self.save_project_auto)
  433. # ###########################################################################################################
  434. # #################################### LOAD PREPROCESSORS ###################################################
  435. # ###########################################################################################################
  436. # ----------------------------------------- WARNING --------------------------------------------------------
  437. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  438. # That's because the number of preprocessors can vary and here the comboboxes are populated
  439. # -----------------------------------------------------------------------------------------------------------
  440. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  441. # the preprocessor file
  442. self.preprocessors = load_preprocessors(self)
  443. # make sure that always the 'default' preprocessor is the first item in the dictionary
  444. if 'default' in self.preprocessors.keys():
  445. new_ppp_dict = {}
  446. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  447. default_pp = self.preprocessors.pop('default')
  448. new_ppp_dict['default'] = default_pp
  449. # then add the rest of the keys
  450. for name, val_class in self.preprocessors.items():
  451. new_ppp_dict[name] = val_class
  452. # and now put back the ordered dict with 'default' key first
  453. self.preprocessors = new_ppp_dict
  454. # populate the Preprocessor ComboBoxes in the PREFERENCES
  455. for name in list(self.preprocessors.keys()):
  456. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  457. if name.partition('_')[0] == 'Paste':
  458. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  459. continue
  460. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  461. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  462. if name == 'hpgl':
  463. continue
  464. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  465. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  466. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  467. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  468. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  469. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  470. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  471. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  472. QtCore.Qt.ToolTipRole)
  473. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  474. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  475. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  476. QtCore.Qt.ToolTipRole)
  477. # ###########################################################################################################
  478. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  479. # ###########################################################################################################
  480. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  481. inform=self.inform)
  482. self.preferencesUiManager.defaults_write_form()
  483. # When the self.defaults dictionary changes will update the Preferences GUI forms
  484. self.defaults.set_change_callback(self.on_defaults_dict_change)
  485. # ###########################################################################################################
  486. # ##################################### FIRST RUN SECTION ###################################################
  487. # ################################ It's done only once after install #####################################
  488. # ###########################################################################################################
  489. if self.defaults["first_run"] is True:
  490. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  491. initial_lay = 'minimal'
  492. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  493. # Set the combobox in Preferences to the current layout
  494. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  495. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  496. # after the first run, this object should be False
  497. self.defaults["first_run"] = False
  498. self.preferencesUiManager.save_defaults(silent=True)
  499. # ###########################################################################################################
  500. # ############################################ Data #########################################################
  501. # ###########################################################################################################
  502. self.recent = []
  503. self.recent_projects = []
  504. self.clipboard = QtWidgets.QApplication.clipboard()
  505. self.project_filename = None
  506. self.toggle_units_ignore = False
  507. self.main_thread = QtWidgets.QApplication.instance().thread()
  508. # ###########################################################################################################
  509. # ########################################## LOAD LANGUAGES ################################################
  510. # ###########################################################################################################
  511. self.languages = fcTranslate.load_languages()
  512. for name in sorted(self.languages.values()):
  513. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  514. # ###########################################################################################################
  515. # ####################################### APPLY APP LANGUAGE ################################################
  516. # ###########################################################################################################
  517. ret_val = fcTranslate.apply_language('strings')
  518. if ret_val == "no language":
  519. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  520. log.debug("Could not find the Language files. The App strings are missing.")
  521. else:
  522. # make the current language the current selection on the language combobox
  523. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  524. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  525. # ###########################################################################################################
  526. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  527. # ###########################################################################################################
  528. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  529. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  530. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  531. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  532. self.defaults.propagate_defaults()
  533. # ###########################################################################################################
  534. # ######################################## UPDATE THE OPTIONS ###############################################
  535. # ###########################################################################################################
  536. self.options = LoudDict()
  537. # -----------------------------------------------------------------------------------------------------------
  538. # Update the self.options from the self.defaults
  539. # The self.defaults holds the application defaults while the self.options holds the object defaults
  540. # -----------------------------------------------------------------------------------------------------------
  541. # Copy app defaults to project options
  542. for def_key, def_val in self.defaults.items():
  543. self.options[def_key] = deepcopy(def_val)
  544. self.preferencesUiManager.show_preferences_gui()
  545. # ### End of Data ####
  546. # ###########################################################################################################
  547. # #################################### SETUP OBJECT COLLECTION ##############################################
  548. # ###########################################################################################################
  549. self.collection = ObjectCollection(app=self)
  550. self.ui.project_tab_layout.addWidget(self.collection.view)
  551. self.app_obj = AppObject(app=self)
  552. # ### Adjust tabs width ## ##
  553. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  554. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  555. self.collection.view.setMinimumWidth(290)
  556. self.log.debug("Finished creating Object Collection.")
  557. # ###########################################################################################################
  558. # ######################################## SETUP Plot Area ##################################################
  559. # ###########################################################################################################
  560. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  561. if self.defaults["global_graphic_engine"] == '3D':
  562. self.is_legacy = False
  563. else:
  564. self.is_legacy = True
  565. # Event signals disconnect id holders
  566. self.mp = None
  567. self.mm = None
  568. self.mr = None
  569. self.mdc = None
  570. self.mp_zc = None
  571. self.kp = None
  572. # Matplotlib axis
  573. self.axes = None
  574. if show_splash:
  575. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  576. "Canvas initialization started."),
  577. alignment=Qt.AlignBottom | Qt.AlignLeft,
  578. color=QtGui.QColor("gray"))
  579. start_plot_time = time.time() # debug
  580. self.plotcanvas = None
  581. self.app_cursor = None
  582. self.hover_shapes = None
  583. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  584. # setup the PlotCanvas
  585. self.on_plotcanvas_setup()
  586. end_plot_time = time.time()
  587. self.used_time = end_plot_time - start_plot_time
  588. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  589. if show_splash:
  590. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  591. "Canvas initialization started.\n"
  592. "Canvas initialization finished in"), '%.2f' % self.used_time),
  593. alignment=Qt.AlignBottom | Qt.AlignLeft,
  594. color=QtGui.QColor("gray"))
  595. self.ui.splitter.setStretchFactor(1, 2)
  596. # ###########################################################################################################
  597. # ############################################### SYS TRAY ##################################################
  598. # ###########################################################################################################
  599. if self.defaults["global_systray_icon"]:
  600. self.parent_w = QtWidgets.QWidget()
  601. if self.cmd_line_headless == 1:
  602. self.trayIcon = FlatCAMSystemTray(app=self,
  603. icon=QtGui.QIcon(self.resource_location +
  604. '/flatcam_icon32_green.png'),
  605. headless=True,
  606. parent=self.parent_w)
  607. else:
  608. self.trayIcon = FlatCAMSystemTray(app=self,
  609. icon=QtGui.QIcon(self.resource_location +
  610. '/flatcam_icon32_green.png'),
  611. parent=self.parent_w)
  612. # ###########################################################################################################
  613. # ############################################### Worker SETUP ##############################################
  614. # ###########################################################################################################
  615. if self.defaults["global_worker_number"]:
  616. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  617. else:
  618. self.workers = WorkerStack(workers_number=2)
  619. self.worker_task.connect(self.workers.add_task)
  620. self.log.debug("Finished creating Workers crew.")
  621. # ###########################################################################################################
  622. # ############################################# Activity Monitor ###########################################
  623. # ###########################################################################################################
  624. # self.activity_view = FlatCAMActivityView(app=self)
  625. # self.ui.infobar.addWidget(self.activity_view)
  626. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  627. # ###########################################################################################################
  628. # ############################################# Signal handling #############################################
  629. # ###########################################################################################################
  630. # ########################################## Custom signals ################################################
  631. # signal for displaying messages in status bar
  632. self.inform[str].connect(self.info)
  633. self.inform[str, bool].connect(self.info)
  634. # signal for displaying messages in the shell
  635. self.inform_shell.connect(self.info_shell)
  636. # signal to be called when the app is quiting
  637. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  638. self.message.connect(lambda: message_dialog(parent=self.ui))
  639. # self.progress.connect(self.set_progress_bar)
  640. # signals emitted when file state change
  641. self.file_opened.connect(self.register_recent)
  642. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  643. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  644. # ########################################## Standard signals ###############################################
  645. # ### Menu
  646. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  647. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  648. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  649. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  650. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  651. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  652. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  653. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  654. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  655. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  656. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  657. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  658. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  659. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  660. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  661. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  662. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  663. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  664. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  665. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  666. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  667. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  668. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  669. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  670. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  671. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  672. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  673. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  674. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  675. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  676. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  677. self.ui.menufile_exit.triggered.connect(self.final_save)
  678. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  679. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  680. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  681. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  682. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  683. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  684. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  685. self.ui.menueditdelete.triggered.connect(self.on_delete)
  686. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  687. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  688. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  689. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  690. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  691. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  692. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  693. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  694. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  695. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  696. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  697. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  698. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  699. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  700. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  701. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  702. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  703. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  704. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  705. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  706. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  707. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  708. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  709. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  710. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  711. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  712. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  713. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  714. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  715. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  716. self.ui.menuview_replot.triggered.connect(self.plot_all)
  717. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  718. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  719. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  720. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  721. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  722. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  723. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  724. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  725. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  726. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  727. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  728. self.ui.menuhelp_about.triggered.connect(self.on_about)
  729. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  730. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  731. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  732. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  733. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  734. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  735. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  736. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  737. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  738. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  739. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  740. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  741. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  742. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  743. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  744. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  745. # ToolBar signals
  746. self.connect_toolbar_signals(ui=self.ui)
  747. # Context Menu
  748. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  749. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  750. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  751. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  752. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  753. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  754. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  755. self.ui.clearplot.triggered.connect(self.clear_plots)
  756. self.ui.replot.triggered.connect(self.plot_all)
  757. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  758. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  759. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  760. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  761. self.ui.popmenu_move.triggered.connect(self.obj_move)
  762. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  763. # Project Context Menu -> Color Setting
  764. for act in self.ui.menuprojectcolor.actions():
  765. act.triggered.connect(self.on_set_color_action_triggered)
  766. # ###########################################################################################################
  767. # #################################### GUI PREFERENCES SIGNALS ##############################################
  768. # ###########################################################################################################
  769. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  770. lambda: self.on_toggle_units(no_pref=False))
  771. # ##################################### Workspace Setting Signals ###########################################
  772. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  773. self.on_workspace_modified)
  774. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  775. self.on_workspace_modified
  776. )
  777. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  778. # ###########################################################################################################
  779. # ######################################## GUI SETTINGS SIGNALS #############################################
  780. # ###########################################################################################################
  781. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  782. # ######################################## Tools related signals ############################################
  783. # portability changed signal
  784. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  785. # Object list
  786. self.object_status_changed.connect(self.collection.on_collection_updated)
  787. # when there are arguments at application startup this get launched
  788. self.args_at_startup[list].connect(self.on_startup_args)
  789. # ###########################################################################################################
  790. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  791. # ###########################################################################################################
  792. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  793. lambda: self.restore_extensions(ext_type='excellon'))
  794. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  795. lambda: self.restore_extensions(ext_type='gcode'))
  796. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  797. lambda: self.restore_extensions(ext_type='gerber'))
  798. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  799. lambda: self.delete_all_extensions(ext_type='excellon'))
  800. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  801. lambda: self.delete_all_extensions(ext_type='gcode'))
  802. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  803. lambda: self.delete_all_extensions(ext_type='gerber'))
  804. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  805. lambda: self.add_extension(ext_type='excellon'))
  806. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  807. lambda: self.add_extension(ext_type='gcode'))
  808. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  809. lambda: self.add_extension(ext_type='gerber'))
  810. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  811. lambda: self.del_extension(ext_type='excellon'))
  812. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  813. lambda: self.del_extension(ext_type='gcode'))
  814. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  815. lambda: self.del_extension(ext_type='gerber'))
  816. # connect the 'Apply' buttons from the Preferences/File Associations
  817. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  818. lambda: self.on_register_files(obj_type='excellon'))
  819. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  820. lambda: self.on_register_files(obj_type='gcode'))
  821. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  822. lambda: self.on_register_files(obj_type='gerber'))
  823. # ###########################################################################################################
  824. # ########################################### KEYWORDS SIGNALS ##############################################
  825. # ###########################################################################################################
  826. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  827. lambda: self.restore_extensions(ext_type='keyword'))
  828. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  829. lambda: self.delete_all_extensions(ext_type='keyword'))
  830. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  831. lambda: self.add_extension(ext_type='keyword'))
  832. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  833. lambda: self.del_extension(ext_type='keyword'))
  834. # ###########################################################################################################
  835. # ########################################### GUI SIGNALS ###################################################
  836. # ###########################################################################################################
  837. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  838. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  839. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  840. # ###########################################################################################################
  841. # ####################################### VARIOUS SIGNALS ###################################################
  842. # ###########################################################################################################
  843. # connect the abort_all_tasks related slots to the related signals
  844. self.proc_container.idle_flag.connect(self.app_is_idle)
  845. # signal emitted when a tab is closed in the Plot Area
  846. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  847. # signal to close the application
  848. self.close_app_signal.connect(self.kill_app)
  849. # ################################# FINISHED CONNECTING SIGNALS #############################################
  850. # ###########################################################################################################
  851. # ###########################################################################################################
  852. # ###########################################################################################################
  853. self.log.debug("Finished connecting Signals.")
  854. # ###########################################################################################################
  855. # ########################################## Other setups ###################################################
  856. # ###########################################################################################################
  857. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  858. # depending on from where those tools are called different actions can be done
  859. self.call_source = 'app'
  860. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  861. self.tool_tab_locked = False
  862. # decide if to show or hide the Notebook side of the screen at startup
  863. if self.defaults["global_project_at_startup"] is True:
  864. self.ui.splitter.setSizes([1, 1])
  865. else:
  866. self.ui.splitter.setSizes([0, 1])
  867. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  868. self.setup_component_editor()
  869. # ###########################################################################################################
  870. # ####################################### Auto-complete KEYWORDS ############################################
  871. # ###########################################################################################################
  872. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  873. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  874. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  875. 'export_exc',
  876. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  877. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  878. 'interiors', 'isolate', 'join_excellon',
  879. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  880. 'mirror', 'ncc',
  881. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  882. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  883. 'options', 'origin',
  884. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  885. 'save', 'save_project',
  886. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  887. 'skew', 'subtract_poly', 'subtract_rectangle',
  888. 'version', 'write_gcode'
  889. ]
  890. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  891. 'Paste_1',
  892. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  893. 'Toolchange_manual', 'True', 'Users',
  894. 'all', 'auto', 'axis',
  895. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  896. 'contour', 'default',
  897. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  898. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  899. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  900. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  901. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  902. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  903. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  904. 'spacing_columns',
  905. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  906. 'toolchange_xy', 'toolchangez', 'travelz',
  907. 'tooldia', 'use_threads', 'value',
  908. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  909. ]
  910. self.tcl_keywords = [
  911. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  912. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  913. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  914. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  915. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  916. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  917. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  918. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  919. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  920. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  921. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  922. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  923. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  924. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  925. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  926. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  927. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  928. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  929. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  930. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  931. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  932. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  933. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  934. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  935. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  936. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  937. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  938. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  939. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  940. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  941. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  942. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  943. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  944. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  945. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  946. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  947. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  948. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  949. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  950. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  951. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  952. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  953. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  954. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  955. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  956. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  957. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  958. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  959. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  960. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  961. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  962. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  963. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  964. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  965. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  966. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  967. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  968. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  969. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  970. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  971. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  972. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  973. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  974. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  975. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  976. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  977. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  978. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  979. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  980. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  981. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  982. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  983. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  984. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  985. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  986. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  987. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  988. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  989. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  990. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  991. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  992. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  993. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  994. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  995. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  996. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  997. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  998. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  999. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1000. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1001. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1002. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1003. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1004. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1005. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1006. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1007. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1008. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1009. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1010. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1011. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1012. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1013. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1014. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1015. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1016. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1017. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1018. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1019. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1020. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1021. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1022. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1023. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1024. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1025. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1026. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1027. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1028. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1029. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1030. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1031. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1032. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1033. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1034. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1035. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1036. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1037. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1038. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1039. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1040. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1041. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1042. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1043. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1044. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1045. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1046. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1047. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1048. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1049. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1050. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1051. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1052. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1053. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1054. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1055. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1056. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1057. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1058. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1059. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1060. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1061. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1062. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1063. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1064. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1065. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1066. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1067. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1068. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1069. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1070. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1071. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1072. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1073. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1074. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1075. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1076. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1077. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1078. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1079. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1080. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1081. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1082. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1083. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1084. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1085. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1086. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1087. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1088. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1089. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1090. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1091. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1092. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1093. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1094. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1095. ]
  1096. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1097. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1098. # ###########################################################################################################
  1099. # ########################################## Tools and Plugins ##############################################
  1100. # ###########################################################################################################
  1101. self.shell = None
  1102. self.dblsidedtool = None
  1103. self.distance_tool = None
  1104. self.distance_min_tool = None
  1105. self.panelize_tool = None
  1106. self.film_tool = None
  1107. self.paste_tool = None
  1108. self.calculator_tool = None
  1109. self.rules_tool = None
  1110. self.sub_tool = None
  1111. self.move_tool = None
  1112. self.cutout_tool = None
  1113. self.ncclear_tool = None
  1114. self.paint_tool = None
  1115. self.isolation_tool = None
  1116. self.drilling_tool = None
  1117. self.optimal_tool = None
  1118. self.transform_tool = None
  1119. self.properties_tool = None
  1120. self.pdf_tool = None
  1121. self.image_tool = None
  1122. self.pcb_wizard_tool = None
  1123. self.cal_exc_tool = None
  1124. self.qrcode_tool = None
  1125. self.copper_thieving_tool = None
  1126. self.fiducial_tool = None
  1127. self.edrills_tool = None
  1128. self.align_objects_tool = None
  1129. self.punch_tool = None
  1130. self.invert_tool = None
  1131. self.corners_tool = None
  1132. self.etch_tool = None
  1133. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1134. try:
  1135. self.install_tools()
  1136. except AttributeError as e:
  1137. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1138. # ###########################################################################################################
  1139. # ############################################ SETUP RECENT ITEMS ###########################################
  1140. # ###########################################################################################################
  1141. self.setup_recent_items()
  1142. # ###########################################################################################################
  1143. # ######################################### BookMarks Manager ###############################################
  1144. # ###########################################################################################################
  1145. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1146. self.install_bookmarks()
  1147. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1148. # ###########################################################################################################
  1149. # ########################################### Tools Database ################################################
  1150. # ###########################################################################################################
  1151. self.tools_db_tab = None
  1152. # ### System Font Parsing ###
  1153. # self.f_parse = ParseFont(self)
  1154. # self.parse_system_fonts()
  1155. # ###########################################################################################################
  1156. # ############################################## Shell SETUP ################################################
  1157. # ###########################################################################################################
  1158. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1159. if self.defaults["global_shell_at_startup"]:
  1160. self.ui.shell_dock.show()
  1161. else:
  1162. self.ui.shell_dock.hide()
  1163. # ###########################################################################################################
  1164. # ######################################### Check for updates ###############################################
  1165. # ###########################################################################################################
  1166. # Separate thread (Not worker)
  1167. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1168. if (self.beta is False or self.beta is None) and \
  1169. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1170. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1171. # self.thr2 = QtCore.QThread()
  1172. self.worker_task.emit({'fcn': self.version_check,
  1173. 'params': []})
  1174. # self.thr2.start(QtCore.QThread.LowPriority)
  1175. # ###########################################################################################################
  1176. # ##################################### Register files with FlatCAM; #######################################
  1177. # ################################### It works only for Windows for now ####################################
  1178. # ###########################################################################################################
  1179. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1180. self.on_register_files()
  1181. # ###########################################################################################################
  1182. # ######################################## Variables for global usage #######################################
  1183. # ###########################################################################################################
  1184. # hold the App units
  1185. self.units = 'MM'
  1186. # coordinates for relative position display
  1187. self.rel_point1 = (0, 0)
  1188. self.rel_point2 = (0, 0)
  1189. # variable to store coordinates
  1190. self.pos = (0, 0)
  1191. self.pos_canvas = (0, 0)
  1192. self.pos_jump = (0, 0)
  1193. # variable to store mouse coordinates
  1194. self.mouse = [0, 0]
  1195. # variable to store the delta positions on cavnas
  1196. self.dx = 0
  1197. self.dy = 0
  1198. # decide if we have a double click or single click
  1199. self.doubleclick = False
  1200. # store here the is_dragging value
  1201. self.event_is_dragging = False
  1202. # variable to store if a command is active (then the var is not None) and which one it is
  1203. self.command_active = None
  1204. # variable to store the status of moving selection action
  1205. # None value means that it's not an selection action
  1206. # True value = a selection from left to right
  1207. # False value = a selection from right to left
  1208. self.selection_type = None
  1209. # List to store the objects that are currently loaded in FlatCAM
  1210. # This list is updated on each object creation or object delete
  1211. self.all_objects_list = []
  1212. self.objects_under_the_click_list = []
  1213. # List to store the objects that are selected
  1214. self.sel_objects_list = []
  1215. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1216. self.key_modifiers = None
  1217. # Variable to store the status of the code editor
  1218. self.toggle_codeeditor = False
  1219. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1220. self.click_noproject = False
  1221. self.cursor = None
  1222. # Variable to store the GCODE that was edited
  1223. self.gcode_edited = ""
  1224. self.text_editor_tab = None
  1225. # reference for the self.ui.code_editor
  1226. self.reference_code_editor = None
  1227. self.script_code = ''
  1228. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1229. self.tools_db_changed_flag = False
  1230. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1231. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1232. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1233. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1234. 'tsm']
  1235. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1236. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1237. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1238. 'sbp', 'tap', 'xpi']
  1239. self.svg_list = ['svg']
  1240. self.dxf_list = ['dxf']
  1241. self.pdf_list = ['pdf']
  1242. self.prj_list = ['flatprj']
  1243. self.conf_list = ['flatconfig']
  1244. # last used filters
  1245. self.last_op_gerber_filter = None
  1246. self.last_op_excellon_filter = None
  1247. self.last_op_gcode_filter = None
  1248. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1249. # flag for polygons not cleared
  1250. self.poly_not_cleared = False
  1251. # VisPy visuals
  1252. self.isHovering = False
  1253. self.notHovering = True
  1254. # Window geometry
  1255. self.x_pos = None
  1256. self.y_pos = None
  1257. self.width = None
  1258. self.height = None
  1259. # when True, the app has to return from any thread
  1260. self.abort_flag = False
  1261. # set the value used in the Windows Title
  1262. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1263. # this holds a widget that is installed in the Plot Area when View Source option is used
  1264. self.source_editor_tab = None
  1265. self.pagesize = {}
  1266. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1267. # VisPy visuals
  1268. if self.is_legacy is False:
  1269. try:
  1270. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1271. except AttributeError:
  1272. self.tool_shapes = None
  1273. else:
  1274. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1275. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1276. # used in the delayed shutdown self.start_delayed_quit() method
  1277. self.save_timer = None
  1278. # ###########################################################################################################
  1279. # ################################## ADDING FlatCAM EDITORS section #########################################
  1280. # ###########################################################################################################
  1281. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1282. # at the first launch of the App , the editors will not be functional.
  1283. try:
  1284. self.geo_editor = AppGeoEditor(self)
  1285. except Exception as es:
  1286. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1287. try:
  1288. self.exc_editor = AppExcEditor(self)
  1289. except Exception as es:
  1290. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1291. try:
  1292. self.grb_editor = AppGerberEditor(self)
  1293. except Exception as es:
  1294. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1295. try:
  1296. self.gcode_editor = AppGCodeEditor(self)
  1297. except Exception as es:
  1298. log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1299. self.log.debug("Finished adding FlatCAM Editor's.")
  1300. self.set_ui_title(name=_("New Project - Not saved"))
  1301. current_platform = platform.architecture()[0]
  1302. if current_platform != '64bit':
  1303. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1304. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1305. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1306. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1307. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1308. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1309. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1310. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1311. # ###########################################################################################################
  1312. # ########################################### EXCLUSION AREAS ###############################################
  1313. # ###########################################################################################################
  1314. self.exc_areas = ExclusionAreas(app=self)
  1315. # ###########################################################################################################
  1316. # ##################################### Finished the CONSTRUCTOR ############################################
  1317. # ###########################################################################################################
  1318. App.log.debug("END of constructor. Releasing control.")
  1319. # ###########################################################################################################
  1320. # ########################################## SHOW GUI #######################################################
  1321. # ###########################################################################################################
  1322. # if the app is not started as headless, show it
  1323. if self.cmd_line_headless != 1:
  1324. if show_splash:
  1325. # finish the splash
  1326. self.splash.finish(self.ui)
  1327. mgui_settings = QSettings("Open Source", "FlatCAM")
  1328. if mgui_settings.contains("maximized_gui"):
  1329. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1330. if maximized_ui is True:
  1331. self.ui.showMaximized()
  1332. else:
  1333. self.ui.show()
  1334. else:
  1335. self.ui.show()
  1336. if self.defaults["global_systray_icon"]:
  1337. self.trayIcon.show()
  1338. else:
  1339. log.warning("******************* RUNNING HEADLESS *******************")
  1340. # ###########################################################################################################
  1341. # ######################################## START-UP ARGUMENTS ###############################################
  1342. # ###########################################################################################################
  1343. # test if the program was started with a script as parameter
  1344. if self.cmd_line_shellvar:
  1345. try:
  1346. cnt = 0
  1347. command_tcl = 0
  1348. for i in self.cmd_line_shellvar.split(','):
  1349. if i is not None:
  1350. # noinspection PyBroadException
  1351. try:
  1352. command_tcl = eval(i)
  1353. except Exception:
  1354. command_tcl = i
  1355. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1356. cnt += 1
  1357. # if there are Windows paths then replace the path separator with a Unix like one
  1358. if sys.platform == 'win32':
  1359. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1360. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1361. except Exception as ext:
  1362. print("ERROR: ", ext)
  1363. sys.exit(2)
  1364. if self.cmd_line_shellfile:
  1365. if self.cmd_line_headless != 1:
  1366. if self.ui.shell_dock.isHidden():
  1367. self.ui.shell_dock.show()
  1368. try:
  1369. with open(self.cmd_line_shellfile, "r") as myfile:
  1370. # if show_splash:
  1371. # self.splash.showMessage('%s: %ssec\n%s' % (
  1372. # _("Canvas initialization started.\n"
  1373. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1374. # _("Executing Tcl Script ...")),
  1375. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1376. # color=QtGui.QColor("gray"))
  1377. cmd_line_shellfile_text = myfile.read()
  1378. if self.cmd_line_headless != 1:
  1379. self.shell.exec_command(cmd_line_shellfile_text)
  1380. else:
  1381. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1382. except Exception as ext:
  1383. print("ERROR: ", ext)
  1384. sys.exit(2)
  1385. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1386. # the path/file_name must be enclosed in quotes if it contain spaces
  1387. if App.args:
  1388. self.args_at_startup.emit(App.args)
  1389. if self.defaults.old_defaults_found is True:
  1390. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1391. "Please reboot the application to update."))
  1392. self.defaults.old_defaults_found = False
  1393. # ######################################### INIT FINISHED #######################################################
  1394. # #################################################################################################################
  1395. # #################################################################################################################
  1396. # #################################################################################################################
  1397. # #################################################################################################################
  1398. # #################################################################################################################
  1399. @staticmethod
  1400. def copy_and_overwrite(from_path, to_path):
  1401. """
  1402. From here:
  1403. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1404. :param from_path: source path
  1405. :param to_path: destination path
  1406. :return: None
  1407. """
  1408. if os.path.exists(to_path):
  1409. shutil.rmtree(to_path)
  1410. try:
  1411. shutil.copytree(from_path, to_path)
  1412. except FileNotFoundError:
  1413. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1414. shutil.copytree(from_new_path, to_path)
  1415. def on_startup_args(self, args, silent=False):
  1416. """
  1417. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1418. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1419. :param args: a list containing the application args at startup
  1420. :return: None
  1421. """
  1422. if args is not None:
  1423. args_to_process = args
  1424. else:
  1425. args_to_process = App.args
  1426. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1427. for argument in args_to_process:
  1428. if '.FlatPrj'.lower() in argument.lower():
  1429. try:
  1430. project_name = str(argument)
  1431. if project_name == "":
  1432. if silent is False:
  1433. self.inform.emit(_("Cancelled."))
  1434. else:
  1435. # self.open_project(project_name)
  1436. run_from_arg = True
  1437. # self.worker_task.emit({'fcn': self.open_project,
  1438. # 'params': [project_name, run_from_arg]})
  1439. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1440. except Exception as e:
  1441. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1442. elif '.FlatConfig'.lower() in argument.lower():
  1443. try:
  1444. file_name = str(argument)
  1445. if file_name == "":
  1446. if silent is False:
  1447. self.inform.emit(_("Open Config file failed."))
  1448. else:
  1449. run_from_arg = True
  1450. # self.worker_task.emit({'fcn': self.open_config_file,
  1451. # 'params': [file_name, run_from_arg]})
  1452. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1453. except Exception as e:
  1454. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1455. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1456. try:
  1457. file_name = str(argument)
  1458. if file_name == "":
  1459. if silent is False:
  1460. self.inform.emit(_("Open Script file failed."))
  1461. else:
  1462. if silent is False:
  1463. self.on_fileopenscript(name=file_name)
  1464. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1465. self.on_filerunscript(name=file_name)
  1466. except Exception as e:
  1467. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1468. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1469. log.debug("App.on_startup_args() --> Quit event.")
  1470. sys.exit()
  1471. elif 'save'.lower() in argument.lower():
  1472. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1473. self.preferencesUiManager.save_defaults()
  1474. else:
  1475. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1476. proc_arg = argument.lower()
  1477. for ext in exc_list:
  1478. proc_ext = ext.replace(' ', '')
  1479. proc_ext = '.%s' % proc_ext
  1480. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1481. file_name = str(argument)
  1482. if file_name == "":
  1483. if silent is False:
  1484. self.inform.emit(_("Open Excellon file failed."))
  1485. else:
  1486. self.on_fileopenexcellon(name=file_name, signal=None)
  1487. return
  1488. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1489. for ext in gco_list:
  1490. proc_ext = ext.replace(' ', '')
  1491. proc_ext = '.%s' % proc_ext
  1492. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1493. file_name = str(argument)
  1494. if file_name == "":
  1495. if silent is False:
  1496. self.inform.emit(_("Open GCode file failed."))
  1497. else:
  1498. self.on_fileopengcode(name=file_name, signal=None)
  1499. return
  1500. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1501. for ext in grb_list:
  1502. proc_ext = ext.replace(' ', '')
  1503. proc_ext = '.%s' % proc_ext
  1504. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1505. file_name = str(argument)
  1506. if file_name == "":
  1507. if silent is False:
  1508. self.inform.emit(_("Open Gerber file failed."))
  1509. else:
  1510. self.on_fileopengerber(name=file_name, signal=None)
  1511. return
  1512. # if it reached here without already returning then the app was registered with a file that it does not
  1513. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1514. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1515. # for arg in args_to_process:
  1516. # if 'FlatCAM.exe' in arg:
  1517. # continue
  1518. # else:
  1519. # sys.exit(2)
  1520. def set_ui_title(self, name):
  1521. """
  1522. Sets the title of the main window.
  1523. :param name: String that store the project path and project name
  1524. :return: None
  1525. """
  1526. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1527. (self.version,
  1528. ('BETA' if self.beta else ''),
  1529. platform.architecture()[0],
  1530. self.engine,
  1531. name)
  1532. )
  1533. def on_app_restart(self):
  1534. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1535. # be left in the SySTray
  1536. try:
  1537. self.trayIcon.hide()
  1538. except Exception:
  1539. pass
  1540. fcTranslate.restart_program(app=self)
  1541. def clear_pool(self):
  1542. """
  1543. Clear the multiprocessing pool and calls garbage collector.
  1544. :return: None
  1545. """
  1546. self.pool.close()
  1547. self.pool = Pool()
  1548. self.pool_recreated.emit(self.pool)
  1549. gc.collect()
  1550. def install_tools(self):
  1551. """
  1552. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1553. Instantiation of the Tools classes.
  1554. The order that the tools are installed is important as they can depend on each other install position.
  1555. :return: None
  1556. """
  1557. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1558. self.shell = FCShell(app=self, version=self.version)
  1559. self.distance_tool = Distance(self)
  1560. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1561. before=self.ui.menueditorigin,
  1562. separator=False)
  1563. self.distance_min_tool = DistanceMin(self)
  1564. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1565. pos=self.ui.menuedit,
  1566. before=self.ui.menueditorigin,
  1567. separator=True)
  1568. self.dblsidedtool = DblSidedTool(self)
  1569. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1570. self.cal_exc_tool = ToolCalibration(self)
  1571. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1572. before=self.dblsidedtool.menuAction,
  1573. separator=False)
  1574. self.align_objects_tool = AlignObjects(self)
  1575. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1576. self.edrills_tool = ToolExtractDrills(self)
  1577. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1578. self.panelize_tool = Panelize(self)
  1579. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1580. self.film_tool = Film(self)
  1581. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1582. self.paste_tool = SolderPaste(self)
  1583. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1584. self.calculator_tool = ToolCalculator(self)
  1585. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1586. self.sub_tool = ToolSub(self)
  1587. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1588. pos=self.ui.menutool, separator=True)
  1589. self.rules_tool = RulesCheck(self)
  1590. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1591. pos=self.ui.menutool, separator=False)
  1592. self.optimal_tool = ToolOptimal(self)
  1593. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1594. pos=self.ui.menutool, separator=True)
  1595. self.move_tool = ToolMove(self)
  1596. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1597. before=self.ui.menueditorigin, separator=True)
  1598. self.cutout_tool = CutOut(self)
  1599. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1600. before=self.sub_tool.menuAction)
  1601. self.ncclear_tool = NonCopperClear(self)
  1602. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1603. before=self.sub_tool.menuAction, separator=True)
  1604. self.paint_tool = ToolPaint(self)
  1605. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1606. before=self.sub_tool.menuAction, separator=True)
  1607. self.isolation_tool = ToolIsolation(self)
  1608. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1609. before=self.sub_tool.menuAction, separator=True)
  1610. self.drilling_tool = ToolDrilling(self)
  1611. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1612. before=self.sub_tool.menuAction, separator=True)
  1613. self.copper_thieving_tool = ToolCopperThieving(self)
  1614. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1615. pos=self.ui.menutool)
  1616. self.fiducial_tool = ToolFiducials(self)
  1617. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1618. pos=self.ui.menutool)
  1619. self.qrcode_tool = QRCode(self)
  1620. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1621. pos=self.ui.menutool)
  1622. self.punch_tool = ToolPunchGerber(self)
  1623. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1624. self.invert_tool = ToolInvertGerber(self)
  1625. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1626. self.corners_tool = ToolCorners(self)
  1627. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1628. self.etch_tool = ToolEtchCompensation(self)
  1629. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1630. self.transform_tool = ToolTransform(self)
  1631. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1632. pos=self.ui.menuoptions, separator=True)
  1633. self.properties_tool = Properties(self)
  1634. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1635. pos=self.ui.menuoptions)
  1636. self.pdf_tool = ToolPDF(self)
  1637. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1638. pos=self.ui.menufileimport,
  1639. separator=True)
  1640. self.image_tool = ToolImage(self)
  1641. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1642. pos=self.ui.menufileimport,
  1643. separator=True)
  1644. self.pcb_wizard_tool = PcbWizard(self)
  1645. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1646. pos=self.ui.menufileimport)
  1647. self.log.debug("Tools are installed.")
  1648. def remove_tools(self):
  1649. """
  1650. Will remove all the actions in the Tool menu.
  1651. :return: None
  1652. """
  1653. for act in self.ui.menutool.actions():
  1654. self.ui.menutool.removeAction(act)
  1655. def init_tools(self):
  1656. """
  1657. Initialize the Tool tab in the notebook side of the central widget.
  1658. Remove the actions in the Tools menu.
  1659. Instantiate again the FlatCAM tools (plugins).
  1660. All this is required when changing the layout: standard, compact etc.
  1661. :return: None
  1662. """
  1663. log.debug("init_tools()")
  1664. # delete the data currently in the Tools Tab and the Tab itself
  1665. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1666. if widget is not None:
  1667. widget.deleteLater()
  1668. self.ui.notebook.removeTab(2)
  1669. # rebuild the Tools Tab
  1670. self.ui.tool_tab = QtWidgets.QWidget()
  1671. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1672. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1673. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1674. self.ui.tool_scroll_area = VerticalScrollArea()
  1675. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1676. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1677. # first remove all of them
  1678. self.remove_tools()
  1679. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1680. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1681. '&Command Line\tS')
  1682. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1683. # third install all of them
  1684. try:
  1685. self.install_tools()
  1686. except AttributeError:
  1687. pass
  1688. self.log.debug("Tools are initialized.")
  1689. # def parse_system_fonts(self):
  1690. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1691. # 'params': []})
  1692. def connect_tools_signals_to_toolbar(self, ui):
  1693. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1694. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1695. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1696. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1697. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1698. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1699. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1700. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1701. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1702. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1703. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1704. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1705. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1706. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1707. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1708. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1709. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1710. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1711. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1712. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1713. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1714. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1715. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1716. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1717. def connect_toolbar_signals(self, ui):
  1718. """
  1719. Reconnect the signals to the actions in the toolbar.
  1720. This has to be done each time after the FlatCAM tools are removed/installed.
  1721. :return: None
  1722. """
  1723. # Toolbar
  1724. # File Toolbar Signals
  1725. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1726. ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1727. ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1728. ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1729. ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1730. # View Toolbar Signals
  1731. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1732. ui.replot_btn.triggered.connect(self.plot_all)
  1733. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1734. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1735. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1736. # Edit Toolbar Signals
  1737. ui.editgeo_btn.triggered.connect(self.object2editor)
  1738. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1739. ui.copy_btn.triggered.connect(self.on_copy_command)
  1740. ui.delete_btn.triggered.connect(self.on_delete)
  1741. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1742. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1743. ui.origin_btn.triggered.connect(self.on_set_origin)
  1744. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1745. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1746. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1747. # Scripting Toolbar Signals
  1748. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1749. ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1750. ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1751. ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1752. # Tools Toolbar Signals
  1753. try:
  1754. self.connect_tools_signals_to_toolbar(ui=ui)
  1755. except Exception as err:
  1756. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1757. def object2editor(self):
  1758. """
  1759. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1760. :return: None
  1761. """
  1762. self.defaults.report_usage("object2editor()")
  1763. # disable the objects menu as it may interfere with the appEditors
  1764. self.ui.menuobjects.setDisabled(True)
  1765. edited_object = self.collection.get_active()
  1766. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1767. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1768. pass
  1769. else:
  1770. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1771. return
  1772. if isinstance(edited_object, GeometryObject):
  1773. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1774. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1775. # we set the notebook to hidden
  1776. # self.ui.splitter.setSizes([0, 1])
  1777. if edited_object.multigeo is True:
  1778. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1779. if len(sel_rows) > 1:
  1780. self.inform.emit('[WARNING_NOTCL] %s' %
  1781. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1782. "is not possible.\n"
  1783. "Edit only one geometry at a time."))
  1784. if not sel_rows:
  1785. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1786. return
  1787. # determine the tool dia of the selected tool
  1788. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1789. # now find the key in the edited_object.tools that has this tooldia
  1790. multi_tool = 1
  1791. for tool in edited_object.tools:
  1792. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1793. multi_tool = tool
  1794. break
  1795. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1796. else:
  1797. self.geo_editor.edit_fcgeometry(edited_object)
  1798. # set call source to the Editor we go into
  1799. self.call_source = 'geo_editor'
  1800. elif isinstance(edited_object, ExcellonObject):
  1801. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1802. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1803. if self.ui.splitter.sizes()[0] == 0:
  1804. self.ui.splitter.setSizes([1, 1])
  1805. self.exc_editor.edit_fcexcellon(edited_object)
  1806. # set call source to the Editor we go into
  1807. self.call_source = 'exc_editor'
  1808. elif isinstance(edited_object, GerberObject):
  1809. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1810. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1811. if self.ui.splitter.sizes()[0] == 0:
  1812. self.ui.splitter.setSizes([1, 1])
  1813. self.grb_editor.edit_fcgerber(edited_object)
  1814. # set call source to the Editor we go into
  1815. self.call_source = 'grb_editor'
  1816. # reset the following variables so the UI is built again after edit
  1817. edited_object.ui_build = False
  1818. elif isinstance(edited_object, CNCJobObject):
  1819. if self.ui.splitter.sizes()[0] == 0:
  1820. self.ui.splitter.setSizes([1, 1])
  1821. # set call source to the Editor we go into
  1822. self.call_source = 'gcode_editor'
  1823. self.gcode_editor.edit_fcgcode(edited_object)
  1824. return
  1825. # make sure that we can't select another object while in Editor Mode:
  1826. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1827. self.ui.project_frame.setDisabled(True)
  1828. # delete any selection shape that might be active as they are not relevant in Editor
  1829. self.delete_selection_shape()
  1830. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1831. self.ui.plot_tab_area.protectTab(0)
  1832. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1833. self.should_we_save = True
  1834. def editor2object(self, cleanup=None):
  1835. """
  1836. Transfers the Geometry or Excellon from it's editor to the current object.
  1837. :return: None
  1838. """
  1839. self.defaults.report_usage("editor2object()")
  1840. # re-enable the objects menu that was disabled on entry in Editor mode
  1841. self.ui.menuobjects.setDisabled(False)
  1842. # do not update a geometry or excellon object unless it comes out of an editor
  1843. if self.call_source != 'app':
  1844. edited_obj = self.collection.get_active()
  1845. if cleanup is None:
  1846. msgbox = QtWidgets.QMessageBox()
  1847. msgbox.setText(_("Do you want to save the edited object?"))
  1848. msgbox.setWindowTitle(_("Close Editor"))
  1849. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1850. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1851. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1852. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1853. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1854. msgbox.setDefaultButton(bt_yes)
  1855. msgbox.exec_()
  1856. response = msgbox.clickedButton()
  1857. if response == bt_yes:
  1858. # clean the Tools Tab
  1859. self.ui.tool_scroll_area.takeWidget()
  1860. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1861. self.ui.notebook.setTabText(2, "Tool")
  1862. if isinstance(edited_obj, GeometryObject):
  1863. obj_type = "Geometry"
  1864. self.geo_editor.update_fcgeometry(edited_obj)
  1865. # self.geo_editor.update_options(edited_obj)
  1866. # restore GUI to the Selected TAB
  1867. # Remove anything else in the appGUI
  1868. self.ui.tool_scroll_area.takeWidget()
  1869. # update the geo object options so it is including the bounding box values
  1870. try:
  1871. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1872. edited_obj.options['xmin'] = xmin
  1873. edited_obj.options['ymin'] = ymin
  1874. edited_obj.options['xmax'] = xmax
  1875. edited_obj.options['ymax'] = ymax
  1876. except AttributeError as e:
  1877. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1878. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1879. edited_obj.build_ui()
  1880. edited_obj.plot()
  1881. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1882. elif isinstance(edited_obj, GerberObject):
  1883. obj_type = "Gerber"
  1884. self.grb_editor.update_fcgerber()
  1885. # self.grb_editor.update_options(edited_obj)
  1886. # delete the old object (the source object) if it was an empty one
  1887. try:
  1888. if len(edited_obj.solid_geometry) == 0:
  1889. old_name = edited_obj.options['name']
  1890. self.collection.delete_by_name(old_name)
  1891. except TypeError:
  1892. # if the solid_geometry is a single Polygon the len() will not work
  1893. # in any case, falling here means that we have something in the solid_geometry, even if only
  1894. # a single Polygon, therefore we pass this
  1895. pass
  1896. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1897. # restore GUI to the Selected TAB
  1898. # Remove anything else in the GUI
  1899. self.ui.selected_scroll_area.takeWidget()
  1900. elif isinstance(edited_obj, ExcellonObject):
  1901. obj_type = "Excellon"
  1902. self.exc_editor.update_fcexcellon(edited_obj)
  1903. # self.exc_editor.update_options(edited_obj)
  1904. # restore GUI to the Selected TAB
  1905. # Remove anything else in the GUI
  1906. self.ui.tool_scroll_area.takeWidget()
  1907. # delete the old object (the source object) if it was an empty one
  1908. # find if we have drills:
  1909. has_drills = None
  1910. for tt in edited_obj.tools:
  1911. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1912. has_drills = True
  1913. break
  1914. # find if we have slots:
  1915. has_slots = None
  1916. for tt in edited_obj.tools:
  1917. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1918. has_slots = True
  1919. break
  1920. if has_drills is None and has_slots is None:
  1921. old_name = edited_obj.options['name']
  1922. self.collection.delete_by_name(name=old_name)
  1923. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1924. else:
  1925. self.inform.emit('[WARNING_NOTCL] %s' %
  1926. _("Select a Gerber, Geometry or Excellon Object to update."))
  1927. return
  1928. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1929. elif response == bt_no:
  1930. # clean the Tools Tab
  1931. self.ui.tool_scroll_area.takeWidget()
  1932. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1933. self.ui.notebook.setTabText(2, "Tool")
  1934. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1935. if isinstance(edited_obj, GeometryObject):
  1936. self.geo_editor.deactivate()
  1937. edited_obj.build_ui()
  1938. edited_obj.plot()
  1939. elif isinstance(edited_obj, GerberObject):
  1940. self.grb_editor.deactivate_grb_editor()
  1941. edited_obj.build_ui()
  1942. elif isinstance(edited_obj, ExcellonObject):
  1943. self.exc_editor.deactivate()
  1944. edited_obj.build_ui()
  1945. else:
  1946. self.inform.emit('[WARNING_NOTCL] %s' %
  1947. _("Select a Gerber, Geometry or Excellon Object to update."))
  1948. return
  1949. elif response == bt_cancel:
  1950. return
  1951. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1952. # edited_obj.build_ui()
  1953. # Switch notebook to Selected page
  1954. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1955. else:
  1956. if isinstance(edited_obj, GeometryObject):
  1957. self.geo_editor.deactivate()
  1958. elif isinstance(edited_obj, GerberObject):
  1959. self.grb_editor.deactivate_grb_editor()
  1960. elif isinstance(edited_obj, ExcellonObject):
  1961. self.exc_editor.deactivate()
  1962. else:
  1963. self.inform.emit('[WARNING_NOTCL] %s' %
  1964. _("Select a Gerber, Geometry or Excellon Object to update."))
  1965. return
  1966. # if notebook is hidden we show it
  1967. if self.ui.splitter.sizes()[0] == 0:
  1968. self.ui.splitter.setSizes([1, 1])
  1969. # restore the call_source to app
  1970. self.call_source = 'app'
  1971. # edited_obj.plot()
  1972. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1973. self.ui.plot_tab_area.protectTab(0)
  1974. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1975. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1976. self.ui.project_frame.setDisabled(False)
  1977. def get_last_folder(self):
  1978. """
  1979. Get the folder path from where the last file was opened.
  1980. :return: String, last opened folder path
  1981. """
  1982. return self.defaults["global_last_folder"]
  1983. def get_last_save_folder(self):
  1984. """
  1985. Get the folder path from where the last file was saved.
  1986. :return: String, last saved folder path
  1987. """
  1988. loc = self.defaults["global_last_save_folder"]
  1989. if loc is None:
  1990. loc = self.defaults["global_last_folder"]
  1991. if loc is None:
  1992. loc = os.path.dirname(__file__)
  1993. return loc
  1994. @QtCore.pyqtSlot(str)
  1995. @QtCore.pyqtSlot(str, bool)
  1996. def info(self, msg, shell_echo=True):
  1997. """
  1998. Informs the user. Normally on the status bar, optionally
  1999. also on the shell.
  2000. :param msg: Text to write.
  2001. :type msg: str
  2002. :param shell_echo: Control if to display the message msg in the Shell
  2003. :type shell_echo: bool
  2004. :return: None
  2005. """
  2006. # Type of message in brackets at the beginning of the message.
  2007. match = re.search(r"\[(.*)\](.*)", msg)
  2008. if match:
  2009. level = match.group(1)
  2010. msg_ = match.group(2)
  2011. self.ui.fcinfo.set_status(str(msg_), level=level)
  2012. if shell_echo is True:
  2013. if level.lower() == "error":
  2014. self.shell_message(msg, error=True, show=True)
  2015. elif level.lower() == "warning":
  2016. self.shell_message(msg, warning=True, show=True)
  2017. elif level.lower() == "error_notcl":
  2018. self.shell_message(msg, error=True, show=False)
  2019. elif level.lower() == "warning_notcl":
  2020. self.shell_message(msg, warning=True, show=False)
  2021. elif level.lower() == "success":
  2022. self.shell_message(msg, success=True, show=False)
  2023. elif level.lower() == "selected":
  2024. self.shell_message(msg, selected=True, show=False)
  2025. else:
  2026. self.shell_message(msg, show=False)
  2027. else:
  2028. self.ui.fcinfo.set_status(str(msg), level="info")
  2029. # make sure that if the message is to clear the infobar with a space
  2030. # is not printed over and over on the shell
  2031. if msg != '' and shell_echo is True:
  2032. self.shell_message(msg)
  2033. def info_shell(self, msg):
  2034. self.shell_message(msg=msg)
  2035. def on_import_preferences(self):
  2036. """
  2037. Loads the application default settings from a saved file into
  2038. ``self.defaults`` dictionary.
  2039. :return: None
  2040. """
  2041. self.defaults.report_usage("on_import_preferences")
  2042. App.log.debug("App.on_import_preferences()")
  2043. # Show file chooser
  2044. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2045. try:
  2046. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2047. directory=self.data_path,
  2048. filter=filter_)
  2049. except TypeError:
  2050. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2051. filter=filter_)
  2052. filename = str(filename)
  2053. if filename == "":
  2054. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2055. return
  2056. # Load in the defaults from the chosen file
  2057. self.defaults.load(filename=filename)
  2058. self.preferencesUiManager.on_preferences_edited()
  2059. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2060. def on_export_preferences(self):
  2061. """
  2062. Save the defaults dictionary to a file.
  2063. :return: None
  2064. """
  2065. self.defaults.report_usage("on_export_preferences")
  2066. App.log.debug("on_export_preferences()")
  2067. # defaults_file_content = None
  2068. # Show file chooser
  2069. date = str(datetime.today()).rpartition('.')[0]
  2070. date = ''.join(c for c in date if c not in ':-')
  2071. date = date.replace(' ', '_')
  2072. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2073. try:
  2074. filename, _f = FCFileSaveDialog.get_saved_filename(
  2075. caption=_("Export FlatCAM Preferences"),
  2076. directory=self.data_path + '/preferences_' + date,
  2077. ext_filter=filter__
  2078. )
  2079. except TypeError:
  2080. filename, _f = FCFileSaveDialog.get_saved_filename(
  2081. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2082. filename = str(filename)
  2083. if filename == "":
  2084. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2085. return
  2086. # Update options
  2087. self.preferencesUiManager.defaults_read_form()
  2088. self.defaults.propagate_defaults()
  2089. # Save update options
  2090. try:
  2091. self.defaults.write(filename=filename)
  2092. except Exception:
  2093. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2094. return
  2095. if self.defaults["global_open_style"] is False:
  2096. self.file_opened.emit("preferences", filename)
  2097. self.file_saved.emit("preferences", filename)
  2098. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2099. def save_to_file(self, content_to_save, txt_content):
  2100. """
  2101. Save something to a file.
  2102. :return: None
  2103. """
  2104. self.defaults.report_usage("save_to_file")
  2105. App.log.debug("save_to_file()")
  2106. self.date = str(datetime.today()).rpartition('.')[0]
  2107. self.date = ''.join(c for c in self.date if c not in ':-')
  2108. self.date = self.date.replace(' ', '_')
  2109. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2110. path_to_save = self.defaults["global_last_save_folder"] if \
  2111. self.defaults["global_last_save_folder"] is not None else self.data_path
  2112. try:
  2113. filename, _f = FCFileSaveDialog.get_saved_filename(
  2114. caption=_("Save to file"),
  2115. directory=path_to_save + '/file_' + self.date,
  2116. ext_filter=filter__
  2117. )
  2118. except TypeError:
  2119. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2120. filename = str(filename)
  2121. if filename == "":
  2122. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2123. return
  2124. else:
  2125. try:
  2126. with open(filename, 'w') as f:
  2127. ___ = f.read()
  2128. except PermissionError:
  2129. self.inform.emit('[WARNING] %s' %
  2130. _("Permission denied, saving not possible.\n"
  2131. "Most likely another app is holding the file open and not accessible."))
  2132. return
  2133. except IOError:
  2134. App.log.debug('Creating a new file ...')
  2135. f = open(filename, 'w')
  2136. f.close()
  2137. except Exception:
  2138. e = sys.exc_info()[0]
  2139. App.log.error("Could not load the file.")
  2140. App.log.error(str(e))
  2141. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2142. return
  2143. # Save content
  2144. if filename.rpartition('.')[2].lower() == 'html':
  2145. file_content = content_to_save
  2146. else:
  2147. file_content = txt_content
  2148. try:
  2149. with open(filename, "w") as f:
  2150. f.write(file_content)
  2151. except Exception:
  2152. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2153. return
  2154. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2155. def register_recent(self, kind, filename):
  2156. """
  2157. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2158. dictionary.
  2159. :param kind: type of file that was opened
  2160. :param filename: the path and file name for the file that was opened
  2161. :return:
  2162. """
  2163. self.log.debug("register_recent()")
  2164. self.log.debug(" %s" % kind)
  2165. self.log.debug(" %s" % filename)
  2166. record = {'kind': str(kind), 'filename': str(filename)}
  2167. if record in self.recent:
  2168. return
  2169. if record in self.recent_projects:
  2170. return
  2171. if record['kind'] == 'project':
  2172. self.recent_projects.insert(0, record)
  2173. else:
  2174. self.recent.insert(0, record)
  2175. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2176. self.recent.pop()
  2177. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2178. self.recent_projects.pop()
  2179. try:
  2180. f = open(self.data_path + '/recent.json', 'w')
  2181. except IOError:
  2182. App.log.error("Failed to open recent items file for writing.")
  2183. self.inform.emit('[ERROR_NOTCL] %s' %
  2184. _('Failed to open recent files file for writing.'))
  2185. return
  2186. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2187. f.close()
  2188. try:
  2189. fp = open(self.data_path + '/recent_projects.json', 'w')
  2190. except IOError:
  2191. App.log.error("Failed to open recent items file for writing.")
  2192. self.inform.emit('[ERROR_NOTCL] %s' %
  2193. _('Failed to open recent projects file for writing.'))
  2194. return
  2195. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2196. fp.close()
  2197. # Re-build the recent items menu
  2198. self.setup_recent_items()
  2199. def on_about(self):
  2200. """
  2201. Displays the "about" dialog found in the Menu --> Help.
  2202. :return: None
  2203. """
  2204. self.defaults.report_usage("on_about")
  2205. version = self.version
  2206. version_date = self.version_date
  2207. beta = self.beta
  2208. class AboutDialog(QtWidgets.QDialog):
  2209. def __init__(self, app, parent=None):
  2210. QtWidgets.QDialog.__init__(self, parent)
  2211. self.app = app
  2212. # Icon and title
  2213. self.setWindowIcon(parent.app_icon)
  2214. self.setWindowTitle(_("About FlatCAM"))
  2215. self.resize(600, 200)
  2216. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2217. # self.setStyleSheet(
  2218. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2219. # "background-attachment: fixed"
  2220. # )
  2221. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2222. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2223. # palette = QtGui.QPalette()
  2224. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2225. # self.setPalette(palette)
  2226. logo = QtWidgets.QLabel()
  2227. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2228. title = QtWidgets.QLabel(
  2229. "<font size=8><B>FlatCAM</B></font><BR>"
  2230. "{title}<BR>"
  2231. "<BR>"
  2232. "<BR>"
  2233. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2234. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2235. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2236. "<B>{issue}</B></a><BR>".format(
  2237. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2238. devel=_("Development"),
  2239. down=_("DOWNLOAD"),
  2240. issue=_("Issue tracker"))
  2241. )
  2242. title.setOpenExternalLinks(True)
  2243. closebtn = QtWidgets.QPushButton(_("Close"))
  2244. tab_widget = QtWidgets.QTabWidget()
  2245. description_label = QtWidgets.QLabel(
  2246. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2247. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2248. version=version,
  2249. beta=('BETA' if beta else ''),
  2250. date=version_date,
  2251. arch=platform.architecture()[0])
  2252. )
  2253. description_label.setOpenExternalLinks(True)
  2254. lic_lbl_header = QtWidgets.QLabel(
  2255. '%s:<br>%s<br>' % (
  2256. _('Licensed under the MIT license'),
  2257. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2258. "http://www.opensource.org/licenses/mit-license.php</a>"
  2259. )
  2260. )
  2261. lic_lbl_header.setOpenExternalLinks(True)
  2262. lic_lbl_body = QtWidgets.QLabel(
  2263. _(
  2264. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2265. 'of this software and associated documentation files (the "Software"), to deal\n'
  2266. 'in the Software without restriction, including without limitation the rights\n'
  2267. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2268. 'copies of the Software, and to permit persons to whom the Software is\n'
  2269. 'furnished to do so, subject to the following conditions:\n\n'
  2270. 'The above copyright notice and this permission notice shall be included in\n'
  2271. 'all copies or substantial portions of the Software.\n\n'
  2272. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2273. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2274. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2275. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2276. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2277. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2278. 'THE SOFTWARE.'
  2279. )
  2280. )
  2281. attributions_label = QtWidgets.QLabel(
  2282. _(
  2283. 'Some of the icons used are from the following sources:<br>'
  2284. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2285. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2286. 'title="Flaticon">www.flaticon.com</a></div>'
  2287. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2288. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2289. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2290. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2291. 'title="Flaticon">www.flaticon.com</a></div>'
  2292. )
  2293. )
  2294. attributions_label.setOpenExternalLinks(True)
  2295. # layouts
  2296. layout1 = QtWidgets.QVBoxLayout()
  2297. layout1_1 = QtWidgets.QHBoxLayout()
  2298. layout1_2 = QtWidgets.QHBoxLayout()
  2299. layout2 = QtWidgets.QHBoxLayout()
  2300. layout3 = QtWidgets.QHBoxLayout()
  2301. self.setLayout(layout1)
  2302. layout1.addLayout(layout1_1)
  2303. layout1.addLayout(layout1_2)
  2304. layout1.addLayout(layout2)
  2305. layout1.addLayout(layout3)
  2306. layout1_1.addStretch()
  2307. layout1_1.addWidget(description_label)
  2308. layout1_2.addWidget(tab_widget)
  2309. self.splash_tab = QtWidgets.QWidget()
  2310. self.splash_tab.setObjectName("splash_about")
  2311. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2312. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2313. tab_widget.addTab(self.splash_tab, _("Splash"))
  2314. self.programmmers_tab = QtWidgets.QWidget()
  2315. self.programmmers_tab.setObjectName("programmers_about")
  2316. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2317. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2318. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2319. self.translators_tab = QtWidgets.QWidget()
  2320. self.translators_tab.setObjectName("translators_about")
  2321. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2322. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2323. tab_widget.addTab(self.translators_tab, _("Translators"))
  2324. self.license_tab = QtWidgets.QWidget()
  2325. self.license_tab.setObjectName("license_about")
  2326. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2327. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2328. tab_widget.addTab(self.license_tab, _("License"))
  2329. self.attributions_tab = QtWidgets.QWidget()
  2330. self.attributions_tab.setObjectName("attributions_about")
  2331. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2332. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2333. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2334. self.splash_tab_layout.addWidget(logo, stretch=0)
  2335. self.splash_tab_layout.addWidget(title, stretch=1)
  2336. pal = QtGui.QPalette()
  2337. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2338. self.prog_grid_lay = QtWidgets.QGridLayout()
  2339. self.prog_grid_lay.setHorizontalSpacing(20)
  2340. self.prog_grid_lay.setColumnStretch(0, 0)
  2341. self.prog_grid_lay.setColumnStretch(2, 1)
  2342. prog_widget = QtWidgets.QWidget()
  2343. prog_widget.setLayout(self.prog_grid_lay)
  2344. prog_scroll = QtWidgets.QScrollArea()
  2345. prog_scroll.setWidget(prog_widget)
  2346. prog_scroll.setWidgetResizable(True)
  2347. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2348. prog_scroll.setPalette(pal)
  2349. self.programmmers_tab_layout.addWidget(prog_scroll)
  2350. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2351. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2352. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2353. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2354. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2355. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2356. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2357. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2358. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2359. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2360. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2361. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2362. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2363. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2364. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2365. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2366. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2367. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2368. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2369. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2370. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2371. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2372. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2373. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2374. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2375. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2376. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2377. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2378. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2379. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2380. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2381. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2382. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2383. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2384. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2385. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2386. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2387. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2388. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2389. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2390. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2391. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2392. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2393. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2394. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2395. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2396. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2397. self.translator_grid_lay = QtWidgets.QGridLayout()
  2398. self.translator_grid_lay.setColumnStretch(0, 0)
  2399. self.translator_grid_lay.setColumnStretch(1, 0)
  2400. self.translator_grid_lay.setColumnStretch(2, 1)
  2401. self.translator_grid_lay.setColumnStretch(3, 0)
  2402. # trans_widget = QtWidgets.QWidget()
  2403. # trans_widget.setLayout(self.translator_grid_lay)
  2404. # self.translators_tab_layout.addWidget(trans_widget)
  2405. # self.translators_tab_layout.addStretch()
  2406. trans_widget = QtWidgets.QWidget()
  2407. trans_widget.setLayout(self.translator_grid_lay)
  2408. trans_scroll = QtWidgets.QScrollArea()
  2409. trans_scroll.setWidget(trans_widget)
  2410. trans_scroll.setWidgetResizable(True)
  2411. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2412. trans_scroll.setPalette(pal)
  2413. self.translators_tab_layout.addWidget(trans_scroll)
  2414. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2415. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2416. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2417. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2418. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2419. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2420. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2421. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2422. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2423. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2424. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2425. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2426. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2427. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2428. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2429. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2430. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2431. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2432. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2433. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2434. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2435. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2436. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2437. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2438. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2439. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2440. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2441. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2442. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2443. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2444. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2445. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2446. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2447. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2448. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2449. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2450. self.translator_grid_lay.setColumnStretch(0, 0)
  2451. self.translators_tab_layout.addStretch()
  2452. self.license_tab_layout.addWidget(lic_lbl_header)
  2453. self.license_tab_layout.addWidget(lic_lbl_body)
  2454. self.license_tab_layout.addStretch()
  2455. self.attributions_tab_layout.addWidget(attributions_label)
  2456. self.attributions_tab_layout.addStretch()
  2457. layout3.addStretch()
  2458. layout3.addWidget(closebtn)
  2459. closebtn.clicked.connect(self.accept)
  2460. AboutDialog(app=self, parent=self.ui).exec_()
  2461. def on_readme(self):
  2462. """
  2463. Displays the "about" dialog found in the Menu --> Help.
  2464. :return: None
  2465. """
  2466. class ReadmeDialog(QtWidgets.QDialog):
  2467. def __init__(self, app, parent=None):
  2468. QtWidgets.QDialog.__init__(self, parent)
  2469. self.app = app
  2470. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2471. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2472. "<b>click</b></a>"
  2473. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2474. # donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2475. # "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2476. # Icon and title
  2477. self.setWindowIcon(parent.app_icon)
  2478. self.setWindowTitle(_("Important Information's"))
  2479. self.resize(750, 375)
  2480. logo = QtWidgets.QLabel()
  2481. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2482. # content = QtWidgets.QLabel(
  2483. # "%s<br>"
  2484. # "%s<br><br>"
  2485. # "%s,<br>"
  2486. # "%s<br>"
  2487. # "<ul>"
  2488. # "<li> &nbsp;%s %s</li>"
  2489. # "<li> &nbsp;%s %s</li>"
  2490. # "</ul>"
  2491. # "%s %s.<br>"
  2492. # "%s"
  2493. # "<ul>"
  2494. # "<li> &nbsp;%s &#128077;</li>"
  2495. # "<li> &nbsp;%s &#128513;</li>"
  2496. # "</ul>" %
  2497. # (
  2498. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2499. # _("Yet it cannot evolve without <b>contributions</b>."),
  2500. # _("If you want to see this application grow and become better and better"),
  2501. # _("you can <b>contribute</b> to the development yourself by:"),
  2502. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2503. # new_features_link,
  2504. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2505. # bugs_link,
  2506. # _("If you like or use this program you can make a donation"),
  2507. # donation_link,
  2508. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2509. # _("it will be welcomed with joy"),
  2510. # _("it will give me a reason to continue")
  2511. # )
  2512. # )
  2513. content = QtWidgets.QLabel(
  2514. "%s<br>"
  2515. "%s<br><br>"
  2516. "%s,<br>"
  2517. "%s<br>"
  2518. "<ul>"
  2519. "<li> &nbsp;%s %s</li>"
  2520. "<li> &nbsp;%s %s</li>"
  2521. "</ul>" %
  2522. (
  2523. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2524. _("Yet it cannot evolve without <b>contributions</b>."),
  2525. _("If you want to see this application grow and become better and better"),
  2526. _("you can <b>contribute</b> to the development yourself by:"),
  2527. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2528. new_features_link,
  2529. _("Bug Reports by providing the steps required to reproduce the bug"),
  2530. bugs_link
  2531. )
  2532. )
  2533. content.setOpenExternalLinks(True)
  2534. # palette
  2535. pal = QtGui.QPalette()
  2536. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2537. # layouts
  2538. main_layout = QtWidgets.QVBoxLayout()
  2539. self.setLayout(main_layout)
  2540. tab_layout = QtWidgets.QHBoxLayout()
  2541. buttons_hlay = QtWidgets.QHBoxLayout()
  2542. main_layout.addLayout(tab_layout)
  2543. main_layout.addLayout(buttons_hlay)
  2544. tab_widget = QtWidgets.QTabWidget()
  2545. tab_layout.addWidget(tab_widget)
  2546. closebtn = QtWidgets.QPushButton(_("Close"))
  2547. buttons_hlay.addStretch()
  2548. buttons_hlay.addWidget(closebtn)
  2549. # CONTRIBUTE section
  2550. self.intro_tab = QtWidgets.QWidget()
  2551. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2552. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2553. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2554. self.grid_lay = QtWidgets.QGridLayout()
  2555. self.grid_lay.setHorizontalSpacing(20)
  2556. self.grid_lay.setColumnStretch(0, 0)
  2557. self.grid_lay.setColumnStretch(1, 1)
  2558. intro_wdg = QtWidgets.QWidget()
  2559. intro_wdg.setLayout(self.grid_lay)
  2560. intro_scroll_area = QtWidgets.QScrollArea()
  2561. intro_scroll_area.setWidget(intro_wdg)
  2562. intro_scroll_area.setWidgetResizable(True)
  2563. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2564. intro_scroll_area.setPalette(pal)
  2565. self.grid_lay.addWidget(logo, 0, 0)
  2566. self.grid_lay.addWidget(content, 0, 1)
  2567. self.intro_tab_layout.addWidget(intro_scroll_area)
  2568. # LINKS EXCHANGE section
  2569. self.links_tab = QtWidgets.QWidget()
  2570. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2571. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2572. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2573. self.links_lay = QtWidgets.QHBoxLayout()
  2574. links_wdg = QtWidgets.QWidget()
  2575. links_wdg.setLayout(self.links_lay)
  2576. links_scroll_area = QtWidgets.QScrollArea()
  2577. links_scroll_area.setWidget(links_wdg)
  2578. links_scroll_area.setWidgetResizable(True)
  2579. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2580. links_scroll_area.setPalette(pal)
  2581. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2582. self.links_tab_layout.addWidget(links_scroll_area)
  2583. # HOW TO section
  2584. self.howto_tab = QtWidgets.QWidget()
  2585. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2586. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2587. tab_widget.addTab(self.howto_tab, _("How To's"))
  2588. self.howto_lay = QtWidgets.QHBoxLayout()
  2589. howto_wdg = QtWidgets.QWidget()
  2590. howto_wdg.setLayout(self.howto_lay)
  2591. howto_scroll_area = QtWidgets.QScrollArea()
  2592. howto_scroll_area.setWidget(howto_wdg)
  2593. howto_scroll_area.setWidgetResizable(True)
  2594. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2595. howto_scroll_area.setPalette(pal)
  2596. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2597. self.howto_tab_layout.addWidget(howto_scroll_area)
  2598. # BUTTONS section
  2599. closebtn.clicked.connect(self.accept)
  2600. ReadmeDialog(app=self, parent=self.ui).exec_()
  2601. def install_bookmarks(self, book_dict=None):
  2602. """
  2603. Install the bookmarks actions in the Help menu -> Bookmarks
  2604. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2605. :return: None
  2606. """
  2607. if book_dict is None:
  2608. self.defaults["global_bookmarks"].update(
  2609. {
  2610. '1': ['FlatCAM', "http://flatcam.org"],
  2611. '2': ['Backup Site', ""]
  2612. }
  2613. )
  2614. else:
  2615. self.defaults["global_bookmarks"].clear()
  2616. self.defaults["global_bookmarks"].update(book_dict)
  2617. # first try to disconnect if somehow they get connected from elsewhere
  2618. for act in self.ui.menuhelp_bookmarks.actions():
  2619. try:
  2620. act.triggered.disconnect()
  2621. except TypeError:
  2622. pass
  2623. # clear all actions except the last one who is the Bookmark manager
  2624. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2625. pass
  2626. else:
  2627. self.ui.menuhelp_bookmarks.removeAction(act)
  2628. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2629. if self.defaults["global_bookmarks"]:
  2630. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2631. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2632. # the JSON is first making the keys as strings (therefore I have to use strings too
  2633. # or do the conversion :(
  2634. # )
  2635. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2636. # the '10' entry jsut after '1' therefore ordering as strings
  2637. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2638. key=lambda x: int(x[0]))
  2639. for entry, bookmark in sorted_bookmarks:
  2640. title = bookmark[0]
  2641. weblink = bookmark[1]
  2642. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2643. act.setText(title)
  2644. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2645. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2646. if title == 'Backup Site' and weblink == "":
  2647. act.triggered.connect(self.on_backup_site)
  2648. else:
  2649. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2650. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2651. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2652. def on_bookmarks_manager(self):
  2653. """
  2654. Adds the bookmark manager in a Tab in Plot Area
  2655. :return:
  2656. """
  2657. for idx in range(self.ui.plot_tab_area.count()):
  2658. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2659. # there can be only one instance of Bookmark Manager at one time
  2660. return
  2661. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2662. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2663. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2664. # add the tab if it was closed
  2665. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2666. # delete the absolute and relative position and messages in the infobar
  2667. # self.ui.position_label.setText("")
  2668. # self.ui.rel_position_label.setText("")
  2669. # hide coordinates toolbars in the infobar while in DB
  2670. self.ui.coords_toolbar.hide()
  2671. self.ui.delta_coords_toolbar.hide()
  2672. # Switch plot_area to preferences page
  2673. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2674. def on_backup_site(self):
  2675. msgbox = QtWidgets.QMessageBox()
  2676. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2677. "1. FlatCAM.org website is down\n"
  2678. "2. Someone forked FlatCAM project and wants to point\n"
  2679. "to his own website\n\n"
  2680. "If you can't get any informations about FlatCAM beta\n"
  2681. "use the YouTube channel link from the Help menu."))
  2682. msgbox.setWindowTitle(_("Alternative website"))
  2683. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2684. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2685. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2686. msgbox.setDefaultButton(bt_yes)
  2687. msgbox.exec_()
  2688. # response = msgbox.clickedButton()
  2689. def on_file_savedefaults(self):
  2690. """
  2691. Callback for menu item File->Save Defaults. Saves application default options
  2692. ``self.defaults`` to current_defaults.FlatConfig.
  2693. :return: None
  2694. """
  2695. self.preferencesUiManager.save_defaults()
  2696. def final_save(self):
  2697. """
  2698. Callback for doing a preferences save to file whenever the application is about to quit.
  2699. If the project has changes, it will ask the user to save the project.
  2700. :return: None
  2701. """
  2702. if self.save_in_progress:
  2703. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2704. return
  2705. if self.should_we_save and self.collection.get_list():
  2706. msgbox = QtWidgets.QMessageBox()
  2707. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2708. "\n"
  2709. "Do you want to Save the project?"))
  2710. msgbox.setWindowTitle(_("Save changes"))
  2711. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2712. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2713. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2714. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2715. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2716. msgbox.setDefaultButton(bt_yes)
  2717. msgbox.exec_()
  2718. response = msgbox.clickedButton()
  2719. if response == bt_yes:
  2720. try:
  2721. self.trayIcon.hide()
  2722. except Exception:
  2723. pass
  2724. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2725. elif response == bt_no:
  2726. try:
  2727. self.trayIcon.hide()
  2728. except Exception:
  2729. pass
  2730. self.quit_application()
  2731. elif response == bt_cancel:
  2732. return
  2733. else:
  2734. try:
  2735. self.trayIcon.hide()
  2736. except Exception:
  2737. pass
  2738. self.quit_application()
  2739. def quit_application(self):
  2740. """
  2741. Called (as a pyslot or not) when the application is quit.
  2742. :return: None
  2743. """
  2744. # close editors before quiting the app, if they are open
  2745. if self.geo_editor.editor_active is True:
  2746. self.geo_editor.deactivate()
  2747. try:
  2748. self.geo_editor.disconnect()
  2749. except TypeError:
  2750. pass
  2751. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2752. if self.exc_editor.editor_active is True:
  2753. self.exc_editor.deactivate()
  2754. try:
  2755. self.grb_editor.disconnect()
  2756. except TypeError:
  2757. pass
  2758. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2759. if self.grb_editor.editor_active is True:
  2760. self.grb_editor.deactivate_grb_editor()
  2761. try:
  2762. self.exc_editor.disconnect()
  2763. except TypeError:
  2764. pass
  2765. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2766. # disconnect the mouse events
  2767. if self.is_legacy:
  2768. self.plotcanvas.graph_event_disconnect(self.mm)
  2769. self.plotcanvas.graph_event_disconnect(self.mp)
  2770. self.plotcanvas.graph_event_disconnect(self.mr)
  2771. self.plotcanvas.graph_event_disconnect(self.mdc)
  2772. self.plotcanvas.graph_event_disconnect(self.kp)
  2773. else:
  2774. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2775. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2776. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2777. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2778. self.on_mouse_double_click_over_plot)
  2779. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2780. self.preferencesUiManager.save_defaults(silent=True)
  2781. log.debug("App.quit_application() --> App Defaults saved.")
  2782. if self.cmd_line_headless != 1:
  2783. # save app state to file
  2784. stgs = QSettings("Open Source", "FlatCAM")
  2785. stgs.setValue('saved_gui_state', self.ui.saveState())
  2786. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2787. stgs.setValue(
  2788. 'language',
  2789. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2790. )
  2791. stgs.setValue(
  2792. 'notebook_font_size',
  2793. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2794. )
  2795. stgs.setValue(
  2796. 'axis_font_size',
  2797. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2798. )
  2799. stgs.setValue(
  2800. 'textbox_font_size',
  2801. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2802. )
  2803. stgs.setValue(
  2804. 'hud_font_size',
  2805. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2806. )
  2807. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2808. stgs.setValue(
  2809. 'machinist',
  2810. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2811. )
  2812. # This will write the setting to the platform specific storage.
  2813. del stgs
  2814. log.debug("App.quit_application() --> App UI state saved.")
  2815. # try to quit the Socket opened by ArgsThread class
  2816. try:
  2817. # self.new_launch.thread_exit = True
  2818. # self.new_launch.listener.close()
  2819. self.new_launch.stop.emit()
  2820. except Exception as err:
  2821. log.debug("App.quit_application() --> %s" % str(err))
  2822. # try to quit the QThread that run ArgsThread class
  2823. try:
  2824. # del self.new_launch
  2825. self.listen_th.quit()
  2826. except Exception as e:
  2827. log.debug("App.quit_application() --> %s" % str(e))
  2828. # terminate workers
  2829. # self.workers.__del__()
  2830. self.clear_pool()
  2831. # quit app by signalling for self.kill_app() method
  2832. # self.close_app_signal.emit()
  2833. QtWidgets.qApp.quit()
  2834. sys.exit(0)
  2835. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2836. # we use the following command
  2837. # minor_v = sys.version_info.minor
  2838. # if minor_v < 8:
  2839. # # make sure that the app closes
  2840. # sys.exit(0)
  2841. # else:
  2842. # os._exit(0) # fix to work with Python 3.8
  2843. @staticmethod
  2844. def kill_app():
  2845. QtWidgets.qApp.quit()
  2846. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2847. # we use the following command
  2848. sys.exit(0)
  2849. def on_portable_checked(self, state):
  2850. """
  2851. Callback called when the checkbox in Preferences GUI is checked.
  2852. It will set the application as portable by creating the preferences and recent files in the
  2853. 'config' folder found in the FlatCAM installation folder.
  2854. :param state: boolean, the state of the checkbox when clicked/checked
  2855. :return:
  2856. """
  2857. line_no = 0
  2858. data = None
  2859. if sys.platform != 'win32':
  2860. # this won't work in Linux or MacOS
  2861. return
  2862. # test if the app was frozen and choose the path for the configuration file
  2863. if getattr(sys, "frozen", False) is True:
  2864. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2865. else:
  2866. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2867. config_file = current_data_path + '\\configuration.txt'
  2868. try:
  2869. with open(config_file, 'r') as f:
  2870. try:
  2871. data = f.readlines()
  2872. except Exception as e:
  2873. log.debug('App.__init__() -->%s' % str(e))
  2874. return
  2875. except FileNotFoundError:
  2876. pass
  2877. for line in data:
  2878. line = line.strip('\n')
  2879. param = str(line).rpartition('=')
  2880. if param[0] == 'portable':
  2881. break
  2882. line_no += 1
  2883. if state:
  2884. data[line_no] = 'portable=True\n'
  2885. # create the new defauults files
  2886. # create current_defaults.FlatConfig file if there is none
  2887. try:
  2888. f = open(current_data_path + '/current_defaults.FlatConfig')
  2889. f.close()
  2890. except IOError:
  2891. App.log.debug('Creating empty current_defaults.FlatConfig')
  2892. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2893. json.dump({}, f)
  2894. f.close()
  2895. # create factory_defaults.FlatConfig file if there is none
  2896. try:
  2897. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2898. f.close()
  2899. except IOError:
  2900. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2901. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2902. json.dump({}, f)
  2903. f.close()
  2904. try:
  2905. f = open(current_data_path + '/recent.json')
  2906. f.close()
  2907. except IOError:
  2908. App.log.debug('Creating empty recent.json')
  2909. f = open(current_data_path + '/recent.json', 'w')
  2910. json.dump([], f)
  2911. f.close()
  2912. try:
  2913. fp = open(current_data_path + '/recent_projects.json')
  2914. fp.close()
  2915. except IOError:
  2916. App.log.debug('Creating empty recent_projects.json')
  2917. fp = open(current_data_path + '/recent_projects.json', 'w')
  2918. json.dump([], fp)
  2919. fp.close()
  2920. # save the current defaults to the new defaults file
  2921. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2922. else:
  2923. data[line_no] = 'portable=False\n'
  2924. with open(config_file, 'w') as f:
  2925. f.writelines(data)
  2926. def on_register_files(self, obj_type=None):
  2927. """
  2928. Called whenever there is a need to register file extensions with FlatCAM.
  2929. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2930. :param obj_type: the type of object to be register for.
  2931. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2932. :return: None
  2933. """
  2934. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2935. new_reg_path = 'Software\\Classes\\'
  2936. # find if the current user is admin
  2937. try:
  2938. is_admin = os.getuid() == 0
  2939. except AttributeError:
  2940. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2941. if is_admin is True:
  2942. root_path = winreg.HKEY_LOCAL_MACHINE
  2943. else:
  2944. root_path = winreg.HKEY_CURRENT_USER
  2945. # create the keys
  2946. def set_reg(name, root_pth, new_reg_path, value):
  2947. try:
  2948. winreg.CreateKey(root_pth, new_reg_path)
  2949. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2950. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2951. return True
  2952. except WindowsError:
  2953. return False
  2954. # delete key in registry
  2955. def delete_reg(root_pth, reg_path, key_to_del):
  2956. key_to_del_path = reg_path + key_to_del
  2957. try:
  2958. winreg.DeleteKey(root_pth, key_to_del_path)
  2959. return True
  2960. except WindowsError:
  2961. return False
  2962. if obj_type is None or obj_type == 'excellon':
  2963. exc_list = \
  2964. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2965. exc_list = [x for x in exc_list if x != '']
  2966. # register all keys in the Preferences window
  2967. for ext in exc_list:
  2968. new_k = new_reg_path + '.%s' % ext
  2969. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2970. # and unregister those that are no longer in the Preferences windows but are in the file
  2971. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2972. if ext not in exc_list:
  2973. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2974. # now write the updated extensions to the self.defaults
  2975. # new_ext = ''
  2976. # for ext in exc_list:
  2977. # new_ext = new_ext + ext + ', '
  2978. # self.defaults["fa_excellon"] = new_ext
  2979. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2980. if obj_type is None or obj_type == 'gcode':
  2981. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2982. gco_list = [x for x in gco_list if x != '']
  2983. # register all keys in the Preferences window
  2984. for ext in gco_list:
  2985. new_k = new_reg_path + '.%s' % ext
  2986. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2987. # and unregister those that are no longer in the Preferences windows but are in the file
  2988. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2989. if ext not in gco_list:
  2990. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2991. # now write the updated extensions to the self.defaults
  2992. # new_ext = ''
  2993. # for ext in gco_list:
  2994. # new_ext = new_ext + ext + ', '
  2995. # self.defaults["fa_gcode"] = new_ext
  2996. self.inform.emit('[success] %s' %
  2997. _("Selected GCode file extensions registered with FlatCAM."))
  2998. if obj_type is None or obj_type == 'gerber':
  2999. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3000. grb_list = [x for x in grb_list if x != '']
  3001. # register all keys in the Preferences window
  3002. for ext in grb_list:
  3003. new_k = new_reg_path + '.%s' % ext
  3004. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3005. # and unregister those that are no longer in the Preferences windows but are in the file
  3006. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3007. if ext not in grb_list:
  3008. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3009. # now write the updated extensions to the self.defaults
  3010. # new_ext = ''
  3011. # for ext in grb_list:
  3012. # new_ext = new_ext + ext + ', '
  3013. # self.defaults["fa_gerber"] = new_ext
  3014. self.inform.emit('[success] %s' %
  3015. _("Selected Gerber file extensions registered with FlatCAM."))
  3016. def add_extension(self, ext_type):
  3017. """
  3018. Add a file extension to the list for a specific object
  3019. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3020. :return:
  3021. """
  3022. if ext_type == 'excellon':
  3023. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3024. if new_ext == '':
  3025. return
  3026. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3027. if new_ext in old_val:
  3028. return
  3029. old_val.append(new_ext)
  3030. old_val.sort()
  3031. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3032. if ext_type == 'gcode':
  3033. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3034. if new_ext == '':
  3035. return
  3036. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3037. if new_ext in old_val:
  3038. return
  3039. old_val.append(new_ext)
  3040. old_val.sort()
  3041. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3042. if ext_type == 'gerber':
  3043. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3044. if new_ext == '':
  3045. return
  3046. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3047. if new_ext in old_val:
  3048. return
  3049. old_val.append(new_ext)
  3050. old_val.sort()
  3051. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3052. if ext_type == 'keyword':
  3053. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3054. if new_kw == '':
  3055. return
  3056. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3057. if new_kw in old_val:
  3058. return
  3059. old_val.append(new_kw)
  3060. old_val.sort()
  3061. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3062. # update the self.myKeywords so the model is updated
  3063. self.autocomplete_kw_list = \
  3064. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3065. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3066. self.shell._edit.set_model_data(self.myKeywords)
  3067. def del_extension(self, ext_type):
  3068. """
  3069. Remove a file extension from the list for a specific object
  3070. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3071. :return:
  3072. """
  3073. if ext_type == 'excellon':
  3074. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3075. if new_ext == '':
  3076. return
  3077. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3078. if new_ext not in old_val:
  3079. return
  3080. old_val.remove(new_ext)
  3081. old_val.sort()
  3082. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3083. if ext_type == 'gcode':
  3084. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3085. if new_ext == '':
  3086. return
  3087. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3088. if new_ext not in old_val:
  3089. return
  3090. old_val.remove(new_ext)
  3091. old_val.sort()
  3092. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3093. if ext_type == 'gerber':
  3094. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3095. if new_ext == '':
  3096. return
  3097. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3098. if new_ext not in old_val:
  3099. return
  3100. old_val.remove(new_ext)
  3101. old_val.sort()
  3102. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3103. if ext_type == 'keyword':
  3104. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3105. if new_kw == '':
  3106. return
  3107. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3108. if new_kw not in old_val:
  3109. return
  3110. old_val.remove(new_kw)
  3111. old_val.sort()
  3112. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3113. # update the self.myKeywords so the model is updated
  3114. self.autocomplete_kw_list = \
  3115. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3116. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3117. self.shell._edit.set_model_data(self.myKeywords)
  3118. def restore_extensions(self, ext_type):
  3119. """
  3120. Restore all file extensions associations with FlatCAM, for a specific object
  3121. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3122. :return:
  3123. """
  3124. if ext_type == 'excellon':
  3125. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3126. # for the ability to open Excellon files with .txt extension
  3127. new_exc_list = deepcopy(self.exc_list)
  3128. try:
  3129. new_exc_list.remove('txt')
  3130. except ValueError:
  3131. pass
  3132. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3133. if ext_type == 'gcode':
  3134. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3135. if ext_type == 'gerber':
  3136. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3137. if ext_type == 'keyword':
  3138. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3139. # update the self.myKeywords so the model is updated
  3140. self.autocomplete_kw_list = self.default_keywords
  3141. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3142. self.shell._edit.set_model_data(self.myKeywords)
  3143. def delete_all_extensions(self, ext_type):
  3144. """
  3145. Delete all file extensions associations with FlatCAM, for a specific object
  3146. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3147. :return:
  3148. """
  3149. if ext_type == 'excellon':
  3150. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3151. if ext_type == 'gcode':
  3152. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3153. if ext_type == 'gerber':
  3154. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3155. if ext_type == 'keyword':
  3156. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3157. # update the self.myKeywords so the model is updated
  3158. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3159. self.shell._edit.set_model_data(self.myKeywords)
  3160. def on_edit_join(self, name=None):
  3161. """
  3162. Callback for Edit->Join. Joins the selected geometry objects into
  3163. a new one.
  3164. :return: None
  3165. """
  3166. self.defaults.report_usage("on_edit_join()")
  3167. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3168. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3169. geo_type_set = set()
  3170. objs = self.collection.get_selected()
  3171. if len(objs) < 2:
  3172. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3173. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3174. return 'fail'
  3175. for obj in objs:
  3176. geo_type_set.add(obj.multigeo)
  3177. # if len(geo_type_list) == 1 means that all list elements are the same
  3178. if len(geo_type_set) != 1:
  3179. self.inform.emit('[ERROR] %s' %
  3180. _("Failed join. The Geometry objects are of different types.\n"
  3181. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3182. "convert from one to another and retry joining \n"
  3183. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3184. "the result may not be what was expected. \n"
  3185. "Check the generated GCODE."))
  3186. return
  3187. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3188. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3189. if True in geo_type_set:
  3190. def initialize(geo_obj, app):
  3191. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3192. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3193. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3194. for v in geo_obj.tools.values():
  3195. v['data']['name'] = obj_name_multi
  3196. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3197. else:
  3198. def initialize(geo_obj, app):
  3199. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3200. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3201. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3202. for v in geo_obj.tools.values():
  3203. v['data']['name'] = obj_name_single
  3204. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3205. self.should_we_save = True
  3206. def on_edit_join_exc(self):
  3207. """
  3208. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3209. a new Excellon.
  3210. :return: None
  3211. """
  3212. self.defaults.report_usage("on_edit_join_exc()")
  3213. objs = self.collection.get_selected()
  3214. for obj in objs:
  3215. if not isinstance(obj, ExcellonObject):
  3216. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3217. return
  3218. if len(objs) < 2:
  3219. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3220. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3221. return 'fail'
  3222. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3223. def initialize(exc_obj, app):
  3224. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3225. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3226. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3227. self.should_we_save = True
  3228. def on_edit_join_grb(self):
  3229. """
  3230. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3231. a new Gerber object.
  3232. :return: None
  3233. """
  3234. self.defaults.report_usage("on_edit_join_grb()")
  3235. objs = self.collection.get_selected()
  3236. for obj in objs:
  3237. if not isinstance(obj, GerberObject):
  3238. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3239. return
  3240. if len(objs) < 2:
  3241. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3242. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3243. return 'fail'
  3244. def initialize(grb_obj, app):
  3245. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3246. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3247. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3248. self.should_we_save = True
  3249. def on_convert_singlegeo_to_multigeo(self):
  3250. """
  3251. Called for converting a Geometry object from single-geo to multi-geo.
  3252. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3253. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3254. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3255. the solid-geometry of that tool.
  3256. :return: None
  3257. """
  3258. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3259. obj = self.collection.get_active()
  3260. if obj is None:
  3261. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3262. return
  3263. if not isinstance(obj, GeometryObject):
  3264. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3265. return
  3266. obj.multigeo = True
  3267. for tooluid, dict_value in obj.tools.items():
  3268. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3269. if not isinstance(obj.solid_geometry, list):
  3270. obj.solid_geometry = [obj.solid_geometry]
  3271. # obj.solid_geometry[:] = []
  3272. obj.plot()
  3273. self.should_we_save = True
  3274. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3275. def on_convert_multigeo_to_singlegeo(self):
  3276. """
  3277. Called for converting a Geometry object from multi-geo to single-geo.
  3278. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3279. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3280. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3281. the solid-geometry of that tool.
  3282. :return: None
  3283. """
  3284. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3285. obj = self.collection.get_active()
  3286. if obj is None:
  3287. self.inform.emit('[ERROR_NOTCL] %s' %
  3288. _("Failed. Select a Geometry Object and try again."))
  3289. return
  3290. if not isinstance(obj, GeometryObject):
  3291. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3292. (_("Expected a GeometryObject, got"), type(obj)))
  3293. return
  3294. obj.multigeo = False
  3295. total_solid_geometry = []
  3296. for tooluid, dict_value in obj.tools.items():
  3297. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3298. # clear the original geometry
  3299. dict_value['solid_geometry'][:] = []
  3300. obj.solid_geometry = deepcopy(total_solid_geometry)
  3301. obj.plot()
  3302. self.should_we_save = True
  3303. self.inform.emit('[success] %s' %
  3304. _("A Geometry object was converted to SingleGeo type."))
  3305. def on_defaults_dict_change(self, field):
  3306. """
  3307. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3308. Edit -> Preferences tab window.
  3309. :param field: the key of the self.defaults dictionary that was changed.
  3310. :return: None
  3311. """
  3312. self.preferencesUiManager.defaults_write_form_field(field=field)
  3313. if field == "units":
  3314. self.set_screen_units(self.defaults['units'])
  3315. def set_screen_units(self, units):
  3316. """
  3317. Set the FlatCAM units on the status bar.
  3318. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3319. :return: None
  3320. """
  3321. self.ui.units_label.setText("[" + units.lower() + "]")
  3322. def on_toggle_units_click(self):
  3323. try:
  3324. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3325. except (TypeError, AttributeError):
  3326. pass
  3327. if self.defaults["units"] == 'MM':
  3328. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3329. else:
  3330. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3331. self.on_toggle_units(no_pref=True)
  3332. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3333. lambda: self.on_toggle_units(no_pref=False))
  3334. def on_toggle_units(self, no_pref=False):
  3335. """
  3336. Callback for the Units radio-button change in the Preferences tab.
  3337. Changes the application's default units adn for the project too.
  3338. If changing the project's units, the change propagates to all of
  3339. the objects in the project.
  3340. :return: None
  3341. """
  3342. self.defaults.report_usage("on_toggle_units")
  3343. if self.toggle_units_ignore:
  3344. return
  3345. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3346. # If option is the same, then ignore
  3347. if new_units == self.defaults["units"].upper():
  3348. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3349. return
  3350. # Keys in self.defaults for which to scale their values
  3351. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3352. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3353. "tools_iso_tool_vtipdia",
  3354. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3355. "gerber_editor_ma_high",
  3356. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3357. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3358. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3359. "excellon_feedrate_probe", "excellon_milling_dia",
  3360. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3361. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3362. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3363. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3364. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3365. "geometry_extracut_length", "geometry_z_pdepth",
  3366. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3367. 'cncjob_tooldia',
  3368. 'tools_paintoffset', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3369. "tools_paintnewdia",
  3370. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3371. "tools_nccnewdia", "tools_ncc_offset_value",
  3372. "tools_2sided_drilldia",
  3373. "tools_film_boundary", "tools_film_scale_stroke",
  3374. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3375. "tools_cutout_depthperpass",
  3376. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3377. "tools_panelize_spacing_rows",
  3378. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3379. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3380. "tools_transform_buffer_dis",
  3381. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3382. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3383. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3384. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3385. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3386. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3387. "tools_cr_h2h_val", "tools_cr_dh_val",
  3388. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3389. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3390. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3391. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3392. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3393. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3394. "tools_copper_thieving_mask_clearance",
  3395. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3396. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3397. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3398. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3399. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3400. "tools_invert_margin",
  3401. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3402. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3403. def scale_defaults(sfactor):
  3404. for dim in dimensions:
  3405. if dim in [
  3406. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3407. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3408. 'tools_transform_mirror_point'
  3409. ]:
  3410. if self.defaults[dim] is None or self.defaults[dim] == '':
  3411. continue
  3412. try:
  3413. coordinates = self.defaults[dim].split(",")
  3414. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3415. coords_xy[0] *= sfactor
  3416. coords_xy[1] *= sfactor
  3417. self.defaults[dim] = "%.*f, %.*f" % (
  3418. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3419. except Exception as e:
  3420. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3421. elif dim in [
  3422. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3423. ]:
  3424. if self.defaults[dim] is None or self.defaults[dim] == '':
  3425. continue
  3426. try:
  3427. self.defaults[dim] = float(self.defaults[dim])
  3428. tools_diameters = [self.defaults[dim]]
  3429. except ValueError:
  3430. try:
  3431. tools_string = self.defaults[dim].split(",")
  3432. tools_diameters = [eval(a) for a in tools_string if a != '']
  3433. except Exception as e:
  3434. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3435. continue
  3436. self.defaults[dim] = ''
  3437. td_len = len(tools_diameters)
  3438. if td_len > 1:
  3439. for t in range(td_len):
  3440. tools_diameters[t] *= sfactor
  3441. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3442. else:
  3443. tools_diameters[0] *= sfactor
  3444. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3445. elif dim in ['global_gridx', 'global_gridy']:
  3446. # format the number of decimals to the one specified in self.decimals
  3447. try:
  3448. val = float(self.defaults[dim]) * sfactor
  3449. except Exception as e:
  3450. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3451. continue
  3452. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3453. else:
  3454. # the number of decimals for the rest is kept unchanged
  3455. if self.defaults[dim]:
  3456. try:
  3457. val = float(self.defaults[dim]) * sfactor
  3458. except Exception as e:
  3459. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3460. continue
  3461. self.defaults[dim] = val
  3462. # The scaling factor depending on choice of units.
  3463. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3464. # Changing project units. Warn user.
  3465. msgbox = QtWidgets.QMessageBox()
  3466. msgbox.setWindowTitle(_("Toggle Units"))
  3467. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3468. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3469. msgbox.setText(_("Changing the units of the project\n"
  3470. "will scale all objects.\n\n"
  3471. "Do you want to continue?"))
  3472. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3473. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3474. msgbox.setDefaultButton(bt_ok)
  3475. msgbox.exec_()
  3476. response = msgbox.clickedButton()
  3477. if response == bt_ok:
  3478. if no_pref is False:
  3479. self.preferencesUiManager.defaults_read_form()
  3480. scale_defaults(factor)
  3481. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3482. self.defaults["units"] = new_units
  3483. # update the defaults from form, some may assume that the conversion is enough and it's not
  3484. self.on_options_app2project()
  3485. # update the objects
  3486. for obj in self.collection.get_list():
  3487. obj.convert_units(new_units)
  3488. # make that the properties stored in the object are also updated
  3489. self.app_obj.object_changed.emit(obj)
  3490. # rebuild the object UI
  3491. obj.build_ui()
  3492. # change this only if the workspace is active
  3493. if self.defaults['global_workspace'] is True:
  3494. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3495. # adjust the grid values on the main toolbar
  3496. val_x = float(self.defaults['global_gridx']) * factor
  3497. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3498. current = self.collection.get_active()
  3499. if current is not None:
  3500. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3501. if not isinstance(current, GeometryObject):
  3502. current.to_form()
  3503. # replot all objects
  3504. self.plot_all()
  3505. # set the status labels to reflect the current FlatCAM units
  3506. self.set_screen_units(new_units)
  3507. # signal to the app that we changed the object properties and it should save the project
  3508. self.should_we_save = True
  3509. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3510. else:
  3511. # Undo toggling
  3512. self.toggle_units_ignore = True
  3513. if self.defaults['units'].upper() == 'MM':
  3514. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3515. else:
  3516. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3517. self.toggle_units_ignore = False
  3518. # store the grid values so they are not changed in the next step
  3519. val_x = float(self.defaults['global_gridx'])
  3520. val_y = float(self.defaults['global_gridy'])
  3521. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3522. self.preferencesUiManager.defaults_read_form()
  3523. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3524. # in self.defaults from the GUI elements but
  3525. # I don't want it for the grid values, so I update them here
  3526. self.defaults['global_gridx'] = val_x
  3527. self.defaults['global_gridy'] = val_y
  3528. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3529. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3530. def on_deselect_all(self):
  3531. self.collection.set_all_inactive()
  3532. self.delete_selection_shape()
  3533. def on_workspace_modified(self):
  3534. # self.save_defaults(silent=True)
  3535. self.plotcanvas.delete_workspace()
  3536. self.preferencesUiManager.defaults_read_form()
  3537. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3538. def on_workspace(self):
  3539. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3540. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3541. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3542. else:
  3543. self.plotcanvas.delete_workspace()
  3544. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3545. self.preferencesUiManager.defaults_read_form()
  3546. # self.save_defaults(silent=True)
  3547. def on_workspace_toggle(self):
  3548. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3549. try:
  3550. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3551. except TypeError:
  3552. pass
  3553. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3554. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3555. self.on_workspace()
  3556. def on_cursor_type(self, val):
  3557. """
  3558. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3559. :return: None
  3560. """
  3561. self.app_cursor.enabled = False
  3562. if val == 'small':
  3563. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3564. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3565. self.app_cursor = self.plotcanvas.new_cursor()
  3566. else:
  3567. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3568. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3569. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3570. if self.ui.grid_snap_btn.isChecked():
  3571. self.app_cursor.enabled = True
  3572. else:
  3573. self.app_cursor.enabled = False
  3574. def on_tool_add_keypress(self):
  3575. # ## Current application units in Upper Case
  3576. self.units = self.defaults['units'].upper()
  3577. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3578. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3579. if notebook_widget_name == 'selected_tab':
  3580. if self.collection.get_active().kind == 'geometry':
  3581. # Tool add works for Geometry only if Advanced is True in Preferences
  3582. if self.defaults["global_app_level"] == 'a':
  3583. tool_add_popup = FCInputDialog(title="New Tool ...",
  3584. text='Enter a Tool Diameter:',
  3585. min=0.0000, max=99.9999, decimals=4)
  3586. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3587. val, ok = tool_add_popup.get_value()
  3588. if ok:
  3589. if float(val) == 0:
  3590. self.inform.emit('[WARNING_NOTCL] %s' %
  3591. _("Please enter a tool diameter with non-zero value, in Float format."))
  3592. return
  3593. self.collection.get_active().on_tool_add(dia=float(val))
  3594. else:
  3595. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3596. else:
  3597. msgbox = QtWidgets.QMessageBox()
  3598. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3599. "Go to Preferences -> General - Show Advanced Options."))
  3600. msgbox.setWindowTitle("Tool adding ...")
  3601. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3602. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3603. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3604. msgbox.setDefaultButton(bt_ok)
  3605. msgbox.exec_()
  3606. # work only if the notebook tab on focus is the Tools_Tab
  3607. if notebook_widget_name == 'tool_tab':
  3608. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3609. # and only if the tool is NCC Tool
  3610. if tool_widget == self.ncclear_tool.toolName:
  3611. self.ncclear_tool.on_add_tool_by_key()
  3612. # and only if the tool is Paint Area Tool
  3613. elif tool_widget == self.paint_tool.toolName:
  3614. self.paint_tool.on_add_tool_by_key()
  3615. # and only if the tool is Solder Paste Dispensing Tool
  3616. elif tool_widget == self.paste_tool.toolName:
  3617. self.paste_tool.on_add_tool_by_key()
  3618. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3619. # See description below.
  3620. def on_delete_keypress(self):
  3621. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3622. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3623. if notebook_widget_name == 'selected_tab':
  3624. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3625. self.collection.get_active().on_tool_delete()
  3626. # work only if the notebook tab on focus is the Tools_Tab
  3627. elif notebook_widget_name == 'tool_tab':
  3628. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3629. # and only if the tool is NCC Tool
  3630. if tool_widget == self.ncclear_tool.toolName:
  3631. self.ncclear_tool.on_tool_delete()
  3632. # and only if the tool is Paint Tool
  3633. elif tool_widget == self.paint_tool.toolName:
  3634. self.paint_tool.on_tool_delete()
  3635. # and only if the tool is Solder Paste Dispensing Tool
  3636. elif tool_widget == self.paste_tool.toolName:
  3637. self.paste_tool.on_tool_delete()
  3638. # and only if the tool is Isolation Tool
  3639. elif tool_widget == self.isolation_tool.toolName:
  3640. self.isolation_tool.on_tool_delete()
  3641. else:
  3642. self.on_delete()
  3643. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3644. # some screens you have to be careful where you hover with your mouse.
  3645. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3646. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3647. # Complicated, I know :)
  3648. def on_delete(self, force_deletion=False):
  3649. """
  3650. Delete the currently selected FlatCAMObjs.
  3651. :param force_deletion: used by Tcl command
  3652. :return: None
  3653. """
  3654. self.defaults.report_usage("on_delete()")
  3655. response = None
  3656. bt_ok = None
  3657. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3658. # a geometry object before we update it.
  3659. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3660. and self.grb_editor.editor_active is False:
  3661. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3662. msgbox = QtWidgets.QMessageBox()
  3663. msgbox.setWindowTitle(_("Delete objects"))
  3664. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3665. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3666. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3667. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3668. "the selected objects?"))
  3669. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3670. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3671. msgbox.setDefaultButton(bt_ok)
  3672. msgbox.exec_()
  3673. response = msgbox.clickedButton()
  3674. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3675. response = bt_ok
  3676. if response == bt_ok:
  3677. if self.collection.get_active():
  3678. self.log.debug("App.on_delete()")
  3679. for obj_active in self.collection.get_selected():
  3680. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3681. if obj_active.kind == 'gerber':
  3682. obj_active.mark_shapes_storage.clear()
  3683. obj_active.mark_shapes.clear(update=True)
  3684. obj_active.mark_shapes.enabled = False
  3685. elif obj_active.kind == 'cncjob':
  3686. try:
  3687. obj_active.text_col.enabled = False
  3688. del obj_active.text_col
  3689. obj_active.annotation.clear(update=True)
  3690. del obj_active.annotation
  3691. except AttributeError as e:
  3692. log.debug(
  3693. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3694. )
  3695. while self.collection.get_selected():
  3696. self.delete_first_selected()
  3697. # make sure that the selection shape is deleted, too
  3698. self.delete_selection_shape()
  3699. # if there are no longer objects delete also the exclusion areas shapes
  3700. if not self.collection.get_list():
  3701. self.exc_areas.clear_shapes()
  3702. self.inform.emit('%s...' % _("Object(s) deleted"))
  3703. else:
  3704. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3705. else:
  3706. self.inform.emit(_("Save the work in Editor and try again ..."))
  3707. def delete_first_selected(self):
  3708. # Keep this for later
  3709. try:
  3710. sel_obj = self.collection.get_active()
  3711. name = sel_obj.options["name"]
  3712. isPlotted = sel_obj.options["plot"]
  3713. except AttributeError:
  3714. self.log.debug("Nothing selected for deletion")
  3715. return
  3716. if self.is_legacy is True:
  3717. # Remove plot only if the object was plotted otherwise delaxes will fail
  3718. if isPlotted:
  3719. try:
  3720. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3721. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3722. except Exception as e:
  3723. log.debug("App.delete_first_selected() --> %s" % str(e))
  3724. self.plotcanvas.auto_adjust_axes()
  3725. # Remove from dictionary
  3726. self.collection.delete_active()
  3727. # Clear form
  3728. self.setup_component_editor()
  3729. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3730. def on_set_origin(self):
  3731. """
  3732. Set the origin to the left mouse click position
  3733. :return: None
  3734. """
  3735. # display the message for the user
  3736. # and ask him to click on the desired position
  3737. self.defaults.report_usage("on_set_origin()")
  3738. def origin_replot():
  3739. def worker_task():
  3740. with self.proc_container.new('%s...' % _("Plotting")):
  3741. for obj in self.collection.get_list():
  3742. obj.plot()
  3743. self.plotcanvas.fit_view()
  3744. if self.is_legacy:
  3745. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3746. else:
  3747. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3748. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3749. self.inform.emit(_('Click to set the origin ...'))
  3750. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3751. # first disconnect it as it may have been used by something else
  3752. try:
  3753. self.replot_signal.disconnect()
  3754. except TypeError:
  3755. pass
  3756. self.replot_signal[list].connect(origin_replot)
  3757. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3758. """
  3759. :param event:
  3760. :param location:
  3761. :param noplot:
  3762. :param use_thread:
  3763. :return:
  3764. """
  3765. noplot_sig = noplot
  3766. def worker_task():
  3767. with self.proc_container.new(_("Setting Origin...")):
  3768. obj_list = self.collection.get_list()
  3769. for obj in obj_list:
  3770. obj.offset((x, y))
  3771. self.app_obj.object_changed.emit(obj)
  3772. # Update the object bounding box options
  3773. a, b, c, d = obj.bounds()
  3774. obj.options['xmin'] = a
  3775. obj.options['ymin'] = b
  3776. obj.options['xmax'] = c
  3777. obj.options['ymax'] = d
  3778. self.inform.emit('[success] %s...' % _('Origin set'))
  3779. for obj in obj_list:
  3780. out_name = obj.options["name"]
  3781. if obj.kind == 'gerber':
  3782. obj.source_file = self.export_gerber(
  3783. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3784. elif obj.kind == 'excellon':
  3785. obj.source_file = self.export_excellon(
  3786. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3787. if noplot_sig is False:
  3788. self.replot_signal.emit([])
  3789. if location is not None:
  3790. if len(location) != 2:
  3791. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3792. return 'fail'
  3793. x, y = location
  3794. if use_thread is True:
  3795. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3796. else:
  3797. worker_task()
  3798. self.should_we_save = True
  3799. return
  3800. if event is not None and event.button == 1:
  3801. if self.is_legacy is False:
  3802. event_pos = event.pos
  3803. else:
  3804. event_pos = (event.xdata, event.ydata)
  3805. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3806. if self.grid_status():
  3807. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3808. else:
  3809. pos = pos_canvas
  3810. x = 0 - pos[0]
  3811. y = 0 - pos[1]
  3812. if use_thread is True:
  3813. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3814. else:
  3815. worker_task()
  3816. self.should_we_save = True
  3817. def on_move2origin(self, use_thread=True):
  3818. """
  3819. Move selected objects to origin.
  3820. :param use_thread: Control if to use threaded operation. Boolean.
  3821. :return:
  3822. """
  3823. def worker_task():
  3824. with self.proc_container.new(_("Moving to Origin...")):
  3825. obj_list = self.collection.get_selected()
  3826. if not obj_list:
  3827. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3828. return
  3829. xminlist = []
  3830. yminlist = []
  3831. # first get a bounding box to fit all
  3832. for obj in obj_list:
  3833. xmin, ymin, xmax, ymax = obj.bounds()
  3834. xminlist.append(xmin)
  3835. yminlist.append(ymin)
  3836. # get the minimum x,y for all objects selected
  3837. x = min(xminlist)
  3838. y = min(yminlist)
  3839. for obj in obj_list:
  3840. obj.offset((-x, -y))
  3841. self.app_obj.object_changed.emit(obj)
  3842. # Update the object bounding box options
  3843. a, b, c, d = obj.bounds()
  3844. obj.options['xmin'] = a
  3845. obj.options['ymin'] = b
  3846. obj.options['xmax'] = c
  3847. obj.options['ymax'] = d
  3848. for obj in obj_list:
  3849. obj.plot()
  3850. for obj in obj_list:
  3851. out_name = obj.options["name"]
  3852. if obj.kind == 'gerber':
  3853. obj.source_file = self.export_gerber(
  3854. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3855. elif obj.kind == 'excellon':
  3856. obj.source_file = self.export_excellon(
  3857. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3858. self.inform.emit('[success] %s...' % _('Origin set'))
  3859. if use_thread is True:
  3860. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3861. else:
  3862. worker_task()
  3863. self.should_we_save = True
  3864. def on_jump_to(self, custom_location=None, fit_center=True):
  3865. """
  3866. Jump to a location by setting the mouse cursor location.
  3867. :param custom_location: Jump to a specified point. (x, y) tuple.
  3868. :param fit_center: If to fit view. Boolean.
  3869. :return:
  3870. """
  3871. self.defaults.report_usage("on_jump_to()")
  3872. if not custom_location:
  3873. dia_box_location = None
  3874. try:
  3875. dia_box_location = eval(self.clipboard.text())
  3876. except Exception:
  3877. pass
  3878. if type(dia_box_location) == tuple:
  3879. dia_box_location = str(dia_box_location)
  3880. else:
  3881. dia_box_location = None
  3882. # dia_box = Dialog_box(title=_("Jump to ..."),
  3883. # label=_("Enter the coordinates in format X,Y:"),
  3884. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3885. # initial_text=dia_box_location)
  3886. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3887. label=_("Enter the coordinates in format X,Y:"),
  3888. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3889. initial_text=dia_box_location,
  3890. reference=self.defaults['global_jump_ref'])
  3891. if dia_box.ok is True:
  3892. try:
  3893. location = eval(dia_box.location)
  3894. if not isinstance(location, tuple):
  3895. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3896. return
  3897. if dia_box.reference == 'rel':
  3898. rel_x = self.mouse[0] + location[0]
  3899. rel_y = self.mouse[1] + location[1]
  3900. location = (rel_x, rel_y)
  3901. self.defaults['global_jump_ref'] = dia_box.reference
  3902. except Exception:
  3903. return
  3904. else:
  3905. return
  3906. else:
  3907. location = custom_location
  3908. self.jump_signal.emit(location)
  3909. if fit_center:
  3910. self.plotcanvas.fit_center(loc=location)
  3911. cursor = QtGui.QCursor()
  3912. if self.is_legacy is False:
  3913. # I don't know where those differences come from but they are constant for the current
  3914. # execution of the application and they are multiples of a value around 0.0263mm.
  3915. # In a random way sometimes they are more sometimes they are less
  3916. # if units == 'MM':
  3917. # cal_factor = 0.0263
  3918. # else:
  3919. # cal_factor = 0.0263 / 25.4
  3920. cal_location = (location[0], location[1])
  3921. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3922. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3923. j_pos = (
  3924. int(canvas_origin.x() + round(jump_loc[0])),
  3925. int(canvas_origin.y() + round(jump_loc[1]))
  3926. )
  3927. cursor.setPos(j_pos[0], j_pos[1])
  3928. else:
  3929. # find the canvas origin which is in the top left corner
  3930. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3931. # determine the coordinates for the lowest left point of the canvas
  3932. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3933. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3934. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3935. # canvas) and the point (width, height) is in the top-right location
  3936. loc = self.plotcanvas.axes.transData.transform_point(location)
  3937. j_pos = (
  3938. int(x0 + loc[0]),
  3939. int(y0 - loc[1])
  3940. )
  3941. cursor.setPos(j_pos[0], j_pos[1])
  3942. self.plotcanvas.mouse = [location[0], location[1]]
  3943. if self.defaults["global_cursor_color_enabled"] is True:
  3944. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3945. else:
  3946. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3947. if self.grid_status():
  3948. # Update cursor
  3949. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3950. symbol='++', edge_color=self.cursor_color_3D,
  3951. edge_width=self.defaults["global_cursor_width"],
  3952. size=self.defaults["global_cursor_size"])
  3953. # Set the relative position label
  3954. dx = location[0] - float(self.rel_point1[0])
  3955. dy = location[1] - float(self.rel_point1[1])
  3956. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3957. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3958. # Set the position label
  3959. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3960. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3961. units = self.defaults["units"].lower()
  3962. self.plotcanvas.text_hud.text = \
  3963. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3964. dx, units, dy, units, location[0], units, location[1], units)
  3965. self.inform.emit('[success] %s' % _("Done."))
  3966. return location
  3967. def on_locate(self, obj, fit_center=True):
  3968. """
  3969. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3970. :param obj: The object on which to locate certain points
  3971. :param fit_center: If to fit view. Boolean.
  3972. :return: A point location. (x, y) tuple.
  3973. """
  3974. self.defaults.report_usage("on_locate()")
  3975. if obj is None:
  3976. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3977. return 'fail'
  3978. class DialogBoxChoice(QtWidgets.QDialog):
  3979. def __init__(self, title=None, icon=None, choice='bl'):
  3980. """
  3981. :param title: string with the window title
  3982. """
  3983. super(DialogBoxChoice, self).__init__()
  3984. self.ok = False
  3985. self.setWindowIcon(icon)
  3986. self.setWindowTitle(str(title))
  3987. self.form = QtWidgets.QFormLayout(self)
  3988. self.ref_radio = RadioSet([
  3989. {"label": _("Bottom-Left"), "value": "bl"},
  3990. {"label": _("Top-Left"), "value": "tl"},
  3991. {"label": _("Bottom-Right"), "value": "br"},
  3992. {"label": _("Top-Right"), "value": "tr"},
  3993. {"label": _("Center"), "value": "c"}
  3994. ], orientation='vertical', stretch=False)
  3995. self.ref_radio.set_value(choice)
  3996. self.form.addRow(self.ref_radio)
  3997. self.button_box = QtWidgets.QDialogButtonBox(
  3998. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3999. Qt.Horizontal, parent=self)
  4000. self.form.addRow(self.button_box)
  4001. self.button_box.accepted.connect(self.accept)
  4002. self.button_box.rejected.connect(self.reject)
  4003. if self.exec_() == QtWidgets.QDialog.Accepted:
  4004. self.ok = True
  4005. self.location_point = self.ref_radio.get_value()
  4006. else:
  4007. self.ok = False
  4008. self.location_point = None
  4009. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4010. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4011. choice=self.defaults['global_locate_pt'])
  4012. if dia_box.ok is True:
  4013. try:
  4014. location_point = dia_box.location_point
  4015. self.defaults['global_locate_pt'] = dia_box.location_point
  4016. except Exception:
  4017. return
  4018. else:
  4019. return
  4020. loc_b = obj.bounds()
  4021. if location_point == 'bl':
  4022. location = (loc_b[0], loc_b[1])
  4023. elif location_point == 'tl':
  4024. location = (loc_b[0], loc_b[3])
  4025. elif location_point == 'br':
  4026. location = (loc_b[2], loc_b[1])
  4027. elif location_point == 'tr':
  4028. location = (loc_b[2], loc_b[3])
  4029. else:
  4030. # center
  4031. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4032. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4033. location = (cx, cy)
  4034. self.locate_signal.emit(location, location_point)
  4035. if fit_center:
  4036. self.plotcanvas.fit_center(loc=location)
  4037. cursor = QtGui.QCursor()
  4038. if self.is_legacy is False:
  4039. # I don't know where those differences come from but they are constant for the current
  4040. # execution of the application and they are multiples of a value around 0.0263mm.
  4041. # In a random way sometimes they are more sometimes they are less
  4042. # if units == 'MM':
  4043. # cal_factor = 0.0263
  4044. # else:
  4045. # cal_factor = 0.0263 / 25.4
  4046. cal_location = (location[0], location[1])
  4047. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4048. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4049. j_pos = (
  4050. int(canvas_origin.x() + round(jump_loc[0])),
  4051. int(canvas_origin.y() + round(jump_loc[1]))
  4052. )
  4053. cursor.setPos(j_pos[0], j_pos[1])
  4054. else:
  4055. # find the canvas origin which is in the top left corner
  4056. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4057. # determine the coordinates for the lowest left point of the canvas
  4058. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4059. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4060. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4061. # canvas) and the point (width, height) is in the top-right location
  4062. loc = self.plotcanvas.axes.transData.transform_point(location)
  4063. j_pos = (
  4064. int(x0 + loc[0]),
  4065. int(y0 - loc[1])
  4066. )
  4067. cursor.setPos(j_pos[0], j_pos[1])
  4068. self.plotcanvas.mouse = [location[0], location[1]]
  4069. if self.defaults["global_cursor_color_enabled"] is True:
  4070. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4071. else:
  4072. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4073. if self.grid_status():
  4074. # Update cursor
  4075. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4076. symbol='++', edge_color=self.cursor_color_3D,
  4077. edge_width=self.defaults["global_cursor_width"],
  4078. size=self.defaults["global_cursor_size"])
  4079. # Set the relative position label
  4080. self.dx = location[0] - float(self.rel_point1[0])
  4081. self.dy = location[1] - float(self.rel_point1[1])
  4082. # Set the position label
  4083. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4084. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4085. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4086. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4087. units = self.defaults["units"].lower()
  4088. self.plotcanvas.text_hud.text = \
  4089. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4090. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4091. self.inform.emit('[success] %s' % _("Done."))
  4092. return location
  4093. def on_copy_command(self):
  4094. """
  4095. Will copy a selection of objects, creating new objects.
  4096. :return:
  4097. """
  4098. self.defaults.report_usage("on_copy_command()")
  4099. def initialize(obj_init, app):
  4100. """
  4101. :param obj_init: the new object
  4102. :type obj_init: class
  4103. :param app: An instance of the App class
  4104. :type app: App
  4105. :return: None
  4106. :rtype:
  4107. """
  4108. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4109. try:
  4110. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4111. except AttributeError:
  4112. pass
  4113. try:
  4114. obj_init.apertures = deepcopy(obj.apertures)
  4115. except AttributeError:
  4116. pass
  4117. try:
  4118. if obj.tools:
  4119. obj_init.tools = deepcopy(obj.tools)
  4120. except Exception as err:
  4121. log.debug("App.on_copy_command() --> %s" % str(err))
  4122. try:
  4123. obj_init.source_file = deepcopy(obj.source_file)
  4124. except (AttributeError, TypeError):
  4125. pass
  4126. def initialize_excellon(obj_init, app):
  4127. obj_init.source_file = deepcopy(obj.source_file)
  4128. obj_init.tools = deepcopy(obj.tools)
  4129. # drills are offset, so they need to be deep copied
  4130. obj_init.drills = deepcopy(obj.drills)
  4131. # slots are offset, so they need to be deep copied
  4132. obj_init.slots = deepcopy(obj.slots)
  4133. obj_init.create_geometry()
  4134. def initialize_script(obj_init, app_obj):
  4135. obj_init.source_file = deepcopy(obj.source_file)
  4136. def initialize_document(obj_init, app_obj):
  4137. obj_init.source_file = deepcopy(obj.source_file)
  4138. for obj in self.collection.get_selected():
  4139. obj_name = obj.options["name"]
  4140. try:
  4141. if isinstance(obj, ExcellonObject):
  4142. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4143. elif isinstance(obj, GerberObject):
  4144. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4145. elif isinstance(obj, GeometryObject):
  4146. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4147. elif isinstance(obj, ScriptObject):
  4148. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4149. elif isinstance(obj, DocumentObject):
  4150. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4151. except Exception as e:
  4152. return "Operation failed: %s" % str(e)
  4153. def on_copy_object2(self, custom_name):
  4154. def initialize_geometry(obj_init, app):
  4155. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4156. try:
  4157. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4158. except AttributeError:
  4159. pass
  4160. try:
  4161. obj_init.apertures = deepcopy(obj.apertures)
  4162. except AttributeError:
  4163. pass
  4164. try:
  4165. if obj.tools:
  4166. obj_init.tools = deepcopy(obj.tools)
  4167. except Exception as ee:
  4168. log.debug("on_copy_object2() --> %s" % str(ee))
  4169. def initialize_gerber(obj_init, app):
  4170. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4171. obj_init.apertures = deepcopy(obj.apertures)
  4172. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4173. def initialize_excellon(obj_init, app):
  4174. obj_init.tools = deepcopy(obj.tools)
  4175. # drills are offset, so they need to be deep copied
  4176. obj_init.drills = deepcopy(obj.drills)
  4177. # slots are offset, so they need to be deep copied
  4178. obj_init.slots = deepcopy(obj.slots)
  4179. obj_init.create_geometry()
  4180. for obj in self.collection.get_selected():
  4181. obj_name = obj.options["name"]
  4182. try:
  4183. if isinstance(obj, ExcellonObject):
  4184. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4185. elif isinstance(obj, GerberObject):
  4186. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4187. elif isinstance(obj, GeometryObject):
  4188. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4189. except Exception as er:
  4190. return "Operation failed: %s" % str(er)
  4191. def on_rename_object(self, text):
  4192. """
  4193. Will rename an object.
  4194. :param text: New name for the object.
  4195. :return:
  4196. """
  4197. self.defaults.report_usage("on_rename_object()")
  4198. named_obj = self.collection.get_active()
  4199. for obj in named_obj:
  4200. if obj is list:
  4201. self.on_rename_object(text)
  4202. else:
  4203. try:
  4204. obj.options['name'] = text
  4205. except Exception as e:
  4206. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4207. def convert_any2geo(self):
  4208. """
  4209. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4210. :return:
  4211. """
  4212. self.defaults.report_usage("convert_any2geo()")
  4213. def initialize(obj_init, app):
  4214. obj_init.solid_geometry = obj.solid_geometry
  4215. try:
  4216. obj_init.follow_geometry = obj.follow_geometry
  4217. except AttributeError:
  4218. pass
  4219. try:
  4220. obj_init.apertures = obj.apertures
  4221. except AttributeError:
  4222. pass
  4223. try:
  4224. if obj.tools:
  4225. obj_init.tools = obj.tools
  4226. except AttributeError:
  4227. pass
  4228. def initialize_excellon(obj_init, app):
  4229. # objs = self.collection.get_selected()
  4230. # GeometryObject.merge(objs, obj)
  4231. solid_geo = []
  4232. for tool in obj.tools:
  4233. for geo in obj.tools[tool]['solid_geometry']:
  4234. solid_geo.append(geo)
  4235. obj_init.solid_geometry = deepcopy(solid_geo)
  4236. if not self.collection.get_selected():
  4237. log.warning("App.convert_any2geo --> No object selected")
  4238. self.inform.emit('[WARNING_NOTCL] %s' %
  4239. _("No object is selected. Select an object and try again."))
  4240. return
  4241. for obj in self.collection.get_selected():
  4242. obj_name = obj.options["name"]
  4243. try:
  4244. if obj.kind == 'excellon':
  4245. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4246. else:
  4247. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4248. except Exception as e:
  4249. return "Operation failed: %s" % str(e)
  4250. def convert_any2gerber(self):
  4251. """
  4252. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4253. :return:
  4254. """
  4255. def initialize_geometry(obj_init, app):
  4256. apertures = {}
  4257. apid = 0
  4258. apertures[str(apid)] = {}
  4259. apertures[str(apid)]['geometry'] = []
  4260. for obj_orig in obj.solid_geometry:
  4261. new_elem = {}
  4262. new_elem['solid'] = obj_orig
  4263. try:
  4264. new_elem['follow'] = obj_orig.exterior
  4265. except AttributeError:
  4266. pass
  4267. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4268. apertures[str(apid)]['size'] = 0.0
  4269. apertures[str(apid)]['type'] = 'C'
  4270. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4271. obj_init.apertures = deepcopy(apertures)
  4272. def initialize_excellon(obj_init, app):
  4273. apertures = {}
  4274. apid = 10
  4275. for tool in obj.tools:
  4276. apertures[str(apid)] = {}
  4277. apertures[str(apid)]['geometry'] = []
  4278. for geo in obj.tools[tool]['solid_geometry']:
  4279. new_el = {}
  4280. new_el['solid'] = geo
  4281. new_el['follow'] = geo.exterior
  4282. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4283. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4284. apertures[str(apid)]['type'] = 'C'
  4285. apid += 1
  4286. # create solid_geometry
  4287. solid_geometry = []
  4288. for apid in apertures:
  4289. for geo_el in apertures[apid]['geometry']:
  4290. solid_geometry.append(geo_el['solid'])
  4291. solid_geometry = MultiPolygon(solid_geometry)
  4292. solid_geometry = solid_geometry.buffer(0.0000001)
  4293. obj_init.solid_geometry = deepcopy(solid_geometry)
  4294. obj_init.apertures = deepcopy(apertures)
  4295. # clear the working objects (perhaps not necessary due of Python GC)
  4296. apertures.clear()
  4297. if not self.collection.get_selected():
  4298. log.warning("App.convert_any2gerber --> No object selected")
  4299. self.inform.emit('[WARNING_NOTCL] %s' %
  4300. _("No object is selected. Select an object and try again."))
  4301. return
  4302. for obj in self.collection.get_selected():
  4303. obj_name = obj.options["name"]
  4304. try:
  4305. if obj.kind == 'excellon':
  4306. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4307. elif obj.kind == 'geometry':
  4308. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4309. else:
  4310. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4311. except Exception as e:
  4312. return "Operation failed: %s" % str(e)
  4313. def convert_any2excellon(self):
  4314. """
  4315. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4316. :return:
  4317. """
  4318. def initialize_geometry(obj_init, app):
  4319. tools = {}
  4320. tooluid = 1
  4321. obj_init.solid_geometry = []
  4322. for geo in obj.solid_geometry:
  4323. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4324. continue
  4325. minx, miny, maxx, maxy = geo.bounds
  4326. new_dia = min([maxx-minx, maxy-miny])
  4327. new_drill = geo.centroid
  4328. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4329. current_tooldias = []
  4330. if tools:
  4331. for tool in tools:
  4332. if tools[tool] and 'tooldia' in tools[tool]:
  4333. current_tooldias.append(tools[tool]['tooldia'])
  4334. if new_dia in current_tooldias:
  4335. for tool in tools:
  4336. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float('%.*f' % (self.decimals,
  4337. new_dia)):
  4338. tools[tool]['drills'].append(new_drill)
  4339. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4340. else:
  4341. tools[tooluid] = {}
  4342. tools[tooluid]['tooldia'] = new_dia
  4343. tools[tooluid]['drills'] = [new_drill]
  4344. tools[tooluid]['slots'] = []
  4345. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4346. tooluid += 1
  4347. try:
  4348. obj_init.solid_geometry.append(new_drill_geo)
  4349. except (TypeError, AttributeError):
  4350. obj_init.solid_geometry = [new_drill_geo]
  4351. obj_init.tools = deepcopy(tools)
  4352. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4353. def initialize_gerber(obj_init, app):
  4354. tools = {}
  4355. tooluid = 1
  4356. obj_init.solid_geometry = []
  4357. for apid in obj.apertures:
  4358. if 'geometry' in obj.apertures[apid]:
  4359. for geo_dict in obj.apertures[apid]['geometry']:
  4360. if 'follow' in geo_dict:
  4361. if isinstance(geo_dict['follow'], Point):
  4362. geo = geo_dict['solid']
  4363. minx, miny, maxx, maxy = geo.bounds
  4364. new_dia = min([maxx - minx, maxy - miny])
  4365. new_drill = geo.centroid
  4366. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4367. current_tooldias = []
  4368. if tools:
  4369. for tool in tools:
  4370. if tools[tool] and 'tooldia' in tools[tool]:
  4371. current_tooldias.append(
  4372. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4373. )
  4374. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4375. for tool in tools:
  4376. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4377. '%.*f' % (self.decimals, new_dia)):
  4378. if new_drill not in tools[tool]['drills']:
  4379. tools[tool]['drills'].append(new_drill)
  4380. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4381. else:
  4382. tools[tooluid] = {}
  4383. tools[tooluid]['tooldia'] = new_dia
  4384. tools[tooluid]['drills'] = [new_drill]
  4385. tools[tooluid]['slots'] = []
  4386. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4387. tooluid += 1
  4388. try:
  4389. obj_init.solid_geometry.append(new_drill_geo)
  4390. except (TypeError, AttributeError):
  4391. obj_init.solid_geometry = [new_drill_geo]
  4392. elif isinstance(geo_dict['follow'], LineString):
  4393. geo_coords = list(geo_dict['follow'].coords)
  4394. # slots can have only a start and stop point and no intermediate points
  4395. if len(geo_coords) != 2:
  4396. continue
  4397. geo = geo_dict['solid']
  4398. try:
  4399. new_dia = obj.apertures[apid]['size']
  4400. except Exception:
  4401. continue
  4402. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4403. new_slot_geo = geo
  4404. current_tooldias = []
  4405. if tools:
  4406. for tool in tools:
  4407. if tools[tool] and 'tooldia' in tools[tool]:
  4408. current_tooldias.append(
  4409. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4410. )
  4411. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4412. for tool in tools:
  4413. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4414. '%.*f' % (self.decimals, new_dia)):
  4415. if new_slot not in tools[tool]['slots']:
  4416. tools[tool]['slots'].append(new_slot)
  4417. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4418. else:
  4419. tools[tooluid] = {}
  4420. tools[tooluid]['tooldia'] = new_dia
  4421. tools[tooluid]['drills'] = []
  4422. tools[tooluid]['slots'] = [new_slot]
  4423. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4424. tooluid += 1
  4425. try:
  4426. obj_init.solid_geometry.append(new_slot_geo)
  4427. except (TypeError, AttributeError):
  4428. obj_init.solid_geometry = [new_slot_geo]
  4429. obj_init.tools = deepcopy(tools)
  4430. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4431. if not self.collection.get_selected():
  4432. log.warning("App.convert_any2excellon--> No object selected")
  4433. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4434. return
  4435. for obj in self.collection.get_selected():
  4436. obj_name = obj.options["name"]
  4437. try:
  4438. if obj.kind == 'gerber':
  4439. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4440. elif obj.kind == 'geometry':
  4441. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4442. else:
  4443. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4444. except Exception as e:
  4445. return "Operation failed: %s" % str(e)
  4446. def abort_all_tasks(self):
  4447. """
  4448. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4449. on the first possible occasion.
  4450. :return:
  4451. """
  4452. if self.abort_flag is False:
  4453. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4454. self.abort_flag = True
  4455. self.cleanup.emit()
  4456. def app_is_idle(self):
  4457. if self.abort_flag:
  4458. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4459. self.abort_flag = False
  4460. def on_selectall(self):
  4461. """
  4462. Will draw a selection box shape around the selected objects.
  4463. :return:
  4464. """
  4465. self.defaults.report_usage("on_selectall()")
  4466. # delete the possible selection box around a possible selected object
  4467. self.delete_selection_shape()
  4468. for name in self.collection.get_names():
  4469. self.collection.set_active(name)
  4470. curr_sel_obj = self.collection.get_by_name(name)
  4471. # create the selection box around the selected object
  4472. if self.defaults['global_selection_shape'] is True:
  4473. self.draw_selection_shape(curr_sel_obj)
  4474. def on_toggle_preferences(self):
  4475. pref_open = False
  4476. for idx in range(self.ui.plot_tab_area.count()):
  4477. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4478. pref_open = True
  4479. if pref_open:
  4480. for idx in range(self.ui.plot_tab_area.count()):
  4481. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4482. self.ui.plot_tab_area.removeTab(idx)
  4483. break
  4484. self.ui.pref_status_label.setStyleSheet("")
  4485. else:
  4486. self.on_preferences()
  4487. def on_preferences(self):
  4488. """
  4489. Adds the Preferences in a Tab in Plot Area
  4490. :return:
  4491. """
  4492. # add the tab if it was closed
  4493. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4494. # delete the absolute and relative position and messages in the infobar
  4495. # self.ui.position_label.setText("")
  4496. # self.ui.rel_position_label.setText("")
  4497. # hide coordinates toolbars in the infobar while in DB
  4498. self.ui.coords_toolbar.hide()
  4499. self.ui.delta_coords_toolbar.hide()
  4500. # Switch plot_area to preferences page
  4501. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4502. # self.ui.show()
  4503. self.ui.pref_status_label.setStyleSheet("""
  4504. QLabel
  4505. {
  4506. color: black;
  4507. background-color: lightseagreen;
  4508. }
  4509. """
  4510. )
  4511. # detect changes in the preferences
  4512. for idx in range(self.ui.pref_tab_area.count()):
  4513. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4514. try:
  4515. try:
  4516. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4517. except (TypeError, AttributeError):
  4518. pass
  4519. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4520. except AttributeError:
  4521. pass
  4522. try:
  4523. try:
  4524. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4525. except (TypeError, AttributeError):
  4526. pass
  4527. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4528. except AttributeError:
  4529. pass
  4530. try:
  4531. try:
  4532. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4533. except (TypeError, AttributeError):
  4534. pass
  4535. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4536. except AttributeError:
  4537. pass
  4538. try:
  4539. try:
  4540. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4541. except (TypeError, AttributeError):
  4542. pass
  4543. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4544. except AttributeError:
  4545. pass
  4546. try:
  4547. try:
  4548. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4549. except (TypeError, AttributeError):
  4550. pass
  4551. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4552. except AttributeError:
  4553. pass
  4554. def on_tools_database(self, source='app'):
  4555. """
  4556. Adds the Tools Database in a Tab in Plot Area.
  4557. :return:
  4558. """
  4559. for idx in range(self.ui.plot_tab_area.count()):
  4560. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4561. # there can be only one instance of Tools Database at one time
  4562. return
  4563. if source == 'app':
  4564. self.tools_db_tab = ToolsDB2(
  4565. app=self,
  4566. parent=self.ui,
  4567. callback_on_edited=self.on_tools_db_edited,
  4568. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4569. )
  4570. elif source == 'ncc':
  4571. self.tools_db_tab = ToolsDB2(
  4572. app=self,
  4573. parent=self.ui,
  4574. callback_on_edited=self.on_tools_db_edited,
  4575. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4576. )
  4577. elif source == 'paint':
  4578. self.tools_db_tab = ToolsDB2(
  4579. app=self,
  4580. parent=self.ui,
  4581. callback_on_edited=self.on_tools_db_edited,
  4582. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4583. )
  4584. elif source == 'iso':
  4585. self.tools_db_tab = ToolsDB2(
  4586. app=self,
  4587. parent=self.ui,
  4588. callback_on_edited=self.on_tools_db_edited,
  4589. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4590. )
  4591. # add the tab if it was closed
  4592. try:
  4593. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4594. self.tools_db_tab.setObjectName("database_tab")
  4595. except Exception as e:
  4596. log.debug("App.on_tools_database() --> %s" % str(e))
  4597. return
  4598. # delete the absolute and relative position and messages in the infobar
  4599. # self.ui.position_label.setText("")
  4600. # self.ui.rel_position_label.setText("")
  4601. # hide coordinates toolbars in the infobar while in DB
  4602. self.ui.coords_toolbar.hide()
  4603. self.ui.delta_coords_toolbar.hide()
  4604. # Switch plot_area to preferences page
  4605. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4606. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4607. self.tools_db_tab.ui_connect()
  4608. def on_tools_db_edited(self):
  4609. """
  4610. Executed whenever a tool is edited in Tools Database.
  4611. Will color the text of the Tools Database tab to Red color.
  4612. :return:
  4613. """
  4614. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4615. for idx in range(self.ui.plot_tab_area.count()):
  4616. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4617. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4618. self.tools_db_tab.ui.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4619. self.tools_db_changed_flag = True
  4620. def on_geometry_tool_add_from_db_executed(self, tool):
  4621. """
  4622. Here add the tool from DB in the selected geometry object.
  4623. :return:
  4624. """
  4625. tool_from_db = deepcopy(tool)
  4626. obj = self.collection.get_active()
  4627. if obj.kind == 'geometry':
  4628. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4629. # close the tab and delete it
  4630. for idx in range(self.ui.plot_tab_area.count()):
  4631. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4632. wdg = self.ui.plot_tab_area.widget(idx)
  4633. wdg.deleteLater()
  4634. self.ui.plot_tab_area.removeTab(idx)
  4635. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4636. elif obj.kind == 'gerber':
  4637. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4638. # close the tab and delete it
  4639. for idx in range(self.ui.plot_tab_area.count()):
  4640. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4641. wdg = self.ui.plot_tab_area.widget(idx)
  4642. wdg.deleteLater()
  4643. self.ui.plot_tab_area.removeTab(idx)
  4644. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4645. else:
  4646. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4647. def on_plot_area_tab_closed(self, tab_obj_name):
  4648. """
  4649. Executed whenever a QTab is closed in the Plot Area.
  4650. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4651. :return:
  4652. """
  4653. if tab_obj_name == "preferences_tab":
  4654. self.preferencesUiManager.on_close_preferences_tab()
  4655. elif tab_obj_name == "database_tab":
  4656. # disconnect the signals from the table widget in tab
  4657. self.tools_db_tab.ui_disconnect()
  4658. if self.tools_db_changed_flag is True:
  4659. msgbox = QtWidgets.QMessageBox()
  4660. msgbox.setText(_("One or more Tools are edited.\n"
  4661. "Do you want to update the Tools Database?"))
  4662. msgbox.setWindowTitle(_("Save Tools Database"))
  4663. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4664. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4665. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4666. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4667. msgbox.setDefaultButton(bt_yes)
  4668. msgbox.exec_()
  4669. response = msgbox.clickedButton()
  4670. if response == bt_yes:
  4671. self.tools_db_tab.on_save_tools_db()
  4672. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4673. else:
  4674. self.tools_db_changed_flag = False
  4675. self.inform.emit('')
  4676. return
  4677. self.tools_db_tab.deleteLater()
  4678. elif tab_obj_name == "text_editor_tab":
  4679. self.toggle_codeeditor = False
  4680. elif tab_obj_name == "bookmarks_tab":
  4681. self.book_dialog_tab.rebuild_actions()
  4682. self.book_dialog_tab.deleteLater()
  4683. else:
  4684. pass
  4685. # restore the coords toolbars
  4686. self.ui.toggle_coords(checked=self.defaults["global_coords_show"])
  4687. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coords_show"])
  4688. def on_flipy(self):
  4689. """
  4690. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4691. :return:
  4692. """
  4693. self.defaults.report_usage("on_flipy()")
  4694. obj_list = self.collection.get_selected()
  4695. xminlist = []
  4696. yminlist = []
  4697. xmaxlist = []
  4698. ymaxlist = []
  4699. if not obj_list:
  4700. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4701. else:
  4702. try:
  4703. # first get a bounding box to fit all
  4704. for obj in obj_list:
  4705. xmin, ymin, xmax, ymax = obj.bounds()
  4706. xminlist.append(xmin)
  4707. yminlist.append(ymin)
  4708. xmaxlist.append(xmax)
  4709. ymaxlist.append(ymax)
  4710. # get the minimum x,y and maximum x,y for all objects selected
  4711. xminimal = min(xminlist)
  4712. yminimal = min(yminlist)
  4713. xmaximal = max(xmaxlist)
  4714. ymaximal = max(ymaxlist)
  4715. px = 0.5 * (xminimal + xmaximal)
  4716. py = 0.5 * (yminimal + ymaximal)
  4717. # execute mirroring
  4718. for obj in obj_list:
  4719. obj.mirror('X', [px, py])
  4720. obj.plot()
  4721. self.app_obj.object_changed.emit(obj)
  4722. self.inform.emit('[success] %s' %
  4723. _("Flip on Y axis done."))
  4724. except Exception as e:
  4725. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4726. return
  4727. def on_flipx(self):
  4728. """
  4729. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4730. :return:
  4731. """
  4732. self.defaults.report_usage("on_flipx()")
  4733. obj_list = self.collection.get_selected()
  4734. xminlist = []
  4735. yminlist = []
  4736. xmaxlist = []
  4737. ymaxlist = []
  4738. if not obj_list:
  4739. self.inform.emit('[WARNING_NOTCL] %s' %
  4740. _("No object selected to Flip on X axis."))
  4741. else:
  4742. try:
  4743. # first get a bounding box to fit all
  4744. for obj in obj_list:
  4745. xmin, ymin, xmax, ymax = obj.bounds()
  4746. xminlist.append(xmin)
  4747. yminlist.append(ymin)
  4748. xmaxlist.append(xmax)
  4749. ymaxlist.append(ymax)
  4750. # get the minimum x,y and maximum x,y for all objects selected
  4751. xminimal = min(xminlist)
  4752. yminimal = min(yminlist)
  4753. xmaximal = max(xmaxlist)
  4754. ymaximal = max(ymaxlist)
  4755. px = 0.5 * (xminimal + xmaximal)
  4756. py = 0.5 * (yminimal + ymaximal)
  4757. # execute mirroring
  4758. for obj in obj_list:
  4759. obj.mirror('Y', [px, py])
  4760. obj.plot()
  4761. self.app_obj.object_changed.emit(obj)
  4762. self.inform.emit('[success] %s' %
  4763. _("Flip on X axis done."))
  4764. except Exception as e:
  4765. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4766. return
  4767. def on_rotate(self, silent=False, preset=None):
  4768. """
  4769. Executed when Options -> Rotate Selection menu entry is clicked.
  4770. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4771. :param preset: A value to be used as predefined angle for rotation.
  4772. :return:
  4773. """
  4774. self.defaults.report_usage("on_rotate()")
  4775. obj_list = self.collection.get_selected()
  4776. xminlist = []
  4777. yminlist = []
  4778. xmaxlist = []
  4779. ymaxlist = []
  4780. if not obj_list:
  4781. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4782. else:
  4783. if silent is False:
  4784. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4785. min=-360, max=360, decimals=4,
  4786. init_val=float(self.defaults['tools_transform_rotate']))
  4787. num, ok = rotatebox.get_value()
  4788. else:
  4789. num = preset
  4790. ok = True
  4791. if ok:
  4792. try:
  4793. # first get a bounding box to fit all
  4794. for obj in obj_list:
  4795. xmin, ymin, xmax, ymax = obj.bounds()
  4796. xminlist.append(xmin)
  4797. yminlist.append(ymin)
  4798. xmaxlist.append(xmax)
  4799. ymaxlist.append(ymax)
  4800. # get the minimum x,y and maximum x,y for all objects selected
  4801. xminimal = min(xminlist)
  4802. yminimal = min(yminlist)
  4803. xmaximal = max(xmaxlist)
  4804. ymaximal = max(ymaxlist)
  4805. px = 0.5 * (xminimal + xmaximal)
  4806. py = 0.5 * (yminimal + ymaximal)
  4807. for sel_obj in obj_list:
  4808. sel_obj.rotate(-float(num), point=(px, py))
  4809. sel_obj.plot()
  4810. self.app_obj.object_changed.emit(sel_obj)
  4811. self.inform.emit('[success] %s' % _("Rotation done."))
  4812. except Exception as e:
  4813. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4814. return
  4815. def on_skewx(self):
  4816. """
  4817. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4818. :return:
  4819. """
  4820. self.defaults.report_usage("on_skewx()")
  4821. obj_list = self.collection.get_selected()
  4822. xminlist = []
  4823. yminlist = []
  4824. if not obj_list:
  4825. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4826. else:
  4827. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4828. min=-360, max=360, decimals=4,
  4829. init_val=float(self.defaults['tools_transform_skew_x']))
  4830. num, ok = skewxbox.get_value()
  4831. if ok:
  4832. # first get a bounding box to fit all
  4833. for obj in obj_list:
  4834. xmin, ymin, xmax, ymax = obj.bounds()
  4835. xminlist.append(xmin)
  4836. yminlist.append(ymin)
  4837. # get the minimum x,y and maximum x,y for all objects selected
  4838. xminimal = min(xminlist)
  4839. yminimal = min(yminlist)
  4840. for obj in obj_list:
  4841. obj.skew(num, 0, point=(xminimal, yminimal))
  4842. obj.plot()
  4843. self.app_obj.object_changed.emit(obj)
  4844. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4845. def on_skewy(self):
  4846. """
  4847. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4848. :return:
  4849. """
  4850. self.defaults.report_usage("on_skewy()")
  4851. obj_list = self.collection.get_selected()
  4852. xminlist = []
  4853. yminlist = []
  4854. if not obj_list:
  4855. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4856. else:
  4857. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4858. min=-360, max=360, decimals=4,
  4859. init_val=float(self.defaults['tools_transform_skew_y']))
  4860. num, ok = skewybox.get_value()
  4861. if ok:
  4862. # first get a bounding box to fit all
  4863. for obj in obj_list:
  4864. xmin, ymin, xmax, ymax = obj.bounds()
  4865. xminlist.append(xmin)
  4866. yminlist.append(ymin)
  4867. # get the minimum x,y and maximum x,y for all objects selected
  4868. xminimal = min(xminlist)
  4869. yminimal = min(yminlist)
  4870. for obj in obj_list:
  4871. obj.skew(0, num, point=(xminimal, yminimal))
  4872. obj.plot()
  4873. self.app_obj.object_changed.emit(obj)
  4874. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4875. def on_plots_updated(self):
  4876. """
  4877. Callback used to report when the plots have changed.
  4878. Adjust axes and zooms to fit.
  4879. :return: None
  4880. """
  4881. if self.is_legacy is False:
  4882. self.plotcanvas.update()
  4883. else:
  4884. self.plotcanvas.auto_adjust_axes()
  4885. self.on_zoom_fit()
  4886. self.collection.update_view()
  4887. # self.inform.emit(_("Plots updated ..."))
  4888. def on_toolbar_replot(self):
  4889. """
  4890. Callback for toolbar button. Re-plots all objects.
  4891. :return: None
  4892. """
  4893. self.log.debug("on_toolbar_replot()")
  4894. try:
  4895. obj = self.collection.get_active()
  4896. if obj:
  4897. obj.read_form()
  4898. else:
  4899. self.on_zoom_fit()
  4900. except AttributeError as e:
  4901. log.debug("on_toolbar_replot() -> %s" % str(e))
  4902. pass
  4903. self.plot_all()
  4904. def grid_status(self):
  4905. return True if self.ui.grid_snap_btn.isChecked() else False
  4906. def populate_cmenu_grids(self):
  4907. units = self.defaults['units'].lower()
  4908. # for act in self.ui.cmenu_gridmenu.actions():
  4909. # act.triggered.disconnect()
  4910. self.ui.cmenu_gridmenu.clear()
  4911. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4912. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4913. _("Grid On/Off"))
  4914. grid_toggle.setCheckable(True)
  4915. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4916. self.ui.cmenu_gridmenu.addSeparator()
  4917. for grid in sorted_list:
  4918. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4919. "%s" % str(grid))
  4920. action.triggered.connect(self.set_grid)
  4921. self.ui.cmenu_gridmenu.addSeparator()
  4922. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4923. _("Add"))
  4924. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4925. _("Delete"))
  4926. grid_add.triggered.connect(self.on_grid_add)
  4927. grid_delete.triggered.connect(self.on_grid_delete)
  4928. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4929. def set_grid(self):
  4930. menu_action = self.sender()
  4931. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4932. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4933. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4934. def on_grid_add(self):
  4935. # ## Current application units in lower Case
  4936. units = self.defaults['units'].lower()
  4937. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4938. text=_('Enter a Grid Value:'),
  4939. min=0.0000, max=99.9999, decimals=4)
  4940. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4941. val, ok = grid_add_popup.get_value()
  4942. if ok:
  4943. if float(val) == 0:
  4944. self.inform.emit('[WARNING_NOTCL] %s' %
  4945. _("Please enter a grid value with non-zero value, in Float format."))
  4946. return
  4947. else:
  4948. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4949. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4950. self.inform.emit('[success] %s...' % _("New Grid added"))
  4951. else:
  4952. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4953. else:
  4954. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4955. def on_grid_delete(self):
  4956. # ## Current application units in lower Case
  4957. units = self.defaults['units'].lower()
  4958. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4959. text='Enter a Grid Value:',
  4960. min=0.0000, max=99.9999, decimals=4)
  4961. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4962. val, ok = grid_del_popup.get_value()
  4963. if ok:
  4964. if float(val) == 0:
  4965. self.inform.emit('[WARNING_NOTCL] %s' %
  4966. _("Please enter a grid value with non-zero value, in Float format."))
  4967. return
  4968. else:
  4969. try:
  4970. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4971. except ValueError:
  4972. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4973. return
  4974. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4975. else:
  4976. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4977. def on_shortcut_list(self):
  4978. self.defaults.report_usage("on_shortcut_list()")
  4979. # add the tab if it was closed
  4980. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4981. # delete the absolute and relative position and messages in the infobar
  4982. # self.ui.position_label.setText("")
  4983. # self.ui.rel_position_label.setText("")
  4984. # hide coordinates toolbars in the infobar while in DB
  4985. self.ui.coords_toolbar.hide()
  4986. self.ui.delta_coords_toolbar.hide()
  4987. # Switch plot_area to preferences page
  4988. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4989. # self.ui.show()
  4990. def on_select_tab(self, name):
  4991. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4992. if self.ui.splitter.sizes()[0] == 0:
  4993. self.ui.splitter.setSizes([1, 1])
  4994. else:
  4995. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4996. self.ui.splitter.setSizes([0, 1])
  4997. if name == 'project':
  4998. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4999. elif name == 'selected':
  5000. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5001. elif name == 'tool':
  5002. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5003. def on_copy_name(self):
  5004. self.defaults.report_usage("on_copy_name()")
  5005. obj = self.collection.get_active()
  5006. try:
  5007. name = obj.options["name"]
  5008. except AttributeError:
  5009. log.debug("on_copy_name() --> No object selected to copy it's name")
  5010. self.inform.emit('[WARNING_NOTCL] %s' %
  5011. _(" No object selected to copy it's name"))
  5012. return
  5013. self.clipboard.setText(name)
  5014. self.inform.emit(_("Name copied on clipboard ..."))
  5015. def on_mouse_click_over_plot(self, event):
  5016. """
  5017. Default actions are:
  5018. :param event: Contains information about the event, like which button
  5019. was clicked, the pixel coordinates and the axes coordinates.
  5020. :return: None
  5021. """
  5022. self.pos = []
  5023. if self.is_legacy is False:
  5024. event_pos = event.pos
  5025. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5026. # # Set the mouse button for panning
  5027. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5028. else:
  5029. event_pos = (event.xdata, event.ydata)
  5030. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5031. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5032. # So it can receive key presses
  5033. self.plotcanvas.native.setFocus()
  5034. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5035. if self.grid_status():
  5036. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5037. else:
  5038. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5039. try:
  5040. if event.button == 1:
  5041. # Reset here the relative coordinates so there is a new reference on the click position
  5042. if self.rel_point1 is None:
  5043. self.rel_point1 = self.pos
  5044. else:
  5045. self.rel_point2 = copy(self.rel_point1)
  5046. self.rel_point1 = self.pos
  5047. self.on_mouse_move_over_plot(event, origin_click=True)
  5048. except Exception as e:
  5049. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5050. def on_mouse_double_click_over_plot(self, event):
  5051. if event.button == 1:
  5052. self.doubleclick = True
  5053. def on_mouse_move_over_plot(self, event, origin_click=None):
  5054. """
  5055. Callback for the mouse motion event over the plot.
  5056. :param event: Contains information about the event.
  5057. :param origin_click
  5058. :return: None
  5059. """
  5060. if self.is_legacy is False:
  5061. event_pos = event.pos
  5062. if self.defaults["global_pan_button"] == '2':
  5063. pan_button = 2
  5064. else:
  5065. pan_button = 3
  5066. self.event_is_dragging = event.is_dragging
  5067. else:
  5068. event_pos = (event.xdata, event.ydata)
  5069. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5070. if self.defaults["global_pan_button"] == '2':
  5071. pan_button = 3
  5072. else:
  5073. pan_button = 2
  5074. self.event_is_dragging = self.plotcanvas.is_dragging
  5075. # So it can receive key presses but not when the Tcl Shell is active
  5076. if not self.ui.shell_dock.isVisible():
  5077. if not self.plotcanvas.native.hasFocus():
  5078. self.plotcanvas.native.setFocus()
  5079. self.pos_jump = event_pos
  5080. self.ui.popMenu.mouse_is_panning = False
  5081. if origin_click is None:
  5082. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5083. if event.button == pan_button and self.event_is_dragging == 1:
  5084. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5085. if self.ui.popMenu.popup_active:
  5086. self.ui.popMenu.popup_active = False
  5087. return
  5088. self.ui.popMenu.mouse_is_panning = True
  5089. return
  5090. if self.rel_point1 is not None:
  5091. try: # May fail in case mouse not within axes
  5092. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5093. if pos_canvas[0] is None or pos_canvas[1] is None:
  5094. return
  5095. if self.grid_status():
  5096. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5097. # Update cursor
  5098. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5099. symbol='++', edge_color=self.cursor_color_3D,
  5100. edge_width=self.defaults["global_cursor_width"],
  5101. size=self.defaults["global_cursor_size"])
  5102. else:
  5103. pos = (pos_canvas[0], pos_canvas[1])
  5104. self.dx = pos[0] - float(self.rel_point1[0])
  5105. self.dy = pos[1] - float(self.rel_point1[1])
  5106. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5107. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5108. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5109. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5110. units = self.defaults["units"].lower()
  5111. self.plotcanvas.text_hud.text = \
  5112. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5113. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5114. self.mouse = [pos[0], pos[1]]
  5115. if self.defaults['global_selection_shape'] is False:
  5116. self.selection_type = None
  5117. return
  5118. # if the mouse is moved and the LMB is clicked then the action is a selection
  5119. if self.event_is_dragging == 1 and event.button == 1:
  5120. self.delete_selection_shape()
  5121. if self.dx < 0:
  5122. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5123. face_color=self.defaults['global_alt_sel_fill'])
  5124. self.selection_type = False
  5125. elif self.dx >= 0:
  5126. self.draw_moving_selection_shape(self.pos, pos)
  5127. self.selection_type = True
  5128. else:
  5129. self.selection_type = None
  5130. else:
  5131. self.selection_type = None
  5132. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5133. if self.defaults['global_hover']:
  5134. for obj in self.collection.get_list():
  5135. try:
  5136. # select the object(s) only if it is enabled (plotted)
  5137. if obj.options['plot']:
  5138. if obj not in self.collection.get_selected():
  5139. poly_obj = Polygon(
  5140. [(obj.options['xmin'], obj.options['ymin']),
  5141. (obj.options['xmax'], obj.options['ymin']),
  5142. (obj.options['xmax'], obj.options['ymax']),
  5143. (obj.options['xmin'], obj.options['ymax'])]
  5144. )
  5145. if Point(pos).within(poly_obj):
  5146. if obj.isHovering is False:
  5147. obj.isHovering = True
  5148. obj.notHovering = True
  5149. # create the selection box around the selected object
  5150. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5151. else:
  5152. if obj.notHovering is True:
  5153. obj.notHovering = False
  5154. obj.isHovering = False
  5155. self.delete_hover_shape()
  5156. except Exception:
  5157. # the Exception here will happen if we try to select on screen and we have an
  5158. # newly (and empty) just created Geometry or Excellon object that do not have the
  5159. # xmin, xmax, ymin, ymax options.
  5160. # In this case poly_obj creation (see above) will fail
  5161. pass
  5162. except Exception as e:
  5163. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5164. self.ui.position_label.setText("")
  5165. self.ui.rel_position_label.setText("")
  5166. self.mouse = None
  5167. def on_mouse_click_release_over_plot(self, event):
  5168. """
  5169. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5170. and has been registered in ''self.__init__()''.
  5171. :param event: contains information about the event.
  5172. :return:
  5173. """
  5174. if self.is_legacy is False:
  5175. event_pos = event.pos
  5176. right_button = 2
  5177. else:
  5178. event_pos = (event.xdata, event.ydata)
  5179. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5180. right_button = 3
  5181. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5182. if self.grid_status():
  5183. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5184. else:
  5185. pos = (pos_canvas[0], pos_canvas[1])
  5186. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5187. # canvas menu
  5188. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5189. self.ui.popMenu.mouse_is_panning = False
  5190. self.cursor = QtGui.QCursor()
  5191. self.populate_cmenu_grids()
  5192. self.ui.popMenu.popup(self.cursor.pos())
  5193. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5194. # selection and then select a type of selection ("enclosing" or "touching")
  5195. if event.button == 1: # left click
  5196. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5197. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5198. if modifiers == QtCore.Qt.ShiftModifier:
  5199. # do not auto open the Project Tab
  5200. self.click_noproject = True
  5201. self.clipboard.setText(
  5202. self.defaults["global_point_clipboard_format"] %
  5203. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5204. )
  5205. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5206. return
  5207. if self.doubleclick is True:
  5208. self.doubleclick = False
  5209. if self.collection.get_selected():
  5210. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5211. if self.ui.splitter.sizes()[0] == 0:
  5212. self.ui.splitter.setSizes([1, 1])
  5213. try:
  5214. # delete the selection shape(S) as it may be in the way
  5215. self.delete_selection_shape()
  5216. self.delete_hover_shape()
  5217. except Exception as e:
  5218. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5219. return
  5220. else:
  5221. # WORKAROUND for LEGACY MODE
  5222. if self.is_legacy is True:
  5223. # if there is no move on canvas then we have no dragging selection
  5224. if self.dx == 0 or self.dy == 0:
  5225. self.selection_type = None
  5226. if self.selection_type is not None:
  5227. try:
  5228. self.selection_area_handler(self.pos, pos, self.selection_type)
  5229. self.selection_type = None
  5230. except Exception as e:
  5231. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5232. return
  5233. else:
  5234. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5235. if key_modifier == QtCore.Qt.ShiftModifier:
  5236. mod_key = 'Shift'
  5237. elif key_modifier == QtCore.Qt.ControlModifier:
  5238. mod_key = 'Control'
  5239. else:
  5240. mod_key = None
  5241. try:
  5242. if self.command_active is None:
  5243. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5244. # deselect, and if it's not selected then it will be selected
  5245. # If there is no active command (self.command_active is None) then we check if we clicked
  5246. # on a object by checking the bounding limits against mouse click position
  5247. if mod_key == self.defaults["global_mselect_key"]:
  5248. self.select_objects(key='multisel')
  5249. else:
  5250. # If there is no active command (self.command_active is None) then we check if
  5251. # we clicked on a object by checking the bounding limits against mouse click position
  5252. self.select_objects()
  5253. self.delete_hover_shape()
  5254. except Exception as e:
  5255. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5256. return
  5257. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5258. """
  5259. :param start_pos: mouse position when the selection LMB click was done
  5260. :param end_pos: mouse position when the left mouse button is released
  5261. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5262. :return:
  5263. """
  5264. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5265. # delete previous selection shape
  5266. self.delete_selection_shape()
  5267. # make all objects inactive
  5268. self.collection.set_all_inactive()
  5269. for obj in self.collection.get_list():
  5270. try:
  5271. # select the object(s) only if it is enabled (plotted)
  5272. if obj.options['plot']:
  5273. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5274. (obj.options['xmax'], obj.options['ymin']),
  5275. (obj.options['xmax'], obj.options['ymax']),
  5276. (obj.options['xmin'], obj.options['ymax'])])
  5277. if sel_type is True:
  5278. if poly_obj.within(poly_selection):
  5279. # create the selection box around the selected object
  5280. if self.defaults['global_selection_shape'] is True:
  5281. self.draw_selection_shape(obj)
  5282. self.collection.set_active(obj.options['name'])
  5283. else:
  5284. if poly_selection.intersects(poly_obj):
  5285. # create the selection box around the selected object
  5286. if self.defaults['global_selection_shape'] is True:
  5287. self.draw_selection_shape(obj)
  5288. self.collection.set_active(obj.options['name'])
  5289. obj.selection_shape_drawn = True
  5290. except Exception as e:
  5291. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5292. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5293. # In this case poly_obj creation (see above) will fail
  5294. log.debug("App.selection_area_handler() --> %s" % str(e))
  5295. def select_objects(self, key=None):
  5296. """
  5297. Will select objects clicked on canvas
  5298. :param key: for future use in cumulative selection
  5299. :return:
  5300. """
  5301. # list where we store the overlapped objects under our mouse left click position
  5302. if key is None:
  5303. self.objects_under_the_click_list = []
  5304. # Populate the list with the overlapped objects on the click position
  5305. curr_x, curr_y = self.pos
  5306. for obj in self.all_objects_list:
  5307. # ScriptObject and DocumentObject objects can't be selected
  5308. if obj.kind == 'script' or obj.kind == 'document':
  5309. continue
  5310. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5311. continue
  5312. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5313. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5314. if obj.options['name'] not in self.objects_under_the_click_list:
  5315. if obj.options['plot']:
  5316. # add objects to the objects_under_the_click list only if the object is plotted
  5317. # (active and not disabled)
  5318. self.objects_under_the_click_list.append(obj.options['name'])
  5319. try:
  5320. if self.objects_under_the_click_list:
  5321. curr_sel_obj = self.collection.get_active()
  5322. # case when there is only an object under the click and we toggle it
  5323. if len(self.objects_under_the_click_list) == 1:
  5324. if curr_sel_obj is None:
  5325. self.collection.set_active(self.objects_under_the_click_list[0])
  5326. curr_sel_obj = self.collection.get_active()
  5327. # create the selection box around the selected object
  5328. if self.defaults['global_selection_shape'] is True:
  5329. self.draw_selection_shape(curr_sel_obj)
  5330. curr_sel_obj.selection_shape_drawn = True
  5331. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5332. self.collection.on_objects_selection(False)
  5333. self.delete_selection_shape()
  5334. curr_sel_obj.selection_shape_drawn = False
  5335. self.collection.set_active(self.objects_under_the_click_list[0])
  5336. curr_sel_obj = self.collection.get_active()
  5337. # create the selection box around the selected object
  5338. if self.defaults['global_selection_shape'] is True:
  5339. self.draw_selection_shape(curr_sel_obj)
  5340. curr_sel_obj.selection_shape_drawn = True
  5341. self.selected_message(curr_sel_obj=curr_sel_obj)
  5342. elif curr_sel_obj.selection_shape_drawn is False:
  5343. if self.defaults['global_selection_shape'] is True:
  5344. self.draw_selection_shape(curr_sel_obj)
  5345. curr_sel_obj.selection_shape_drawn = True
  5346. else:
  5347. self.collection.on_objects_selection(False)
  5348. self.delete_selection_shape()
  5349. if self.call_source != 'app':
  5350. self.call_source = 'app'
  5351. self.selected_message(curr_sel_obj=curr_sel_obj)
  5352. else:
  5353. # If there is no selected object
  5354. # make active the first element of the overlapped objects list
  5355. if self.collection.get_active() is None:
  5356. self.collection.set_active(self.objects_under_the_click_list[0])
  5357. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5358. name_sel_obj = self.collection.get_active().options['name']
  5359. # In case that there is a selected object but it is not in the overlapped object list
  5360. # make that object inactive and activate the first element in the overlapped object list
  5361. if name_sel_obj not in self.objects_under_the_click_list:
  5362. self.collection.set_inactive(name_sel_obj)
  5363. name_sel_obj = self.objects_under_the_click_list[0]
  5364. self.collection.set_active(name_sel_obj)
  5365. else:
  5366. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5367. self.collection.set_all_inactive()
  5368. self.collection.set_active(
  5369. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5370. curr_sel_obj = self.collection.get_active()
  5371. # delete the possible selection box around a possible selected object
  5372. self.delete_selection_shape()
  5373. curr_sel_obj.selection_shape_drawn = False
  5374. # create the selection box around the selected object
  5375. if self.defaults['global_selection_shape'] is True:
  5376. self.draw_selection_shape(curr_sel_obj)
  5377. curr_sel_obj.selection_shape_drawn = True
  5378. self.selected_message(curr_sel_obj=curr_sel_obj)
  5379. else:
  5380. # deselect everything
  5381. self.collection.on_objects_selection(False)
  5382. # delete the possible selection box around a possible selected object
  5383. self.delete_selection_shape()
  5384. for o in self.collection.get_list():
  5385. o.selection_shape_drawn = False
  5386. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5387. # only when working on App
  5388. if self.call_source == 'app':
  5389. if self.click_noproject is False:
  5390. # if the Tool Tab is in focus don't change focus to Project Tab
  5391. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5392. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5393. else:
  5394. # restore auto open the Project Tab
  5395. self.click_noproject = False
  5396. # delete any text in the status bar, implicitly the last object name that was selected
  5397. # self.inform.emit("")
  5398. else:
  5399. self.call_source = 'app'
  5400. except Exception as e:
  5401. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5402. def selected_message(self, curr_sel_obj):
  5403. if curr_sel_obj:
  5404. if curr_sel_obj.kind == 'gerber':
  5405. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5406. color='green',
  5407. name=str(curr_sel_obj.options['name']),
  5408. tx=_("selected"))
  5409. )
  5410. elif curr_sel_obj.kind == 'excellon':
  5411. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5412. color='brown',
  5413. name=str(curr_sel_obj.options['name']),
  5414. tx=_("selected"))
  5415. )
  5416. elif curr_sel_obj.kind == 'cncjob':
  5417. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5418. color='blue',
  5419. name=str(curr_sel_obj.options['name']),
  5420. tx=_("selected"))
  5421. )
  5422. elif curr_sel_obj.kind == 'geometry':
  5423. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5424. color='red',
  5425. name=str(curr_sel_obj.options['name']),
  5426. tx=_("selected"))
  5427. )
  5428. def delete_hover_shape(self):
  5429. self.hover_shapes.clear()
  5430. self.hover_shapes.redraw()
  5431. def draw_hover_shape(self, sel_obj, color=None):
  5432. """
  5433. :param sel_obj: The object for which the hover shape must be drawn
  5434. :param color: The color of the hover shape
  5435. :return: None
  5436. """
  5437. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5438. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5439. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5440. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5441. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5442. if self.defaults['units'].upper() == 'MM':
  5443. hover_rect = hover_rect.buffer(-0.1)
  5444. hover_rect = hover_rect.buffer(0.2)
  5445. else:
  5446. hover_rect = hover_rect.buffer(-0.00393)
  5447. hover_rect = hover_rect.buffer(0.00787)
  5448. # if color:
  5449. # face = Color(color)
  5450. # face.alpha = 0.2
  5451. # outline = Color(color, alpha=0.8)
  5452. # else:
  5453. # face = Color(self.defaults['global_sel_fill'])
  5454. # face.alpha = 0.2
  5455. # outline = self.defaults['global_sel_line']
  5456. if color:
  5457. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5458. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5459. else:
  5460. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5461. outline = self.defaults['global_sel_line']
  5462. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5463. if self.is_legacy is True:
  5464. self.hover_shapes.redraw()
  5465. def delete_selection_shape(self):
  5466. self.move_tool.sel_shapes.clear()
  5467. self.move_tool.sel_shapes.redraw()
  5468. def draw_selection_shape(self, sel_obj, color=None):
  5469. """
  5470. Will draw a selection shape around the selected object.
  5471. :param sel_obj: The object for which the selection shape must be drawn
  5472. :param color: The color for the selection shape.
  5473. :return: None
  5474. """
  5475. if sel_obj is None:
  5476. return
  5477. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5478. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5479. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5480. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5481. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5482. if self.defaults['units'].upper() == 'MM':
  5483. sel_rect = sel_rect.buffer(-0.1)
  5484. sel_rect = sel_rect.buffer(0.2)
  5485. else:
  5486. sel_rect = sel_rect.buffer(-0.00393)
  5487. sel_rect = sel_rect.buffer(0.00787)
  5488. if color:
  5489. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5490. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5491. else:
  5492. if self.is_legacy is False:
  5493. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5494. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5495. else:
  5496. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5497. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5498. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5499. color=outline,
  5500. face_color=face,
  5501. update=True,
  5502. layer=0,
  5503. tolerance=None))
  5504. if self.is_legacy is True:
  5505. self.move_tool.sel_shapes.redraw()
  5506. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5507. """
  5508. Will draw a selection shape when dragging mouse on canvas.
  5509. :param old_coords: Old coordinates
  5510. :param coords: New coordinates
  5511. :param kwargs: Keyword arguments
  5512. :return:
  5513. """
  5514. if 'color' in kwargs:
  5515. color = kwargs['color']
  5516. else:
  5517. color = self.defaults['global_sel_line']
  5518. if 'face_color' in kwargs:
  5519. face_color = kwargs['face_color']
  5520. else:
  5521. face_color = self.defaults['global_sel_fill']
  5522. if 'face_alpha' in kwargs:
  5523. face_alpha = kwargs['face_alpha']
  5524. else:
  5525. face_alpha = 0.3
  5526. x0, y0 = old_coords
  5527. x1, y1 = coords
  5528. pt1 = (x0, y0)
  5529. pt2 = (x1, y0)
  5530. pt3 = (x1, y1)
  5531. pt4 = (x0, y1)
  5532. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5533. # color_t = Color(face_color)
  5534. # color_t.alpha = face_alpha
  5535. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5536. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5537. layer=0, tolerance=None)
  5538. if self.is_legacy is True:
  5539. self.move_tool.sel_shapes.redraw()
  5540. def on_file_new_click(self):
  5541. """
  5542. Callback for menu item File -> New.
  5543. Executed on clicking the Menu -> File -> New Project
  5544. :return:
  5545. """
  5546. if self.collection.get_list() and self.should_we_save:
  5547. msgbox = QtWidgets.QMessageBox()
  5548. # msgbox.setText("<B>Save changes ...</B>")
  5549. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5550. "Creating a New project will delete them.\n"
  5551. "Do you want to Save the project?"))
  5552. msgbox.setWindowTitle(_("Save changes"))
  5553. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5554. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5555. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5556. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5557. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5558. msgbox.setDefaultButton(bt_yes)
  5559. msgbox.exec_()
  5560. response = msgbox.clickedButton()
  5561. if response == bt_yes:
  5562. self.on_file_saveprojectas()
  5563. elif response == bt_cancel:
  5564. return
  5565. elif response == bt_no:
  5566. self.on_file_new()
  5567. else:
  5568. self.on_file_new()
  5569. self.inform.emit('[success] %s...' % _("New Project created"))
  5570. def on_file_new(self, cli=None):
  5571. """
  5572. Returns the application to its startup state. This method is thread-safe.
  5573. :param cli: Boolean. If True this method was run from command line
  5574. :return: None
  5575. """
  5576. self.defaults.report_usage("on_file_new")
  5577. # Remove everything from memory
  5578. App.log.debug("on_file_new()")
  5579. # close any editor that might be open
  5580. if self.call_source != 'app':
  5581. self.editor2object(cleanup=True)
  5582. # ## EDITOR section
  5583. self.geo_editor = AppGeoEditor(self)
  5584. self.exc_editor = AppExcEditor(self)
  5585. self.grb_editor = AppGerberEditor(self)
  5586. # Clear pool
  5587. self.clear_pool()
  5588. for obj in self.collection.get_list():
  5589. # delete shapes left drawn from mark shape_collections, if any
  5590. if isinstance(obj, GerberObject):
  5591. try:
  5592. obj.mark_shapes_storage.clear()
  5593. obj.mark_shapes.clear(update=True)
  5594. obj.mark_shapes.enabled = False
  5595. except AttributeError:
  5596. pass
  5597. # also delete annotation shapes, if any
  5598. elif isinstance(obj, CNCJobObject):
  5599. try:
  5600. obj.text_col.enabled = False
  5601. del obj.text_col
  5602. obj.annotation.clear(update=True)
  5603. del obj.annotation
  5604. except AttributeError:
  5605. pass
  5606. # delete the exclusion areas
  5607. self.exc_areas.clear_shapes()
  5608. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5609. self.shell.init_tcl()
  5610. # delete any selection shape on canvas
  5611. self.delete_selection_shape()
  5612. # delete all FlatCAM objects
  5613. self.collection.delete_all()
  5614. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5615. self.setup_component_editor()
  5616. # Clear project filename
  5617. self.project_filename = None
  5618. # Load the application defaults
  5619. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5620. # Re-fresh project options
  5621. self.on_options_app2project()
  5622. # Init FlatCAMTools
  5623. self.init_tools()
  5624. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  5625. if cli is None:
  5626. # we need to go in reverse because once we remove a tab then the index changes
  5627. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5628. # and so on. Therefore the deletion should be done in reverse
  5629. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5630. for index in range(wdg_count, -1, -1):
  5631. try:
  5632. self.ui.plot_tab_area.closeTab(index)
  5633. except Exception as e:
  5634. log.debug("App.on_file_new() --> %s" % str(e))
  5635. # # And then add again the Plot Area
  5636. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5637. self.ui.plot_tab_area.protectTab(0)
  5638. # take the focus of the Notebook on Project Tab.
  5639. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5640. self.set_ui_title(name=_("New Project - Not saved"))
  5641. def obj_properties(self):
  5642. """
  5643. Will launch the object Properties Tool
  5644. :return:
  5645. """
  5646. self.defaults.report_usage("obj_properties()")
  5647. self.properties_tool.run(toggle=False)
  5648. def on_project_context_save(self):
  5649. """
  5650. Wrapper, will save the object function of it's type
  5651. :return:
  5652. """
  5653. sel_objects = self.collection.get_selected()
  5654. len_objects = len(sel_objects)
  5655. cnt = 0
  5656. if len_objects > 1:
  5657. for o in sel_objects:
  5658. if o.kind == 'cncjob':
  5659. cnt += 1
  5660. if len_objects == cnt:
  5661. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5662. _filter_ = self.defaults['cncjob_save_filters'] + \
  5663. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5664. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5665. try:
  5666. filename, _f = FCFileSaveDialog.get_saved_filename(
  5667. caption=_("Export Code ..."),
  5668. directory=dir_file_to_save,
  5669. ext_filter=_filter_
  5670. )
  5671. except TypeError:
  5672. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."),
  5673. ext_filter=_filter_)
  5674. filename = filename.rpartition('/')[0]
  5675. for ob in sel_objects:
  5676. ob.read_form()
  5677. fname = '%s/%s' % (filename, ob.options['name'])
  5678. ob.export_gcode_handler(fname, is_gcode=True)
  5679. return
  5680. obj = self.collection.get_active()
  5681. if type(obj) == GeometryObject:
  5682. self.on_file_exportdxf()
  5683. elif type(obj) == ExcellonObject:
  5684. self.on_file_saveexcellon()
  5685. elif type(obj) == CNCJobObject:
  5686. obj.on_exportgcode_button_click()
  5687. elif type(obj) == GerberObject:
  5688. self.on_file_savegerber()
  5689. elif type(obj) == ScriptObject:
  5690. self.on_file_savescript()
  5691. elif type(obj) == DocumentObject:
  5692. self.on_file_savedocument()
  5693. def obj_move(self):
  5694. """
  5695. Callback for the Move menu entry in various Context Menu's.
  5696. :return:
  5697. """
  5698. self.defaults.report_usage("obj_move()")
  5699. self.move_tool.run(toggle=False)
  5700. def on_fileopengerber(self, signal, name=None):
  5701. """
  5702. File menu callback for opening a Gerber.
  5703. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5704. :param name:
  5705. :return: None
  5706. """
  5707. self.defaults.report_usage("on_fileopengerber")
  5708. App.log.debug("on_fileopengerber()")
  5709. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  5710. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  5711. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  5712. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  5713. "*.outline);;" \
  5714. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5715. "*.mil);;" \
  5716. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5717. "Allegro Files (*.art);;" \
  5718. "Mentor Files (*.pho *.gdo);;" \
  5719. "All Files (*.*)"
  5720. if name is None:
  5721. try:
  5722. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5723. directory=self.get_last_folder(),
  5724. filter=_filter_,
  5725. initialFilter=self.last_op_gerber_filter)
  5726. except TypeError:
  5727. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5728. filenames = [str(filename) for filename in filenames]
  5729. self.last_op_gerber_filter = _f
  5730. else:
  5731. filenames = [name]
  5732. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5733. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5734. _("Opening Gerber file.")),
  5735. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5736. color=QtGui.QColor("gray"))
  5737. if len(filenames) == 0:
  5738. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5739. else:
  5740. for filename in filenames:
  5741. if filename != '':
  5742. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5743. def on_fileopenexcellon(self, signal, name=None):
  5744. """
  5745. File menu callback for opening an Excellon file.
  5746. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5747. :param name:
  5748. :return: None
  5749. """
  5750. self.defaults.report_usage("on_fileopenexcellon")
  5751. App.log.debug("on_fileopenexcellon()")
  5752. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5753. "All Files (*.*)"
  5754. if name is None:
  5755. try:
  5756. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5757. directory=self.get_last_folder(),
  5758. filter=_filter_,
  5759. initialFilter=self.last_op_excellon_filter)
  5760. except TypeError:
  5761. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5762. filenames = [str(filename) for filename in filenames]
  5763. self.last_op_excellon_filter = _f
  5764. else:
  5765. filenames = [str(name)]
  5766. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5767. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5768. _("Opening Excellon file.")),
  5769. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5770. color=QtGui.QColor("gray"))
  5771. if len(filenames) == 0:
  5772. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5773. else:
  5774. for filename in filenames:
  5775. if filename != '':
  5776. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5777. def on_fileopengcode(self, signal, name=None):
  5778. """
  5779. File menu call back for opening gcode.
  5780. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5781. :param name:
  5782. :return:
  5783. """
  5784. self.defaults.report_usage("on_fileopengcode")
  5785. App.log.debug("on_fileopengcode()")
  5786. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5787. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5788. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5789. "All Files (*.*)"
  5790. if name is None:
  5791. try:
  5792. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5793. directory=self.get_last_folder(),
  5794. filter=_filter_,
  5795. initialFilter=self.last_op_gcode_filter)
  5796. except TypeError:
  5797. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5798. filenames = [str(filename) for filename in filenames]
  5799. self.last_op_gcode_filter = _f
  5800. else:
  5801. filenames = [name]
  5802. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5803. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5804. _("Opening G-Code file.")),
  5805. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5806. color=QtGui.QColor("gray"))
  5807. if len(filenames) == 0:
  5808. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5809. else:
  5810. for filename in filenames:
  5811. if filename != '':
  5812. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5813. def on_file_openproject(self, signal):
  5814. """
  5815. File menu callback for opening a project.
  5816. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5817. :return: None
  5818. """
  5819. self.defaults.report_usage("on_file_openproject")
  5820. App.log.debug("on_file_openproject()")
  5821. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5822. try:
  5823. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5824. directory=self.get_last_folder(), filter=_filter_)
  5825. except TypeError:
  5826. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5827. # The Qt methods above will return a QString which can cause problems later.
  5828. # So far json.dump() will fail to serialize it.
  5829. # TODO: Improve the serialization methods and remove this fix.
  5830. filename = str(filename)
  5831. if filename == "":
  5832. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5833. else:
  5834. # self.worker_task.emit({'fcn': self.open_project,
  5835. # 'params': [filename]})
  5836. # The above was failing because open_project() is not
  5837. # thread safe. The new_project()
  5838. self.open_project(filename)
  5839. def on_fileopenhpgl2(self, signal, name=None):
  5840. """
  5841. File menu callback for opening a HPGL2.
  5842. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5843. :param name:
  5844. :return: None
  5845. """
  5846. self.defaults.report_usage("on_fileopenhpgl2")
  5847. App.log.debug("on_fileopenhpgl2()")
  5848. _filter_ = "HPGL2 Files (*.plt);;" \
  5849. "All Files (*.*)"
  5850. if name is None:
  5851. try:
  5852. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5853. directory=self.get_last_folder(),
  5854. filter=_filter_)
  5855. except TypeError:
  5856. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5857. filenames = [str(filename) for filename in filenames]
  5858. else:
  5859. filenames = [name]
  5860. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5861. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5862. _("Opening HPGL2 file.")),
  5863. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5864. color=QtGui.QColor("gray"))
  5865. if len(filenames) == 0:
  5866. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5867. else:
  5868. for filename in filenames:
  5869. if filename != '':
  5870. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5871. def on_file_openconfig(self, signal):
  5872. """
  5873. File menu callback for opening a config file.
  5874. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5875. :return: None
  5876. """
  5877. self.defaults.report_usage("on_file_openconfig")
  5878. App.log.debug("on_file_openconfig()")
  5879. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5880. try:
  5881. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5882. directory=self.data_path, filter=_filter_)
  5883. except TypeError:
  5884. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5885. filter=_filter_)
  5886. if filename == "":
  5887. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5888. else:
  5889. self.open_config_file(filename)
  5890. def on_file_exportsvg(self):
  5891. """
  5892. Callback for menu item File->Export SVG.
  5893. :return: None
  5894. """
  5895. self.defaults.report_usage("on_file_exportsvg")
  5896. App.log.debug("on_file_exportsvg()")
  5897. obj = self.collection.get_active()
  5898. if obj is None:
  5899. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5900. msg = _("Please Select a Geometry object to export")
  5901. msgbox = QtWidgets.QMessageBox()
  5902. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5903. msgbox.setInformativeText(msg)
  5904. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5905. msgbox.setDefaultButton(bt_ok)
  5906. msgbox.exec_()
  5907. return
  5908. # Check for more compatible types and add as required
  5909. if (not isinstance(obj, GeometryObject)
  5910. and not isinstance(obj, GerberObject)
  5911. and not isinstance(obj, CNCJobObject)
  5912. and not isinstance(obj, ExcellonObject)):
  5913. msg = '[ERROR_NOTCL] %s' % \
  5914. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5915. msgbox = QtWidgets.QMessageBox()
  5916. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5917. msgbox.setInformativeText(msg)
  5918. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5919. msgbox.setDefaultButton(bt_ok)
  5920. msgbox.exec_()
  5921. return
  5922. name = obj.options["name"]
  5923. _filter = "SVG File (*.svg);;All Files (*.*)"
  5924. try:
  5925. filename, _f = FCFileSaveDialog.get_saved_filename(
  5926. caption=_("Export SVG"),
  5927. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5928. ext_filter=_filter)
  5929. except TypeError:
  5930. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5931. filename = str(filename)
  5932. if filename == "":
  5933. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5934. return
  5935. else:
  5936. self.export_svg(name, filename)
  5937. if self.defaults["global_open_style"] is False:
  5938. self.file_opened.emit("SVG", filename)
  5939. self.file_saved.emit("SVG", filename)
  5940. def on_file_exportpng(self):
  5941. self.defaults.report_usage("on_file_exportpng")
  5942. App.log.debug("on_file_exportpng()")
  5943. self.date = str(datetime.today()).rpartition('.')[0]
  5944. self.date = ''.join(c for c in self.date if c not in ':-')
  5945. self.date = self.date.replace(' ', '_')
  5946. data = None
  5947. if self.is_legacy is False:
  5948. image = _screenshot(alpha=False)
  5949. data = np.asarray(image)
  5950. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5951. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5952. return
  5953. filter_ = "PNG File (*.png);;All Files (*.*)"
  5954. try:
  5955. filename, _f = FCFileSaveDialog.get_saved_filename(
  5956. caption=_("Export PNG Image"),
  5957. directory=self.get_last_save_folder() + '/png_' + self.date,
  5958. ext_filter=filter_)
  5959. except TypeError:
  5960. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  5961. filename = str(filename)
  5962. if filename == "":
  5963. self.inform.emit(_("Cancelled."))
  5964. return
  5965. else:
  5966. if self.is_legacy is False:
  5967. write_png(filename, data)
  5968. else:
  5969. self.plotcanvas.figure.savefig(filename)
  5970. if self.defaults["global_open_style"] is False:
  5971. self.file_opened.emit("png", filename)
  5972. self.file_saved.emit("png", filename)
  5973. def on_file_savegerber(self):
  5974. """
  5975. Callback for menu item in Project context menu.
  5976. :return: None
  5977. """
  5978. self.defaults.report_usage("on_file_savegerber")
  5979. App.log.debug("on_file_savegerber()")
  5980. obj = self.collection.get_active()
  5981. if obj is None:
  5982. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5983. return
  5984. # Check for more compatible types and add as required
  5985. if not isinstance(obj, GerberObject):
  5986. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5987. return
  5988. name = self.collection.get_active().options["name"]
  5989. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5990. try:
  5991. filename, _f = FCFileSaveDialog.get_saved_filename(
  5992. caption="Save Gerber source file",
  5993. directory=self.get_last_save_folder() + '/' + name,
  5994. ext_filter=_filter)
  5995. except TypeError:
  5996. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  5997. filename = str(filename)
  5998. if filename == "":
  5999. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6000. return
  6001. else:
  6002. self.save_source_file(name, filename)
  6003. if self.defaults["global_open_style"] is False:
  6004. self.file_opened.emit("Gerber", filename)
  6005. self.file_saved.emit("Gerber", filename)
  6006. def on_file_savescript(self):
  6007. """
  6008. Callback for menu item in Project context menu.
  6009. :return: None
  6010. """
  6011. self.defaults.report_usage("on_file_savescript")
  6012. App.log.debug("on_file_savescript()")
  6013. obj = self.collection.get_active()
  6014. if obj is None:
  6015. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6016. return
  6017. # Check for more compatible types and add as required
  6018. if not isinstance(obj, ScriptObject):
  6019. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6020. return
  6021. name = self.collection.get_active().options["name"]
  6022. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6023. try:
  6024. filename, _f = FCFileSaveDialog.get_saved_filename(
  6025. caption="Save Script source file",
  6026. directory=self.get_last_save_folder() + '/' + name,
  6027. ext_filter=_filter)
  6028. except TypeError:
  6029. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  6030. filename = str(filename)
  6031. if filename == "":
  6032. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6033. return
  6034. else:
  6035. self.save_source_file(name, filename)
  6036. if self.defaults["global_open_style"] is False:
  6037. self.file_opened.emit("Script", filename)
  6038. self.file_saved.emit("Script", filename)
  6039. def on_file_savedocument(self):
  6040. """
  6041. Callback for menu item in Project context menu.
  6042. :return: None
  6043. """
  6044. self.defaults.report_usage("on_file_savedocument")
  6045. App.log.debug("on_file_savedocument()")
  6046. obj = self.collection.get_active()
  6047. if obj is None:
  6048. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6049. return
  6050. # Check for more compatible types and add as required
  6051. if not isinstance(obj, ScriptObject):
  6052. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6053. return
  6054. name = self.collection.get_active().options["name"]
  6055. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6056. try:
  6057. filename, _f = FCFileSaveDialog.get_saved_filename(
  6058. caption="Save Document source file",
  6059. directory=self.get_last_save_folder() + '/' + name,
  6060. ext_filter=_filter)
  6061. except TypeError:
  6062. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  6063. ext_filter=_filter)
  6064. filename = str(filename)
  6065. if filename == "":
  6066. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6067. return
  6068. else:
  6069. self.save_source_file(name, filename)
  6070. if self.defaults["global_open_style"] is False:
  6071. self.file_opened.emit("Document", filename)
  6072. self.file_saved.emit("Document", filename)
  6073. def on_file_saveexcellon(self):
  6074. """
  6075. Callback for menu item in project context menu.
  6076. :return: None
  6077. """
  6078. self.defaults.report_usage("on_file_saveexcellon")
  6079. App.log.debug("on_file_saveexcellon()")
  6080. obj = self.collection.get_active()
  6081. if obj is None:
  6082. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6083. return
  6084. # Check for more compatible types and add as required
  6085. if not isinstance(obj, ExcellonObject):
  6086. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6087. return
  6088. name = self.collection.get_active().options["name"]
  6089. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6090. try:
  6091. filename, _f = FCFileSaveDialog.get_saved_filename(
  6092. caption=_("Save Excellon source file"),
  6093. directory=self.get_last_save_folder() + '/' + name,
  6094. ext_filter=_filter)
  6095. except TypeError:
  6096. filename, _f = FCFileSaveDialog.get_saved_filename(
  6097. caption=_("Save Excellon source file"), ext_filter=_filter)
  6098. filename = str(filename)
  6099. if filename == "":
  6100. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6101. return
  6102. else:
  6103. self.save_source_file(name, filename)
  6104. if self.defaults["global_open_style"] is False:
  6105. self.file_opened.emit("Excellon", filename)
  6106. self.file_saved.emit("Excellon", filename)
  6107. def on_file_exportexcellon(self):
  6108. """
  6109. Callback for menu item File->Export->Excellon.
  6110. :return: None
  6111. """
  6112. self.defaults.report_usage("on_file_exportexcellon")
  6113. App.log.debug("on_file_exportexcellon()")
  6114. obj = self.collection.get_active()
  6115. if obj is None:
  6116. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6117. return
  6118. # Check for more compatible types and add as required
  6119. if not isinstance(obj, ExcellonObject):
  6120. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6121. return
  6122. name = self.collection.get_active().options["name"]
  6123. _filter = self.defaults["excellon_save_filters"]
  6124. try:
  6125. filename, _f = FCFileSaveDialog.get_saved_filename(
  6126. caption=_("Export Excellon"),
  6127. directory=self.get_last_save_folder() + '/' + name,
  6128. ext_filter=_filter)
  6129. except TypeError:
  6130. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  6131. filename = str(filename)
  6132. if filename == "":
  6133. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6134. return
  6135. else:
  6136. used_extension = filename.rpartition('.')[2]
  6137. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6138. self.export_excellon(name, filename)
  6139. if self.defaults["global_open_style"] is False:
  6140. self.file_opened.emit("Excellon", filename)
  6141. self.file_saved.emit("Excellon", filename)
  6142. def on_file_exportgerber(self):
  6143. """
  6144. Callback for menu item File->Export->Gerber.
  6145. :return: None
  6146. """
  6147. self.defaults.report_usage("on_file_exportgerber")
  6148. App.log.debug("on_file_exportgerber()")
  6149. obj = self.collection.get_active()
  6150. if obj is None:
  6151. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6152. return
  6153. # Check for more compatible types and add as required
  6154. if not isinstance(obj, GerberObject):
  6155. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6156. return
  6157. name = self.collection.get_active().options["name"]
  6158. _filter_ = self.defaults['gerber_save_filters']
  6159. try:
  6160. filename, _f = FCFileSaveDialog.get_saved_filename(
  6161. caption=_("Export Gerber"),
  6162. directory=self.get_last_save_folder() + '/' + name,
  6163. ext_filter=_filter_)
  6164. except TypeError:
  6165. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  6166. filename = str(filename)
  6167. if filename == "":
  6168. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6169. return
  6170. else:
  6171. used_extension = filename.rpartition('.')[2]
  6172. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6173. self.export_gerber(name, filename)
  6174. if self.defaults["global_open_style"] is False:
  6175. self.file_opened.emit("Gerber", filename)
  6176. self.file_saved.emit("Gerber", filename)
  6177. def on_file_exportdxf(self):
  6178. """
  6179. Callback for menu item File->Export DXF.
  6180. :return: None
  6181. """
  6182. self.defaults.report_usage("on_file_exportdxf")
  6183. App.log.debug("on_file_exportdxf()")
  6184. obj = self.collection.get_active()
  6185. if obj is None:
  6186. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6187. msg = _("Please Select a Geometry object to export")
  6188. msgbox = QtWidgets.QMessageBox()
  6189. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6190. msgbox.setInformativeText(msg)
  6191. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6192. msgbox.setDefaultButton(bt_ok)
  6193. msgbox.exec_()
  6194. return
  6195. # Check for more compatible types and add as required
  6196. if not isinstance(obj, GeometryObject):
  6197. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6198. msgbox = QtWidgets.QMessageBox()
  6199. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6200. msgbox.setInformativeText(msg)
  6201. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6202. msgbox.setDefaultButton(bt_ok)
  6203. msgbox.exec_()
  6204. return
  6205. name = self.collection.get_active().options["name"]
  6206. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6207. try:
  6208. filename, _f = FCFileSaveDialog.get_saved_filename(
  6209. caption=_("Export DXF"),
  6210. directory=self.get_last_save_folder() + '/' + name,
  6211. ext_filter=_filter_)
  6212. except TypeError:
  6213. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  6214. filename = str(filename)
  6215. if filename == "":
  6216. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6217. return
  6218. else:
  6219. self.export_dxf(name, filename)
  6220. if self.defaults["global_open_style"] is False:
  6221. self.file_opened.emit("DXF", filename)
  6222. self.file_saved.emit("DXF", filename)
  6223. def on_file_importsvg(self, type_of_obj):
  6224. """
  6225. Callback for menu item File->Import SVG.
  6226. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6227. :type type_of_obj: str
  6228. :return: None
  6229. """
  6230. self.defaults.report_usage("on_file_importsvg")
  6231. App.log.debug("on_file_importsvg()")
  6232. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6233. try:
  6234. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6235. directory=self.get_last_folder(), filter=_filter_)
  6236. except TypeError:
  6237. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6238. filter=_filter_)
  6239. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6240. type_of_obj = "geometry"
  6241. filenames = [str(filename) for filename in filenames]
  6242. if len(filenames) == 0:
  6243. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6244. else:
  6245. for filename in filenames:
  6246. if filename != '':
  6247. self.worker_task.emit({'fcn': self.import_svg,
  6248. 'params': [filename, type_of_obj]})
  6249. def on_file_importdxf(self, type_of_obj):
  6250. """
  6251. Callback for menu item File->Import DXF.
  6252. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6253. :type type_of_obj: str
  6254. :return: None
  6255. """
  6256. self.defaults.report_usage("on_file_importdxf")
  6257. App.log.debug("on_file_importdxf()")
  6258. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6259. try:
  6260. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6261. directory=self.get_last_folder(),
  6262. filter=_filter_)
  6263. except TypeError:
  6264. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6265. filter=_filter_)
  6266. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6267. type_of_obj = "geometry"
  6268. filenames = [str(filename) for filename in filenames]
  6269. if len(filenames) == 0:
  6270. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6271. else:
  6272. for filename in filenames:
  6273. if filename != '':
  6274. self.worker_task.emit({'fcn': self.import_dxf,
  6275. 'params': [filename, type_of_obj]})
  6276. # ###############################################################################################################
  6277. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6278. # ###############################################################################################################
  6279. def init_code_editor(self, name):
  6280. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  6281. # add the tab if it was closed
  6282. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6283. self.text_editor_tab.setObjectName('text_editor_tab')
  6284. # delete the absolute and relative position and messages in the infobar
  6285. # self.ui.position_label.setText("")
  6286. # self.ui.rel_position_label.setText("")
  6287. # hide coordinates toolbars in the infobar while in DB
  6288. self.ui.coords_toolbar.hide()
  6289. self.ui.delta_coords_toolbar.hide()
  6290. self.toggle_codeeditor = True
  6291. self.text_editor_tab.code_editor.completer_enable = False
  6292. self.text_editor_tab.buttonRun.hide()
  6293. # make sure to keep a reference to the code editor
  6294. self.reference_code_editor = self.text_editor_tab.code_editor
  6295. # Switch plot_area to CNCJob tab
  6296. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6297. def on_view_source(self):
  6298. """
  6299. Called when the user wants to see the source file of the selected object
  6300. :return:
  6301. """
  6302. try:
  6303. obj = self.collection.get_active()
  6304. except Exception as e:
  6305. log.debug("App.on_view_source() --> %s" % str(e))
  6306. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6307. return 'fail'
  6308. if obj is None:
  6309. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6310. return 'fail'
  6311. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6312. self.proc_container.view.set_busy(_("Loading..."))
  6313. flt = "All Files (*.*)"
  6314. if obj.kind == 'gerber':
  6315. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6316. elif obj.kind == 'excellon':
  6317. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6318. elif obj.kind == 'cncjob':
  6319. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6320. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  6321. # add the tab if it was closed
  6322. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6323. self.source_editor_tab.setObjectName('source_editor_tab')
  6324. # delete the absolute and relative position and messages in the infobar
  6325. # self.ui.position_label.setText("")
  6326. # self.ui.rel_position_label.setText("")
  6327. # hide coordinates toolbars in the infobar while in DB
  6328. self.ui.coords_toolbar.hide()
  6329. self.ui.delta_coords_toolbar.hide()
  6330. self.source_editor_tab.code_editor.completer_enable = False
  6331. self.source_editor_tab.buttonRun.hide()
  6332. # Switch plot_area to CNCJob tab
  6333. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6334. try:
  6335. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6336. except TypeError:
  6337. pass
  6338. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6339. try:
  6340. self.source_editor_tab.buttonSave.clicked.disconnect()
  6341. except TypeError:
  6342. pass
  6343. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6344. # then append the text from GCode to the text editor
  6345. if obj.kind == 'cncjob':
  6346. try:
  6347. file = obj.export_gcode(to_file=True)
  6348. if file == 'fail':
  6349. return 'fail'
  6350. except AttributeError:
  6351. self.inform.emit('[WARNING_NOTCL] %s' %
  6352. _("There is no selected object for which to see it's source file code."))
  6353. return 'fail'
  6354. else:
  6355. try:
  6356. file = StringIO(obj.source_file)
  6357. except (AttributeError, TypeError):
  6358. self.inform.emit('[WARNING_NOTCL] %s' %
  6359. _("There is no selected object for which to see it's source file code."))
  6360. return 'fail'
  6361. self.source_editor_tab.t_frame.hide()
  6362. try:
  6363. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  6364. except Exception as e:
  6365. log.debug('App.on_view_source() -->%s' % str(e))
  6366. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6367. return
  6368. self.source_editor_tab.t_frame.show()
  6369. self.proc_container.view.set_idle()
  6370. # self.ui.show()
  6371. def on_toggle_code_editor(self):
  6372. self.defaults.report_usage("on_toggle_code_editor()")
  6373. if self.toggle_codeeditor is False:
  6374. self.init_code_editor(name=_("Code Editor"))
  6375. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6376. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6377. self.text_editor_tab.buttonSave.clicked.disconnect()
  6378. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6379. else:
  6380. for idx in range(self.ui.plot_tab_area.count()):
  6381. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6382. self.ui.plot_tab_area.closeTab(idx)
  6383. break
  6384. self.toggle_codeeditor = False
  6385. def on_code_editor_close(self):
  6386. self.toggle_codeeditor = False
  6387. def goto_text_line(self):
  6388. """
  6389. Will scroll a text to the specified text line.
  6390. :return: None
  6391. """
  6392. dia_box = Dialog_box(title=_("Go to Line ..."),
  6393. label=_("Line:"),
  6394. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6395. initial_text='')
  6396. try:
  6397. line = int(dia_box.location) - 1
  6398. except (ValueError, TypeError):
  6399. line = 0
  6400. if dia_box.ok:
  6401. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6402. # at the top of the window
  6403. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6404. # get the document() of the AppTextEditor
  6405. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6406. # create a Text Cursor based on the searched line
  6407. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6408. # set cursor of the code editor with the cursor at the searcehd line
  6409. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6410. def on_filenewscript(self, silent=False):
  6411. """
  6412. Will create a new script file and open it in the Code Editor
  6413. :param silent: if True will not display status messages
  6414. :return: None
  6415. """
  6416. if silent is False:
  6417. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6418. # delete the absolute and relative position and messages in the infobar
  6419. # self.ui.position_label.setText("")
  6420. # self.ui.rel_position_label.setText("")
  6421. # hide coordinates toolbars in the infobar while in DB
  6422. self.ui.coords_toolbar.hide()
  6423. self.ui.delta_coords_toolbar.hide()
  6424. self.app_obj.new_script_object()
  6425. # script_text = script_obj.source_file
  6426. #
  6427. # self.proc_container.view.set_busy(_("Loading..."))
  6428. # script_obj.script_editor_tab.t_frame.hide()
  6429. #
  6430. # script_obj.script_editor_tab.t_frame.show()
  6431. # self.proc_container.view.set_idle()
  6432. def on_fileopenscript(self, name=None, silent=False):
  6433. """
  6434. Will open a Tcl script file into the Code Editor
  6435. :param silent: if True will not display status messages
  6436. :param name: name of a Tcl script file to open
  6437. :return: None
  6438. """
  6439. self.defaults.report_usage("on_fileopenscript")
  6440. App.log.debug("on_fileopenscript()")
  6441. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6442. "All Files (*.*)"
  6443. if name:
  6444. filenames = [name]
  6445. else:
  6446. try:
  6447. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6448. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6449. except TypeError:
  6450. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6451. if len(filenames) == 0:
  6452. if silent is False:
  6453. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6454. else:
  6455. for filename in filenames:
  6456. if filename != '':
  6457. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6458. def on_fileopenscript_example(self, name=None, silent=False):
  6459. """
  6460. Will open a Tcl script file into the Code Editor
  6461. :param silent: if True will not display status messages
  6462. :param name: name of a Tcl script file to open
  6463. :return:
  6464. """
  6465. self.defaults.report_usage("on_fileopenscript_example")
  6466. log.debug("on_fileopenscript_example()")
  6467. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6468. "All Files (*.*)"
  6469. # test if the app was frozen and choose the path for the configuration file
  6470. if getattr(sys, "frozen", False) is True:
  6471. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6472. else:
  6473. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6474. if name:
  6475. filenames = [name]
  6476. else:
  6477. try:
  6478. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6479. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6480. except TypeError:
  6481. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6482. if len(filenames) == 0:
  6483. if silent is False:
  6484. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6485. else:
  6486. for filename in filenames:
  6487. if filename != '':
  6488. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6489. def on_filerunscript(self, name=None, silent=False):
  6490. """
  6491. File menu callback for loading and running a TCL script.
  6492. :param silent: if True will not display status messages
  6493. :param name: name of a Tcl script file to be run by FlatCAM
  6494. :return: None
  6495. """
  6496. self.defaults.report_usage("on_filerunscript")
  6497. App.log.debug("on_file_runscript()")
  6498. if name:
  6499. filename = name
  6500. if self.cmd_line_headless != 1:
  6501. self.splash.showMessage('%s: %ssec\n%s' %
  6502. (_("Canvas initialization started.\n"
  6503. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6504. _("Executing ScriptObject file.")
  6505. ),
  6506. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6507. color=QtGui.QColor("gray"))
  6508. else:
  6509. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6510. "All Files (*.*)"
  6511. try:
  6512. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6513. directory=self.get_last_folder(), filter=_filter_)
  6514. except TypeError:
  6515. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6516. # The Qt methods above will return a QString which can cause problems later.
  6517. # So far json.dump() will fail to serialize it.
  6518. filename = str(filename)
  6519. if filename == "":
  6520. if silent is False:
  6521. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6522. else:
  6523. if self.cmd_line_headless != 1:
  6524. if self.ui.shell_dock.isHidden():
  6525. self.ui.shell_dock.show()
  6526. try:
  6527. with open(filename, "r") as tcl_script:
  6528. cmd_line_shellfile_content = tcl_script.read()
  6529. if self.cmd_line_headless != 1:
  6530. self.shell.exec_command(cmd_line_shellfile_content)
  6531. else:
  6532. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6533. if silent is False:
  6534. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6535. except Exception as e:
  6536. log.debug("App.on_filerunscript() -> %s" % str(e))
  6537. sys.exit(2)
  6538. def on_file_saveproject(self, silent=False):
  6539. """
  6540. Callback for menu item File->Save Project. Saves the project to
  6541. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6542. if set to None. The project is saved by calling ``self.save_project()``.
  6543. :param silent: if True will not display status messages
  6544. :return: None
  6545. """
  6546. self.defaults.report_usage("on_file_saveproject")
  6547. if self.project_filename is None:
  6548. self.on_file_saveprojectas()
  6549. else:
  6550. self.worker_task.emit({'fcn': self.save_project,
  6551. 'params': [self.project_filename, silent]})
  6552. if self.defaults["global_open_style"] is False:
  6553. self.file_opened.emit("project", self.project_filename)
  6554. self.file_saved.emit("project", self.project_filename)
  6555. self.set_ui_title(name=self.project_filename)
  6556. self.should_we_save = False
  6557. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6558. """
  6559. Callback for menu item File->Save Project As... Opens a file
  6560. chooser and saves the project to the given file via
  6561. ``self.save_project()``.
  6562. :param make_copy if to be create a copy of the project; boolean
  6563. :param use_thread: if to be run in a separate thread; boolean
  6564. :param quit_action: if to be followed by quiting the application; boolean
  6565. :return: None
  6566. """
  6567. self.defaults.report_usage("on_file_saveprojectas")
  6568. self.date = str(datetime.today()).rpartition('.')[0]
  6569. self.date = ''.join(c for c in self.date if c not in ':-')
  6570. self.date = self.date.replace(' ', '_')
  6571. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6572. try:
  6573. filename, _f = FCFileSaveDialog.get_saved_filename(
  6574. caption=_("Save Project As ..."),
  6575. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6576. proj=_("Project")),
  6577. ext_filter=filter_
  6578. )
  6579. except TypeError:
  6580. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6581. filename = str(filename)
  6582. if filename == '':
  6583. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6584. return
  6585. if use_thread is True:
  6586. self.worker_task.emit({'fcn': self.save_project,
  6587. 'params': [filename, quit_action]})
  6588. else:
  6589. self.save_project(filename, quit_action)
  6590. # self.save_project(filename)
  6591. if self.defaults["global_open_style"] is False:
  6592. self.file_opened.emit("project", filename)
  6593. self.file_saved.emit("project", filename)
  6594. if not make_copy:
  6595. self.project_filename = filename
  6596. self.set_ui_title(name=self.project_filename)
  6597. self.should_we_save = False
  6598. def on_file_save_objects_pdf(self, use_thread=True):
  6599. self.date = str(datetime.today()).rpartition('.')[0]
  6600. self.date = ''.join(c for c in self.date if c not in ':-')
  6601. self.date = self.date.replace(' ', '_')
  6602. try:
  6603. obj_selection = self.collection.get_selected()
  6604. if len(obj_selection) == 1:
  6605. obj_name = str(obj_selection[0].options['name'])
  6606. else:
  6607. obj_name = _("FlatCAM objects print")
  6608. except AttributeError as err:
  6609. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6610. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6611. return
  6612. if not obj_selection:
  6613. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6614. return
  6615. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6616. try:
  6617. filename, _f = FCFileSaveDialog.get_saved_filename(
  6618. caption=_("Save Object as PDF ..."),
  6619. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6620. obj_name=obj_name,
  6621. date=self.date),
  6622. ext_filter=filter_
  6623. )
  6624. except TypeError:
  6625. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6626. filename = str(filename)
  6627. if filename == '':
  6628. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6629. return
  6630. if use_thread is True:
  6631. self.proc_container.new(_("Printing PDF ... Please wait."))
  6632. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6633. else:
  6634. self.save_pdf(filename, obj_selection)
  6635. # self.save_project(filename)
  6636. if self.defaults["global_open_style"] is False:
  6637. self.file_opened.emit("pdf", filename)
  6638. self.file_saved.emit("pdf", filename)
  6639. def save_pdf(self, file_name, obj_selection):
  6640. p_size = self.defaults['global_workspaceT']
  6641. orientation = self.defaults['global_workspace_orientation']
  6642. color = 'black'
  6643. transparency_level = 1.0
  6644. self.pagesize = {}
  6645. self.pagesize.update(
  6646. {
  6647. 'Bounds': None,
  6648. 'A0': (841 * mm, 1189 * mm),
  6649. 'A1': (594 * mm, 841 * mm),
  6650. 'A2': (420 * mm, 594 * mm),
  6651. 'A3': (297 * mm, 420 * mm),
  6652. 'A4': (210 * mm, 297 * mm),
  6653. 'A5': (148 * mm, 210 * mm),
  6654. 'A6': (105 * mm, 148 * mm),
  6655. 'A7': (74 * mm, 105 * mm),
  6656. 'A8': (52 * mm, 74 * mm),
  6657. 'A9': (37 * mm, 52 * mm),
  6658. 'A10': (26 * mm, 37 * mm),
  6659. 'B0': (1000 * mm, 1414 * mm),
  6660. 'B1': (707 * mm, 1000 * mm),
  6661. 'B2': (500 * mm, 707 * mm),
  6662. 'B3': (353 * mm, 500 * mm),
  6663. 'B4': (250 * mm, 353 * mm),
  6664. 'B5': (176 * mm, 250 * mm),
  6665. 'B6': (125 * mm, 176 * mm),
  6666. 'B7': (88 * mm, 125 * mm),
  6667. 'B8': (62 * mm, 88 * mm),
  6668. 'B9': (44 * mm, 62 * mm),
  6669. 'B10': (31 * mm, 44 * mm),
  6670. 'C0': (917 * mm, 1297 * mm),
  6671. 'C1': (648 * mm, 917 * mm),
  6672. 'C2': (458 * mm, 648 * mm),
  6673. 'C3': (324 * mm, 458 * mm),
  6674. 'C4': (229 * mm, 324 * mm),
  6675. 'C5': (162 * mm, 229 * mm),
  6676. 'C6': (114 * mm, 162 * mm),
  6677. 'C7': (81 * mm, 114 * mm),
  6678. 'C8': (57 * mm, 81 * mm),
  6679. 'C9': (40 * mm, 57 * mm),
  6680. 'C10': (28 * mm, 40 * mm),
  6681. # American paper sizes
  6682. 'LETTER': (8.5 * inch, 11 * inch),
  6683. 'LEGAL': (8.5 * inch, 14 * inch),
  6684. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6685. # From https://en.wikipedia.org/wiki/Paper_size
  6686. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6687. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6688. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6689. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6690. 'LEDGER': (17 * inch, 11 * inch),
  6691. }
  6692. )
  6693. exported_svg = []
  6694. for obj in obj_selection:
  6695. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6696. scale_factor_x=None, scale_factor_y=None,
  6697. skew_factor_x=None, skew_factor_y=None,
  6698. mirror=None)
  6699. if obj.kind.lower() == 'gerber':
  6700. # color = self.defaults["gerber_plot_fill"][:-2]
  6701. color = obj.fill_color[:-2]
  6702. elif obj.kind.lower() == 'excellon':
  6703. color = '#C40000'
  6704. elif obj.kind.lower() == 'geometry':
  6705. color = self.defaults["global_draw_color"]
  6706. # Change the attributes of the exported SVG
  6707. # We don't need stroke-width
  6708. # We set opacity to maximum
  6709. # We set the colour to WHITE
  6710. root = ET.fromstring(svg_obj)
  6711. for child in root:
  6712. child.set('fill', str(color))
  6713. child.set('opacity', str(transparency_level))
  6714. child.set('stroke', str(color))
  6715. exported_svg.append(ET.tostring(root))
  6716. xmin = Inf
  6717. ymin = Inf
  6718. xmax = -Inf
  6719. ymax = -Inf
  6720. for obj in obj_selection:
  6721. try:
  6722. gxmin, gymin, gxmax, gymax = obj.bounds()
  6723. xmin = min([xmin, gxmin])
  6724. ymin = min([ymin, gymin])
  6725. xmax = max([xmax, gxmax])
  6726. ymax = max([ymax, gymax])
  6727. except Exception as e:
  6728. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6729. # Determine bounding area for svg export
  6730. bounds = [xmin, ymin, xmax, ymax]
  6731. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6732. # This contain the measure units
  6733. uom = obj_selection[0].units.lower()
  6734. # Define a boundary around SVG of about 1.0mm (~39mils)
  6735. if uom in "mm":
  6736. boundary = 1.0
  6737. else:
  6738. boundary = 0.0393701
  6739. # Convert everything to strings for use in the xml doc
  6740. svgwidth = str(size[0] + (2 * boundary))
  6741. svgheight = str(size[1] + (2 * boundary))
  6742. minx = str(bounds[0] - boundary)
  6743. miny = str(bounds[1] + boundary + size[1])
  6744. # Add a SVG Header and footer to the svg output from shapely
  6745. # The transform flips the Y Axis so that everything renders
  6746. # properly within svg apps such as inkscape
  6747. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6748. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6749. svg_header += 'width="' + svgwidth + uom + '" '
  6750. svg_header += 'height="' + svgheight + uom + '" '
  6751. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6752. svg_header += '>'
  6753. svg_header += '<g transform="scale(1,-1)">'
  6754. svg_footer = '</g> </svg>'
  6755. svg_elem = str(svg_header)
  6756. for svg_item in exported_svg:
  6757. svg_elem += str(svg_item)
  6758. svg_elem += str(svg_footer)
  6759. # Parse the xml through a xml parser just to add line feeds
  6760. # and to make it look more pretty for the output
  6761. doc = parse_xml_string(svg_elem)
  6762. doc_final = doc.toprettyxml()
  6763. try:
  6764. if self.defaults['units'].upper() == 'IN':
  6765. unit = inch
  6766. else:
  6767. unit = mm
  6768. doc_final = StringIO(doc_final)
  6769. drawing = svg2rlg(doc_final)
  6770. if p_size == 'Bounds':
  6771. renderPDF.drawToFile(drawing, file_name)
  6772. else:
  6773. if orientation == 'p':
  6774. page_size = portrait(self.pagesize[p_size])
  6775. else:
  6776. page_size = landscape(self.pagesize[p_size])
  6777. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6778. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6779. renderPDF.draw(drawing, my_canvas, 0, 0)
  6780. my_canvas.save()
  6781. except Exception as e:
  6782. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6783. return 'fail'
  6784. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6785. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6786. """
  6787. Exports a Geometry Object to an SVG file.
  6788. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6789. :param filename: Path to the SVG file to save to.
  6790. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6791. :return:
  6792. """
  6793. self.defaults.report_usage("export_svg()")
  6794. if filename is None:
  6795. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6796. is not None else self.defaults["global_last_folder"]
  6797. self.log.debug("export_svg()")
  6798. try:
  6799. obj = self.collection.get_by_name(str(obj_name))
  6800. except Exception:
  6801. # TODO: The return behavior has not been established... should raise exception?
  6802. return "Could not retrieve object: %s" % obj_name
  6803. with self.proc_container.new(_("Exporting SVG")) as proc:
  6804. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6805. # Determine bounding area for svg export
  6806. bounds = obj.bounds()
  6807. size = obj.size()
  6808. # Convert everything to strings for use in the xml doc
  6809. svgwidth = str(size[0])
  6810. svgheight = str(size[1])
  6811. minx = str(bounds[0])
  6812. miny = str(bounds[1] - size[1])
  6813. uom = obj.units.lower()
  6814. # Add a SVG Header and footer to the svg output from shapely
  6815. # The transform flips the Y Axis so that everything renders
  6816. # properly within svg apps such as inkscape
  6817. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6818. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6819. svg_header += 'width="' + svgwidth + uom + '" '
  6820. svg_header += 'height="' + svgheight + uom + '" '
  6821. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6822. svg_header += '<g transform="scale(1,-1)">'
  6823. svg_footer = '</g> </svg>'
  6824. svg_elem = svg_header + exported_svg + svg_footer
  6825. # Parse the xml through a xml parser just to add line feeds
  6826. # and to make it look more pretty for the output
  6827. svgcode = parse_xml_string(svg_elem)
  6828. svgcode = svgcode.toprettyxml()
  6829. try:
  6830. with open(filename, 'w') as fp:
  6831. fp.write(svgcode)
  6832. except PermissionError:
  6833. self.inform.emit('[WARNING] %s' %
  6834. _("Permission denied, saving not possible.\n"
  6835. "Most likely another app is holding the file open and not accessible."))
  6836. return 'fail'
  6837. if self.defaults["global_open_style"] is False:
  6838. self.file_opened.emit("SVG", filename)
  6839. self.file_saved.emit("SVG", filename)
  6840. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6841. def save_source_file(self, obj_name, filename, use_thread=True):
  6842. """
  6843. Exports a FlatCAM Object to an Gerber/Excellon file.
  6844. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6845. :param filename: Path to the Gerber file to save to.
  6846. :param use_thread: if to be run in a separate thread
  6847. :return:
  6848. """
  6849. self.defaults.report_usage("save source file()")
  6850. if filename is None:
  6851. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6852. is not None else self.defaults["global_last_folder"]
  6853. self.log.debug("save source file()")
  6854. obj = self.collection.get_by_name(obj_name)
  6855. file_string = StringIO(obj.source_file)
  6856. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6857. if file_string.getvalue() == '':
  6858. self.inform.emit('[ERROR_NOTCL] %s' %
  6859. _("Save cancelled because source file is empty. Try to export the file."))
  6860. return 'fail'
  6861. try:
  6862. with open(filename, 'w') as file:
  6863. file.writelines('G04*\n')
  6864. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6865. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6866. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6867. file.writelines('G04 Created on : %s*\n' % time_string)
  6868. for line in file_string:
  6869. file.writelines(line)
  6870. except PermissionError:
  6871. self.inform.emit('[WARNING] %s' %
  6872. _("Permission denied, saving not possible.\n"
  6873. "Most likely another app is holding the file open and not accessible."))
  6874. return 'fail'
  6875. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6876. """
  6877. Exports a Excellon Object to an Excellon file.
  6878. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6879. :param filename: Path to the Excellon file to save to.
  6880. :param local_use:
  6881. :param use_thread: if to be run in a separate thread
  6882. :return:
  6883. """
  6884. self.defaults.report_usage("export_excellon()")
  6885. if filename is None:
  6886. if self.defaults["global_last_save_folder"]:
  6887. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6888. else:
  6889. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6890. self.log.debug("export_excellon()")
  6891. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6892. self.defaults["excellon_exp_decimals"]
  6893. )
  6894. if local_use is None:
  6895. try:
  6896. obj = self.collection.get_by_name(str(obj_name))
  6897. except Exception:
  6898. return "Could not retrieve object: %s" % obj_name
  6899. else:
  6900. obj = local_use
  6901. if not isinstance(obj, ExcellonObject):
  6902. self.inform.emit('[ERROR_NOTCL] %s' %
  6903. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6904. return
  6905. # updated units
  6906. eunits = self.defaults["excellon_exp_units"]
  6907. ewhole = self.defaults["excellon_exp_integer"]
  6908. efract = self.defaults["excellon_exp_decimals"]
  6909. ezeros = self.defaults["excellon_exp_zeros"]
  6910. eformat = self.defaults["excellon_exp_format"]
  6911. slot_type = self.defaults["excellon_exp_slot_type"]
  6912. fc_units = self.defaults['units'].upper()
  6913. if fc_units == 'MM':
  6914. factor = 1 if eunits == 'METRIC' else 0.03937
  6915. else:
  6916. factor = 25.4 if eunits == 'METRIC' else 1
  6917. def make_excellon():
  6918. try:
  6919. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6920. header = 'M48\n'
  6921. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6922. (str(self.version), str(self.version_date))
  6923. header += ';Filename: %s' % str(obj_name) + '\n'
  6924. header += ';Created on : %s' % time_str + '\n'
  6925. if eformat == 'dec':
  6926. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6927. header += eunits + '\n'
  6928. for tool in obj.tools:
  6929. if eunits == 'METRIC':
  6930. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6931. tool=str(tool),
  6932. dec=2)
  6933. else:
  6934. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6935. tool=str(tool),
  6936. dec=4)
  6937. else:
  6938. if ezeros == 'LZ':
  6939. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6940. form='ndec', e_zeros='LZ', factor=factor,
  6941. slot_type=slot_type)
  6942. header += '%s,%s\n' % (eunits, 'LZ')
  6943. header += format_exc
  6944. for tool in obj.tools:
  6945. if eunits == 'METRIC':
  6946. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6947. float(obj.tools[tool]['tooldia']) * factor,
  6948. tool=str(tool),
  6949. dec=2)
  6950. else:
  6951. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6952. float(obj.tools[tool]['tooldia']) * factor,
  6953. tool=str(tool),
  6954. dec=4)
  6955. else:
  6956. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6957. form='ndec', e_zeros='TZ', factor=factor,
  6958. slot_type=slot_type)
  6959. header += '%s,%s\n' % (eunits, 'TZ')
  6960. header += format_exc
  6961. for tool in obj.tools:
  6962. if eunits == 'METRIC':
  6963. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6964. float(obj.tools[tool]['tooldia']) * factor,
  6965. tool=str(tool),
  6966. dec=2)
  6967. else:
  6968. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6969. float(obj.tools[tool]['tooldia']) * factor,
  6970. tool=str(tool),
  6971. dec=4)
  6972. header += '%\n'
  6973. footer = 'M30\n'
  6974. exported_excellon = header
  6975. exported_excellon += excellon_code
  6976. exported_excellon += footer
  6977. if local_use is None:
  6978. try:
  6979. with open(filename, 'w') as fp:
  6980. fp.write(exported_excellon)
  6981. except PermissionError:
  6982. self.inform.emit('[WARNING] %s' %
  6983. _("Permission denied, saving not possible.\n"
  6984. "Most likely another app is holding the file open and not accessible."))
  6985. return 'fail'
  6986. if self.defaults["global_open_style"] is False:
  6987. self.file_opened.emit("Excellon", filename)
  6988. self.file_saved.emit("Excellon", filename)
  6989. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6990. else:
  6991. return exported_excellon
  6992. except Exception as e:
  6993. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6994. return 'fail'
  6995. if use_thread is True:
  6996. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6997. def job_thread_exc(app_obj):
  6998. ret = make_excellon()
  6999. if ret == 'fail':
  7000. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7001. return
  7002. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7003. else:
  7004. eret = make_excellon()
  7005. if eret == 'fail':
  7006. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7007. return 'fail'
  7008. if local_use is not None:
  7009. return eret
  7010. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7011. """
  7012. Exports a Gerber Object to an Gerber file.
  7013. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7014. :param filename: Path to the Gerber file to save to.
  7015. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7016. When not None, the value will be the actual Gerber object for which to create
  7017. the Gerber code
  7018. :param use_thread: if to be run in a separate thread
  7019. :return:
  7020. """
  7021. self.defaults.report_usage("export_gerber()")
  7022. if filename is None:
  7023. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7024. is not None else self.defaults["global_last_folder"]
  7025. self.log.debug("export_gerber()")
  7026. if local_use is None:
  7027. try:
  7028. obj = self.collection.get_by_name(str(obj_name))
  7029. except Exception:
  7030. return 'fail'
  7031. else:
  7032. obj = local_use
  7033. # updated units
  7034. gunits = self.defaults["gerber_exp_units"]
  7035. gwhole = self.defaults["gerber_exp_integer"]
  7036. gfract = self.defaults["gerber_exp_decimals"]
  7037. gzeros = self.defaults["gerber_exp_zeros"]
  7038. fc_units = self.defaults['units'].upper()
  7039. if fc_units == 'MM':
  7040. factor = 1 if gunits == 'MM' else 0.03937
  7041. else:
  7042. factor = 25.4 if gunits == 'MM' else 1
  7043. def make_gerber():
  7044. try:
  7045. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7046. header = 'G04*\n'
  7047. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7048. (str(self.version), str(self.version_date))
  7049. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7050. header += 'G04 Created on : %s*' % time_str + '\n'
  7051. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7052. header += "%MO{units}*%\n".format(units=gunits)
  7053. for apid in obj.apertures:
  7054. if obj.apertures[apid]['type'] == 'C':
  7055. header += "%ADD{apid}{type},{size}*%\n".format(
  7056. apid=str(apid),
  7057. type='C',
  7058. size=(factor * obj.apertures[apid]['size'])
  7059. )
  7060. elif obj.apertures[apid]['type'] == 'R':
  7061. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7062. apid=str(apid),
  7063. type='R',
  7064. width=(factor * obj.apertures[apid]['width']),
  7065. height=(factor * obj.apertures[apid]['height'])
  7066. )
  7067. elif obj.apertures[apid]['type'] == 'O':
  7068. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7069. apid=str(apid),
  7070. type='O',
  7071. width=(factor * obj.apertures[apid]['width']),
  7072. height=(factor * obj.apertures[apid]['height'])
  7073. )
  7074. header += '\n'
  7075. # obsolete units but some software may need it
  7076. if gunits == 'IN':
  7077. header += 'G70*\n'
  7078. else:
  7079. header += 'G71*\n'
  7080. # Absolute Mode
  7081. header += 'G90*\n'
  7082. header += 'G01*\n'
  7083. # positive polarity
  7084. header += '%LPD*%\n'
  7085. footer = 'M02*\n'
  7086. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7087. exported_gerber = header
  7088. exported_gerber += gerber_code
  7089. exported_gerber += footer
  7090. if local_use is None:
  7091. try:
  7092. with open(filename, 'w') as fp:
  7093. fp.write(exported_gerber)
  7094. except PermissionError:
  7095. self.inform.emit('[WARNING] %s' %
  7096. _("Permission denied, saving not possible.\n"
  7097. "Most likely another app is holding the file open and not accessible."))
  7098. return 'fail'
  7099. if self.defaults["global_open_style"] is False:
  7100. self.file_opened.emit("Gerber", filename)
  7101. self.file_saved.emit("Gerber", filename)
  7102. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7103. else:
  7104. return exported_gerber
  7105. except Exception as e:
  7106. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7107. return 'fail'
  7108. if use_thread is True:
  7109. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7110. def job_thread_grb(app_obj):
  7111. ret = make_gerber()
  7112. if ret == 'fail':
  7113. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7114. return
  7115. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7116. else:
  7117. gret = make_gerber()
  7118. if gret == 'fail':
  7119. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7120. return 'fail'
  7121. if local_use is not None:
  7122. return gret
  7123. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  7124. """
  7125. Exports a Geometry Object to an DXF file.
  7126. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7127. :param filename: Path to the DXF file to save to.
  7128. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7129. When not None, the value will be the actual Geometry object for which to create
  7130. the Geometry/DXF code
  7131. :param use_thread: if to be run in a separate thread
  7132. :return:
  7133. """
  7134. self.defaults.report_usage("export_dxf()")
  7135. if filename is None:
  7136. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7137. is not None else self.defaults["global_last_folder"]
  7138. self.log.debug("export_dxf()")
  7139. if local_use is None:
  7140. try:
  7141. obj = self.collection.get_by_name(str(obj_name))
  7142. except Exception:
  7143. return 'fail'
  7144. else:
  7145. obj = local_use
  7146. def make_dxf():
  7147. try:
  7148. dxf_code = obj.export_dxf()
  7149. if local_use is None:
  7150. try:
  7151. dxf_code.saveas(filename)
  7152. except PermissionError:
  7153. self.inform.emit('[WARNING] %s' %
  7154. _("Permission denied, saving not possible.\n"
  7155. "Most likely another app is holding the file open and not accessible."))
  7156. return 'fail'
  7157. if self.defaults["global_open_style"] is False:
  7158. self.file_opened.emit("DXF", filename)
  7159. self.file_saved.emit("DXF", filename)
  7160. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7161. else:
  7162. return dxf_code
  7163. except Exception as e:
  7164. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  7165. return 'fail'
  7166. if use_thread is True:
  7167. with self.proc_container.new(_("Exporting DXF")) as proc:
  7168. def job_thread_exc(app_obj):
  7169. ret_dxf_val = make_dxf()
  7170. if ret_dxf_val == 'fail':
  7171. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7172. return
  7173. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7174. else:
  7175. ret = make_dxf()
  7176. if ret == 'fail':
  7177. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7178. return
  7179. if local_use is not None:
  7180. return ret
  7181. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7182. """
  7183. Adds a new Geometry Object to the projects and populates
  7184. it with shapes extracted from the SVG file.
  7185. :param plot: If True then the resulting object will be plotted on canvas
  7186. :param filename: Path to the SVG file.
  7187. :param geo_type: Type of FlatCAM object that will be created from SVG
  7188. :param outname: The name given to the resulting FlatCAM object
  7189. :return:
  7190. """
  7191. self.defaults.report_usage("import_svg()")
  7192. log.debug("App.import_svg()")
  7193. obj_type = ""
  7194. if geo_type is None or geo_type == "geometry":
  7195. obj_type = "geometry"
  7196. elif geo_type == "gerber":
  7197. obj_type = "gerber"
  7198. else:
  7199. self.inform.emit('[ERROR_NOTCL] %s' %
  7200. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7201. return
  7202. units = self.defaults['units'].upper()
  7203. def obj_init(geo_obj, app_obj):
  7204. geo_obj.import_svg(filename, obj_type, units=units)
  7205. geo_obj.multigeo = False
  7206. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7207. with self.proc_container.new(_("Importing SVG")) as proc:
  7208. # Object name
  7209. name = outname or filename.split('/')[-1].split('\\')[-1]
  7210. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7211. if ret == 'fail':
  7212. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7213. return 'fail'
  7214. # Register recent file
  7215. self.file_opened.emit("svg", filename)
  7216. # appGUI feedback
  7217. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7218. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7219. """
  7220. Adds a new Geometry Object to the projects and populates
  7221. it with shapes extracted from the DXF file.
  7222. :param filename: Path to the DXF file.
  7223. :param geo_type: Type of FlatCAM object that will be created from DXF
  7224. :param outname: Name for the imported Geometry
  7225. :param plot: If True then the resulting object will be plotted on canvas
  7226. :return:
  7227. """
  7228. log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  7229. obj_type = ""
  7230. if geo_type is None or geo_type == "geometry":
  7231. obj_type = "geometry"
  7232. elif geo_type == "gerber":
  7233. obj_type = geo_type
  7234. else:
  7235. self.inform.emit('[ERROR_NOTCL] %s' %
  7236. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7237. return
  7238. units = self.defaults['units'].upper()
  7239. def obj_init(geo_obj, app_obj):
  7240. if obj_type == "geometry":
  7241. geo_obj.import_dxf_as_geo(filename, units=units)
  7242. elif obj_type == "gerber":
  7243. geo_obj.import_dxf_as_gerber(filename, units=units)
  7244. else:
  7245. return "fail"
  7246. geo_obj.multigeo = True
  7247. with self.proc_container.new(_("Importing DXF")):
  7248. # Object name
  7249. name = outname or filename.split('/')[-1].split('\\')[-1]
  7250. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7251. if ret == 'fail':
  7252. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7253. return 'fail'
  7254. # Register recent file
  7255. self.file_opened.emit("dxf", filename)
  7256. # appGUI feedback
  7257. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7258. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7259. """
  7260. Opens a Gerber file, parses it and creates a new object for
  7261. it in the program. Thread-safe.
  7262. :param outname: Name of the resulting object. None causes the
  7263. name to be that of the file. Str.
  7264. :param filename: Gerber file filename
  7265. :type filename: str
  7266. :param plot: boolean, to plot or not the resulting object
  7267. :param from_tcl: True if run from Tcl Shell
  7268. :return: None
  7269. """
  7270. # How the object should be initialized
  7271. def obj_init(gerber_obj, app_obj):
  7272. assert isinstance(gerber_obj, GerberObject), \
  7273. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7274. # Opening the file happens here
  7275. try:
  7276. gerber_obj.parse_file(filename)
  7277. except IOError:
  7278. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7279. return "fail"
  7280. except ParseError as err:
  7281. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7282. app_obj.log.error(str(err))
  7283. return "fail"
  7284. except Exception as e:
  7285. log.debug("App.open_gerber() --> %s" % str(e))
  7286. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7287. msg += traceback.format_exc()
  7288. app_obj.inform.emit(msg)
  7289. return "fail"
  7290. if gerber_obj.is_empty():
  7291. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7292. _("Object is not Gerber file or empty. Aborting object creation."))
  7293. return "fail"
  7294. App.log.debug("open_gerber()")
  7295. with self.proc_container.new(_("Opening Gerber")):
  7296. # Object name
  7297. name = outname or filename.split('/')[-1].split('\\')[-1]
  7298. # # ## Object creation # ##
  7299. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7300. if ret_val == 'fail':
  7301. if from_tcl:
  7302. filename = self.defaults['global_tcl_path'] + '/' + name
  7303. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7304. if ret_val == 'fail':
  7305. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7306. return 'fail'
  7307. # Register recent file
  7308. self.file_opened.emit("gerber", filename)
  7309. # appGUI feedback
  7310. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7311. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7312. """
  7313. Opens an Excellon file, parses it and creates a new object for
  7314. it in the program. Thread-safe.
  7315. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7316. :param filename: Excellon file filename
  7317. :type filename: str
  7318. :param plot: boolean, to plot or not the resulting object
  7319. :param from_tcl: True if run from Tcl Shell
  7320. :return: None
  7321. """
  7322. App.log.debug("open_excellon()")
  7323. # How the object should be initialized
  7324. def obj_init(excellon_obj, app_obj):
  7325. try:
  7326. ret = excellon_obj.parse_file(filename=filename)
  7327. if ret == "fail":
  7328. log.debug("Excellon parsing failed.")
  7329. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  7330. return "fail"
  7331. except IOError:
  7332. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  7333. log.debug("Could not open Excellon object.")
  7334. return "fail"
  7335. except Exception:
  7336. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7337. msg += traceback.format_exc()
  7338. app_obj.inform.emit(msg)
  7339. return "fail"
  7340. ret = excellon_obj.create_geometry()
  7341. if ret == 'fail':
  7342. log.debug("Could not create geometry for Excellon object.")
  7343. return "fail"
  7344. for tool in excellon_obj.tools:
  7345. if excellon_obj.tools[tool]['solid_geometry']:
  7346. return
  7347. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7348. return "fail"
  7349. with self.proc_container.new(_("Opening Excellon.")):
  7350. # Object name
  7351. name = outname or filename.split('/')[-1].split('\\')[-1]
  7352. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7353. if ret_val == 'fail':
  7354. if from_tcl:
  7355. filename = self.defaults['global_tcl_path'] + '/' + name
  7356. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7357. if ret_val == 'fail':
  7358. self.inform.emit('[ERROR_NOTCL] %s' %
  7359. _('Open Excellon file failed. Probable not an Excellon file.'))
  7360. return
  7361. # Register recent file
  7362. self.file_opened.emit("excellon", filename)
  7363. # appGUI feedback
  7364. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7365. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7366. """
  7367. Opens a G-gcode file, parses it and creates a new object for
  7368. it in the program. Thread-safe.
  7369. :param filename: G-code file filename
  7370. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7371. :param force_parsing:
  7372. :param plot: If True plot the object on canvas
  7373. :param from_tcl: True if run from Tcl Shell
  7374. :return: None
  7375. """
  7376. App.log.debug("open_gcode()")
  7377. # How the object should be initialized
  7378. def obj_init(job_obj, app_obj_):
  7379. """
  7380. :param job_obj: the resulting object
  7381. :type app_obj_: App
  7382. """
  7383. assert isinstance(app_obj_, App), \
  7384. "Initializer expected App, got %s" % type(app_obj_)
  7385. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7386. try:
  7387. f = open(filename)
  7388. gcode = f.read()
  7389. f.close()
  7390. except IOError:
  7391. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7392. return "fail"
  7393. job_obj.gcode = gcode
  7394. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7395. if gcode_ret == "fail":
  7396. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7397. return "fail"
  7398. job_obj.create_geometry()
  7399. with self.proc_container.new(_("Opening G-Code.")):
  7400. # Object name
  7401. name = outname or filename.split('/')[-1].split('\\')[-1]
  7402. # New object creation and file processing
  7403. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7404. if ret_val == 'fail':
  7405. if from_tcl:
  7406. filename = self.defaults['global_tcl_path'] + '/' + name
  7407. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7408. if ret_val == 'fail':
  7409. self.inform.emit('[ERROR_NOTCL] %s' %
  7410. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7411. "Try to load it from File menu.\n "
  7412. "Attempting to create a FlatCAM CNCJob Object from "
  7413. "G-Code file failed during processing"))
  7414. return "fail"
  7415. # Register recent file
  7416. self.file_opened.emit("cncjob", filename)
  7417. # appGUI feedback
  7418. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7419. def open_hpgl2(self, filename, outname=None):
  7420. """
  7421. Opens a HPGL2 file, parses it and creates a new object for
  7422. it in the program. Thread-safe.
  7423. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7424. :param filename: HPGL2 file filename
  7425. :return: None
  7426. """
  7427. filename = filename
  7428. # How the object should be initialized
  7429. def obj_init(geo_obj, app_obj):
  7430. assert isinstance(geo_obj, GeometryObject), \
  7431. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7432. # Opening the file happens here
  7433. obj = HPGL2(self)
  7434. try:
  7435. HPGL2.parse_file(obj, filename)
  7436. except IOError:
  7437. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7438. return "fail"
  7439. except ParseError as err:
  7440. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7441. app_obj.log.error(str(err))
  7442. return "fail"
  7443. except Exception as e:
  7444. log.debug("App.open_hpgl2() --> %s" % str(e))
  7445. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7446. msg += traceback.format_exc()
  7447. app_obj.inform.emit(msg)
  7448. return "fail"
  7449. geo_obj.multigeo = True
  7450. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7451. geo_obj.tools = deepcopy(obj.tools)
  7452. geo_obj.source_file = deepcopy(obj.source_file)
  7453. del obj
  7454. if not geo_obj.solid_geometry:
  7455. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7456. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7457. return "fail"
  7458. App.log.debug("open_hpgl2()")
  7459. with self.proc_container.new(_("Opening HPGL2")):
  7460. # Object name
  7461. name = outname or filename.split('/')[-1].split('\\')[-1]
  7462. # # ## Object creation # ##
  7463. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7464. if ret == 'fail':
  7465. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7466. return 'fail'
  7467. # Register recent file
  7468. self.file_opened.emit("geometry", filename)
  7469. # appGUI feedback
  7470. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7471. def open_script(self, filename, outname=None, silent=False):
  7472. """
  7473. Opens a Script file, parses it and creates a new object for
  7474. it in the program. Thread-safe.
  7475. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7476. :param filename: Script file filename
  7477. :param silent: If True there will be no messages printed to StatusBar
  7478. :return: None
  7479. """
  7480. def obj_init(script_obj, app_obj):
  7481. assert isinstance(script_obj, ScriptObject), \
  7482. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7483. if silent is False:
  7484. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7485. try:
  7486. script_obj.parse_file(filename)
  7487. except IOError:
  7488. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7489. return "fail"
  7490. except ParseError as err:
  7491. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7492. app_obj.log.error(str(err))
  7493. return "fail"
  7494. except Exception as e:
  7495. log.debug("App.open_script() -> %s" % str(e))
  7496. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7497. msg += traceback.format_exc()
  7498. app_obj.inform.emit(msg)
  7499. return "fail"
  7500. App.log.debug("open_script()")
  7501. with self.proc_container.new(_("Opening TCL Script...")):
  7502. # Object name
  7503. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7504. # Object creation
  7505. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7506. if ret_val == 'fail':
  7507. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7508. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7509. if ret_val == 'fail':
  7510. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7511. return 'fail'
  7512. # Register recent file
  7513. self.file_opened.emit("script", filename)
  7514. # appGUI feedback
  7515. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7516. def open_config_file(self, filename, run_from_arg=None):
  7517. """
  7518. Loads a config file from the specified file.
  7519. :param filename: Name of the file from which to load.
  7520. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7521. :return: None
  7522. """
  7523. App.log.debug("Opening config file: " + filename)
  7524. if run_from_arg:
  7525. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7526. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7527. _("Opening FlatCAM Config file.")),
  7528. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7529. color=QtGui.QColor("gray"))
  7530. # # add the tab if it was closed
  7531. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7532. # # first clear previous text in text editor (if any)
  7533. # self.ui.text_editor_tab.code_editor.clear()
  7534. #
  7535. # # Switch plot_area to CNCJob tab
  7536. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7537. # close the Code editor if already open
  7538. if self.toggle_codeeditor:
  7539. self.on_toggle_code_editor()
  7540. self.on_toggle_code_editor()
  7541. try:
  7542. if filename:
  7543. f = QtCore.QFile(filename)
  7544. if f.open(QtCore.QIODevice.ReadOnly):
  7545. stream = QtCore.QTextStream(f)
  7546. code_edited = stream.readAll()
  7547. self.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  7548. f.close()
  7549. except IOError:
  7550. App.log.error("Failed to open config file: %s" % filename)
  7551. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7552. (_("Failed to open config file"), filename))
  7553. return
  7554. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7555. """
  7556. Loads a project from the specified file.
  7557. 1) Loads and parses file
  7558. 2) Registers the file as recently opened.
  7559. 3) Calls on_file_new()
  7560. 4) Updates options
  7561. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7562. 6) Calls plot_all() if plot=True
  7563. :param filename: Name of the file from which to load.
  7564. :param run_from_arg: True if run for arguments
  7565. :param plot: If True plot all objects in the project
  7566. :param cli: Run from command line
  7567. :param from_tcl: True if run from Tcl Sehll
  7568. :return: None
  7569. """
  7570. App.log.debug("Opening project: " + filename)
  7571. # block autosaving while a project is loaded
  7572. self.block_autosave = True
  7573. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7574. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7575. if cli is None:
  7576. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7577. if run_from_arg:
  7578. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7579. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7580. _("Opening FlatCAM Project file.")),
  7581. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7582. color=QtGui.QColor("gray"))
  7583. # Open and parse an uncompressed Project file
  7584. try:
  7585. f = open(filename, 'r')
  7586. except IOError:
  7587. if from_tcl:
  7588. name = filename.split('/')[-1].split('\\')[-1]
  7589. filename = self.defaults['global_tcl_path'] + '/' + name
  7590. try:
  7591. f = open(filename, 'r')
  7592. except IOError:
  7593. log.error("Failed to open project file: %s" % filename)
  7594. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7595. return
  7596. else:
  7597. log.error("Failed to open project file: %s" % filename)
  7598. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7599. return
  7600. try:
  7601. d = json.load(f, object_hook=dict2obj)
  7602. except Exception as e:
  7603. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7604. (filename, str(e)))
  7605. f.close()
  7606. # Open and parse a compressed Project file
  7607. try:
  7608. with lzma.open(filename) as f:
  7609. file_content = f.read().decode('utf-8')
  7610. d = json.loads(file_content, object_hook=dict2obj)
  7611. except Exception as e:
  7612. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7613. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7614. return
  7615. # Clear the current project
  7616. # # NOT THREAD SAFE # ##
  7617. if run_from_arg is True:
  7618. pass
  7619. elif cli is True:
  7620. self.delete_selection_shape()
  7621. else:
  7622. self.on_file_new()
  7623. # Project options
  7624. self.options.update(d['options'])
  7625. self.project_filename = filename
  7626. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7627. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7628. if cli is None:
  7629. self.set_screen_units(self.options["units"])
  7630. # Re create objects
  7631. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7632. for obj in d['objs']:
  7633. def obj_init(obj_inst, app_inst):
  7634. try:
  7635. obj_inst.from_dict(obj)
  7636. except Exception as e:
  7637. print('App.open_project() --> ' + str(e))
  7638. return 'fail'
  7639. App.log.debug("Recreating from opened project an %s object: %s" %
  7640. (obj['kind'].capitalize(), obj['options']['name']))
  7641. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7642. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7643. if cli is None:
  7644. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7645. obj['kind'].upper(),
  7646. obj['options']['name']
  7647. )
  7648. )
  7649. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7650. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7651. self.should_we_save = False
  7652. self.file_opened.emit("project", filename)
  7653. # restore autosaving after a project was loaded
  7654. self.block_autosave = False
  7655. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7656. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7657. if cli is None:
  7658. self.set_ui_title(name=self.project_filename)
  7659. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7660. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7661. """
  7662. Re-generates all plots from all objects.
  7663. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7664. :param muted: if True don't print messages
  7665. :param use_thread: if True will use threading for plotting the objects
  7666. :return: None
  7667. """
  7668. self.log.debug("Plot_all()")
  7669. if muted is not True:
  7670. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7671. for plot_obj in self.collection.get_list():
  7672. def worker_task(obj):
  7673. with self.proc_container.new("Plotting"):
  7674. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7675. if fit_view is True:
  7676. self.app_obj.object_plotted.emit(obj)
  7677. if use_thread is True:
  7678. # Send to worker
  7679. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7680. else:
  7681. worker_task(plot_obj)
  7682. def register_folder(self, filename):
  7683. """
  7684. Register the last folder used by the app to open something
  7685. :param filename: the last folder is extracted from the filename
  7686. :return: None
  7687. """
  7688. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7689. def register_save_folder(self, filename):
  7690. """
  7691. Register the last folder used by the app to save something
  7692. :param filename: the last folder is extracted from the filename
  7693. :return: None
  7694. """
  7695. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7696. # def set_progress_bar(self, percentage, text=""):
  7697. # """
  7698. # Set a progress bar to a value (percentage)
  7699. #
  7700. # :param percentage: Value set to the progressbar
  7701. # :param text: Not used
  7702. # :return: None
  7703. # """
  7704. # self.ui.progress_bar.setValue(int(percentage))
  7705. def setup_recent_items(self):
  7706. """
  7707. Setup a dictionary with the recent files accessed, organized by type
  7708. :return:
  7709. """
  7710. icons = {
  7711. "gerber": self.resource_location + "/flatcam_icon16.png",
  7712. "excellon": self.resource_location + "/drill16.png",
  7713. 'geometry': self.resource_location + "/geometry16.png",
  7714. "cncjob": self.resource_location + "/cnc16.png",
  7715. "script": self.resource_location + "/script_new24.png",
  7716. "document": self.resource_location + "/notes16_1.png",
  7717. "project": self.resource_location + "/project16.png",
  7718. "svg": self.resource_location + "/geometry16.png",
  7719. "dxf": self.resource_location + "/dxf16.png",
  7720. "pdf": self.resource_location + "/pdf32.png",
  7721. "image": self.resource_location + "/image16.png"
  7722. }
  7723. try:
  7724. image_opener = self.image_tool.import_image
  7725. except AttributeError:
  7726. image_opener = None
  7727. openers = {
  7728. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7729. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7730. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7731. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7732. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7733. "document": None,
  7734. 'project': self.open_project,
  7735. 'svg': self.import_svg,
  7736. 'dxf': self.import_dxf,
  7737. 'image': image_opener,
  7738. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7739. }
  7740. # Open recent file for files
  7741. try:
  7742. f = open(self.data_path + '/recent.json')
  7743. except IOError:
  7744. App.log.error("Failed to load recent item list.")
  7745. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7746. return
  7747. try:
  7748. self.recent = json.load(f)
  7749. except json.errors.JSONDecodeError:
  7750. App.log.error("Failed to parse recent item list.")
  7751. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7752. f.close()
  7753. return
  7754. f.close()
  7755. # Open recent file for projects
  7756. try:
  7757. fp = open(self.data_path + '/recent_projects.json')
  7758. except IOError:
  7759. App.log.error("Failed to load recent project item list.")
  7760. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7761. return
  7762. try:
  7763. self.recent_projects = json.load(fp)
  7764. except json.errors.JSONDecodeError:
  7765. App.log.error("Failed to parse recent project item list.")
  7766. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7767. fp.close()
  7768. return
  7769. fp.close()
  7770. # Closure needed to create callbacks in a loop.
  7771. # Otherwise late binding occurs.
  7772. def make_callback(func, fname):
  7773. def opener():
  7774. func(fname)
  7775. return opener
  7776. def reset_recent_files():
  7777. # Reset menu
  7778. self.ui.recent.clear()
  7779. self.recent = []
  7780. try:
  7781. ff = open(self.data_path + '/recent.json', 'w')
  7782. except IOError:
  7783. App.log.error("Failed to open recent items file for writing.")
  7784. return
  7785. json.dump(self.recent, ff)
  7786. def reset_recent_projects():
  7787. # Reset menu
  7788. self.ui.recent_projects.clear()
  7789. self.recent_projects = []
  7790. try:
  7791. frp = open(self.data_path + '/recent_projects.json', 'w')
  7792. except IOError:
  7793. App.log.error("Failed to open recent projects items file for writing.")
  7794. return
  7795. json.dump(self.recent, frp)
  7796. # Reset menu
  7797. self.ui.recent.clear()
  7798. self.ui.recent_projects.clear()
  7799. # Create menu items for projects
  7800. for recent in self.recent_projects:
  7801. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7802. if recent['kind'] == 'project':
  7803. try:
  7804. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7805. # Attach callback
  7806. o = make_callback(openers[recent["kind"]], recent['filename'])
  7807. action.triggered.connect(o)
  7808. self.ui.recent_projects.addAction(action)
  7809. except KeyError:
  7810. App.log.error("Unsupported file type: %s" % recent["kind"])
  7811. # Last action in Recent Files menu is one that Clear the content
  7812. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7813. (_("Clear Recent projects")), self)
  7814. clear_action_proj.triggered.connect(reset_recent_projects)
  7815. self.ui.recent_projects.addSeparator()
  7816. self.ui.recent_projects.addAction(clear_action_proj)
  7817. # Create menu items for files
  7818. for recent in self.recent:
  7819. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7820. if recent['kind'] != 'project':
  7821. try:
  7822. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7823. # Attach callback
  7824. o = make_callback(openers[recent["kind"]], recent['filename'])
  7825. action.triggered.connect(o)
  7826. self.ui.recent.addAction(action)
  7827. except KeyError:
  7828. App.log.error("Unsupported file type: %s" % recent["kind"])
  7829. # Last action in Recent Files menu is one that Clear the content
  7830. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7831. (_("Clear Recent files")), self)
  7832. clear_action.triggered.connect(reset_recent_files)
  7833. self.ui.recent.addSeparator()
  7834. self.ui.recent.addAction(clear_action)
  7835. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7836. # self.ui.menufilerecent.set_submenu(recent_menu)
  7837. # recent_menu.show_all()
  7838. # self.ui.recent.show()
  7839. self.log.debug("Recent items list has been populated.")
  7840. def setup_component_editor(self):
  7841. """
  7842. Default text for the Selected tab when is not taken by the Object UI.
  7843. :return:
  7844. """
  7845. # label = QtWidgets.QLabel("Choose an item from Project")
  7846. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7847. sel_title = QtWidgets.QTextEdit(
  7848. _('<b>Shortcut Key List</b>'))
  7849. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7850. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7851. f_settings = QSettings("Open Source", "FlatCAM")
  7852. if f_settings.contains("notebook_font_size"):
  7853. fsize = f_settings.value('notebook_font_size', type=int)
  7854. else:
  7855. fsize = 12
  7856. tsize = fsize + int(fsize / 2)
  7857. # selected_text = (_('''
  7858. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7859. # </p>
  7860. #
  7861. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7862. # The normal flow when working in FlatCAM is the following:</span></p>
  7863. #
  7864. # <ol>
  7865. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7866. # file into
  7867. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7868. # even dragging and dropping the files on the appGUI.<br />
  7869. # <br />
  7870. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7871. # drop of the
  7872. # file into the FLATCAM appGUI or through the menu/toolbar links offered within the app.</span><br />
  7873. # &nbsp;</li>
  7874. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7875. # and then
  7876. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7877. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7878. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7879. # <br />
  7880. # If the selection of the object is done on the canvas by single click instead, and the
  7881. # <strong>SELECTED TAB</strong>
  7882. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7883. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7884. # it even if it was out of focus.<br />
  7885. # <br />
  7886. # You can change the parameters in this screen and the flow direction is like this:<br />
  7887. # <br />
  7888. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7889. # <strong> Geometry Object
  7890. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7891. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7892. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7893. # </ol>
  7894. #
  7895. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7896. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7897. # <strong>F3</strong>.</span></p>
  7898. #
  7899. # ''').format(fsize=fsize, tsize=tsize))
  7900. selected_text = '''
  7901. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7902. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7903. {s1}</span></p>
  7904. <ol>
  7905. <li><span style="font-size:{fsize}px">{s2}<br />
  7906. <br />
  7907. {s3}</span><br />
  7908. &nbsp;</li>
  7909. <li><span style="font-size:{fsize}px">{s4}<br />
  7910. &nbsp;</li>
  7911. <br />
  7912. <li><span style="font-size:{fsize}px">{s5}<br />
  7913. &nbsp;</li>
  7914. <br />
  7915. <li><span style="font-size:{fsize}px">{s6}<br />
  7916. <br />
  7917. {s7}</span></li>
  7918. </ol>
  7919. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7920. '''.format(
  7921. title=_("Selected Tab - Choose an Item from Project Tab"),
  7922. subtitle=_("Details"),
  7923. s1=_("The normal flow when working with the application is the following:"),
  7924. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into the application "
  7925. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7926. "files on the GUI."),
  7927. s3=_("You can also load a project by double clicking on the project file, "
  7928. "drag and drop of the file into the GUI or through the menu (or toolbar) "
  7929. "actions offered within the app."),
  7930. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7931. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7932. "SELECTED TAB will be updated with the object properties according to its kind: "
  7933. "Gerber, Excellon, Geometry or CNCJob object."),
  7934. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7935. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7936. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7937. "the SELECTED TAB and populate it even if it was out of focus."),
  7938. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7939. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7940. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7941. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7942. "(again, done in SELECTED TAB) --> Save GCode."),
  7943. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7944. "or through its own key shortcut: <b>F3</b>."),
  7945. tsize=tsize,
  7946. fsize=fsize
  7947. )
  7948. sel_title.setText(selected_text)
  7949. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7950. self.ui.selected_scroll_area.setWidget(sel_title)
  7951. def setup_obj_classes(self):
  7952. """
  7953. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7954. class.
  7955. :return: None
  7956. """
  7957. FlatCAMObj.app = self
  7958. ObjectCollection.app = self
  7959. Gerber.app = self
  7960. Excellon.app = self
  7961. Geometry.app = self
  7962. CNCjob.app = self
  7963. FCProcess.app = self
  7964. FCProcessContainer.app = self
  7965. OptionsGroupUI.app = self
  7966. def version_check(self):
  7967. """
  7968. Checks for the latest version of the program. Alerts the
  7969. user if theirs is outdated. This method is meant to be run
  7970. in a separate thread.
  7971. :return: None
  7972. """
  7973. self.log.debug("version_check()")
  7974. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7975. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7976. App.version_url,
  7977. str(self.defaults['global_serial']),
  7978. str(self.version),
  7979. str(self.os),
  7980. urllib.parse.urlencode(self.defaults["global_stats"])
  7981. )
  7982. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7983. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7984. # urllib.parse.urlencode(self.defaults["global_stats"])
  7985. else:
  7986. # no_stats dict; just so it won't break things on website
  7987. no_ststs_dict = {}
  7988. no_ststs_dict["global_ststs"] = {}
  7989. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7990. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7991. App.log.debug("Checking for updates @ %s" % full_url)
  7992. # ## Get the data
  7993. try:
  7994. f = urllib.request.urlopen(full_url)
  7995. except Exception:
  7996. # App.log.warning("Failed checking for latest version. Could not connect.")
  7997. self.log.warning("Failed checking for latest version. Could not connect.")
  7998. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7999. return
  8000. try:
  8001. data = json.load(f)
  8002. except Exception as e:
  8003. App.log.error("Could not parse information about latest version.")
  8004. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8005. App.log.debug("json.load(): %s" % str(e))
  8006. f.close()
  8007. return
  8008. f.close()
  8009. # ## Latest version?
  8010. if self.version >= data["version"]:
  8011. App.log.debug("FlatCAM is up to date!")
  8012. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8013. return
  8014. App.log.debug("Newer version available.")
  8015. self.message.emit(
  8016. _("Newer Version Available"),
  8017. '%s<br><br>><b>%s</b><br>%s' % (
  8018. _("There is a newer version of FlatCAM available for download:"),
  8019. str(data["name"]),
  8020. str(data["message"])
  8021. ),
  8022. _("info")
  8023. )
  8024. def on_plotcanvas_setup(self, container=None):
  8025. """
  8026. This is doing the setup for the plot area (canvas).
  8027. :param container: QT Widget where to install the canvas
  8028. :return: None
  8029. """
  8030. if container:
  8031. plot_container = container
  8032. else:
  8033. plot_container = self.ui.right_layout
  8034. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8035. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8036. self.is_legacy = True
  8037. self.defaults["global_graphic_engine"] = "2D"
  8038. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8039. else:
  8040. try:
  8041. self.plotcanvas = PlotCanvas(plot_container, self)
  8042. except Exception as er:
  8043. msg_txt = traceback.format_exc()
  8044. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8045. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8046. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8047. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8048. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8049. msg += msg_txt
  8050. self.inform.emit(msg)
  8051. return 'fail'
  8052. # So it can receive key presses
  8053. self.plotcanvas.native.setFocus()
  8054. if self.is_legacy is False:
  8055. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8056. # Set the mouse button for panning
  8057. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8058. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8059. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8060. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8061. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8062. # Keys over plot enabled
  8063. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8064. if self.defaults['global_cursor_type'] == 'small':
  8065. self.app_cursor = self.plotcanvas.new_cursor()
  8066. else:
  8067. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8068. if self.ui.grid_snap_btn.isChecked():
  8069. self.app_cursor.enabled = True
  8070. else:
  8071. self.app_cursor.enabled = False
  8072. if self.is_legacy is False:
  8073. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8074. else:
  8075. # will use the default Matplotlib axes
  8076. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8077. def on_zoom_fit(self):
  8078. """
  8079. Callback for zoom-fit request. This can be either from the corresponding
  8080. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8081. with axes limits from the geometry bounds of all objects.
  8082. :return: None
  8083. """
  8084. if self.is_legacy is False:
  8085. self.plotcanvas.fit_view()
  8086. else:
  8087. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8088. width = xmax - xmin
  8089. height = ymax - ymin
  8090. xmin -= 0.05 * width
  8091. xmax += 0.05 * width
  8092. ymin -= 0.05 * height
  8093. ymax += 0.05 * height
  8094. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8095. def on_zoom_in(self):
  8096. """
  8097. Callback for zoom-in request.
  8098. :return:
  8099. """
  8100. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8101. def on_zoom_out(self):
  8102. """
  8103. Callback for zoom-out request.
  8104. :return:
  8105. """
  8106. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8107. def disable_all_plots(self):
  8108. self.defaults.report_usage("disable_all_plots()")
  8109. self.disable_plots(self.collection.get_list())
  8110. self.inform.emit('[success] %s' %
  8111. _("All plots disabled."))
  8112. def disable_other_plots(self):
  8113. self.defaults.report_usage("disable_other_plots()")
  8114. self.disable_plots(self.collection.get_non_selected())
  8115. self.inform.emit('[success] %s' %
  8116. _("All non selected plots disabled."))
  8117. def enable_all_plots(self):
  8118. self.defaults.report_usage("enable_all_plots()")
  8119. self.enable_plots(self.collection.get_list())
  8120. self.inform.emit('[success] %s' %
  8121. _("All plots enabled."))
  8122. def on_enable_sel_plots(self):
  8123. log.debug("App.on_enable_sel_plot()")
  8124. object_list = self.collection.get_selected()
  8125. self.enable_plots(objects=object_list)
  8126. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8127. def on_disable_sel_plots(self):
  8128. log.debug("App.on_disable_sel_plot()")
  8129. # self.inform.emit(_("Disabling plots ..."))
  8130. object_list = self.collection.get_selected()
  8131. self.disable_plots(objects=object_list)
  8132. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8133. def enable_plots(self, objects):
  8134. """
  8135. Enable plots
  8136. :param objects: list of Objects to be enabled
  8137. :return:
  8138. """
  8139. log.debug("Enabling plots ...")
  8140. # self.inform.emit(_("Working ..."))
  8141. for obj in objects:
  8142. if obj.options['plot'] is False:
  8143. obj.options.set_change_callback(lambda x: None)
  8144. obj.options['plot'] = True
  8145. try:
  8146. # only the Gerber obj has on_plot_cb_click() method
  8147. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8148. # disable this cb while disconnected,
  8149. # in case the operation takes time the user is not allowed to change it
  8150. obj.ui.plot_cb.setDisabled(True)
  8151. except AttributeError:
  8152. pass
  8153. obj.set_form_item("plot")
  8154. try:
  8155. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8156. obj.ui.plot_cb.setDisabled(False)
  8157. except AttributeError:
  8158. pass
  8159. obj.options.set_change_callback(obj.on_options_change)
  8160. def worker_task(objs):
  8161. with self.proc_container.new(_("Enabling plots ...")):
  8162. for plot_obj in objs:
  8163. # obj.options['plot'] = True
  8164. if isinstance(plot_obj, CNCJobObject):
  8165. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8166. else:
  8167. plot_obj.plot(visible=True)
  8168. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8169. def disable_plots(self, objects):
  8170. """
  8171. Disables plots
  8172. :param objects: list of Objects to be disabled
  8173. :return:
  8174. """
  8175. # if no objects selected then do nothing
  8176. if not self.collection.get_selected():
  8177. return
  8178. log.debug("Disabling plots ...")
  8179. # self.inform.emit(_("Working ..."))
  8180. for obj in objects:
  8181. if obj.options['plot'] is True:
  8182. obj.options.set_change_callback(lambda x: None)
  8183. obj.options['plot'] = False
  8184. try:
  8185. # only the Gerber obj has on_plot_cb_click() method
  8186. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8187. obj.ui.plot_cb.setDisabled(True)
  8188. except AttributeError:
  8189. pass
  8190. obj.set_form_item("plot")
  8191. try:
  8192. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8193. obj.ui.plot_cb.setDisabled(False)
  8194. except AttributeError:
  8195. pass
  8196. obj.options.set_change_callback(obj.on_options_change)
  8197. try:
  8198. self.delete_selection_shape()
  8199. except Exception as e:
  8200. log.debug("App.disable_plots() --> %s" % str(e))
  8201. def worker_task(objs):
  8202. with self.proc_container.new(_("Disabling plots ...")):
  8203. for plot_obj in objs:
  8204. # obj.options['plot'] = True
  8205. if isinstance(plot_obj, CNCJobObject):
  8206. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8207. else:
  8208. plot_obj.plot(visible=False)
  8209. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8210. def toggle_plots(self, objects):
  8211. """
  8212. Toggle plots visibility
  8213. :param objects: list of Objects for which to be toggled the visibility
  8214. :return: None
  8215. """
  8216. # if no objects selected then do nothing
  8217. if not self.collection.get_selected():
  8218. return
  8219. log.debug("Toggling plots ...")
  8220. self.inform.emit(_("Working ..."))
  8221. for obj in objects:
  8222. if obj.options['plot'] is False:
  8223. obj.options['plot'] = True
  8224. else:
  8225. obj.options['plot'] = False
  8226. self.app_obj.plots_updated.emit()
  8227. def clear_plots(self):
  8228. """
  8229. Clear the plots
  8230. :return: None
  8231. """
  8232. objects = self.collection.get_list()
  8233. for obj in objects:
  8234. obj.clear(obj == objects[-1])
  8235. # Clear pool to free memory
  8236. self.clear_pool()
  8237. def on_set_color_action_triggered(self):
  8238. """
  8239. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8240. :return:
  8241. """
  8242. new_color = self.defaults['gerber_plot_fill']
  8243. clicked_action = self.sender()
  8244. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8245. act_name = clicked_action.text()
  8246. sel_obj_list = self.collection.get_selected()
  8247. if not sel_obj_list:
  8248. return
  8249. # a default value, I just chose this one
  8250. alpha_level = 'BF'
  8251. for sel_obj in sel_obj_list:
  8252. if sel_obj.kind == 'excellon':
  8253. alpha_level = str(hex(
  8254. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  8255. elif sel_obj.kind == 'gerber':
  8256. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  8257. elif sel_obj.kind == 'geometry':
  8258. alpha_level = 'FF'
  8259. else:
  8260. log.debug(
  8261. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8262. continue
  8263. sel_obj.alpha_level = alpha_level
  8264. if act_name == _('Red'):
  8265. new_color = '#FF0000' + alpha_level
  8266. if act_name == _('Blue'):
  8267. new_color = '#0000FF' + alpha_level
  8268. if act_name == _('Yellow'):
  8269. new_color = '#FFDF00' + alpha_level
  8270. if act_name == _('Green'):
  8271. new_color = '#00FF00' + alpha_level
  8272. if act_name == _('Purple'):
  8273. new_color = '#FF00FF' + alpha_level
  8274. if act_name == _('Brown'):
  8275. new_color = '#A52A2A' + alpha_level
  8276. if act_name == _('White'):
  8277. new_color = '#FFFFFF' + alpha_level
  8278. if act_name == _('Black'):
  8279. new_color = '#000000' + alpha_level
  8280. if act_name == _('Custom'):
  8281. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8282. c_dialog = QtWidgets.QColorDialog()
  8283. plot_fill_color = c_dialog.getColor(initial=new_color)
  8284. if plot_fill_color.isValid() is False:
  8285. return
  8286. new_color = str(plot_fill_color.name()) + alpha_level
  8287. if act_name == _("Default"):
  8288. for sel_obj in sel_obj_list:
  8289. if sel_obj.kind == 'excellon':
  8290. new_color = self.defaults['excellon_plot_fill']
  8291. new_line_color = self.defaults['excellon_plot_line']
  8292. elif sel_obj.kind == 'gerber':
  8293. new_color = self.defaults['gerber_plot_fill']
  8294. new_line_color = self.defaults['gerber_plot_line']
  8295. elif sel_obj.kind == 'geometry':
  8296. new_color = self.defaults['geometry_plot_line']
  8297. new_line_color = self.defaults['geometry_plot_line']
  8298. else:
  8299. log.debug(
  8300. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8301. continue
  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. return
  8308. if act_name == _("Opacity"):
  8309. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8310. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8311. if ok_button:
  8312. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8313. for sel_obj in sel_obj_list:
  8314. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8315. sel_obj.shapes.redraw(
  8316. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8317. )
  8318. return
  8319. new_line_color = color_variant(new_color[:7], 0.7)
  8320. if act_name == _("White"):
  8321. new_line_color = color_variant("#dedede", 0.7)
  8322. for sel_obj in sel_obj_list:
  8323. sel_obj.fill_color = new_color
  8324. sel_obj.outline_color = new_line_color
  8325. sel_obj.shapes.redraw(
  8326. update_colors=(new_color, new_line_color)
  8327. )
  8328. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  8329. group = self.collection.group_items["gerber"]
  8330. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  8331. new_c = (new_line_color, new_color)
  8332. for sel_obj in sel_obj_list:
  8333. if sel_obj.kind == 'gerber':
  8334. item = sel_obj.item
  8335. item_index = self.collection.index(item.row(), 0, group_index)
  8336. idx = item_index.row()
  8337. self.defaults["gerber_color_list"][idx] = new_c
  8338. def generate_cnc_job(self, objects):
  8339. """
  8340. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8341. :param objects: Selected objects in the Project Tab
  8342. :return:
  8343. """
  8344. self.defaults.report_usage("generate_cnc_job()")
  8345. # for obj in objects:
  8346. # obj.generatecncjob()
  8347. for obj in objects:
  8348. obj.on_generatecnc_button_click()
  8349. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8350. """
  8351. Saves the current project to the specified file.
  8352. :param filename: Name of the file in which to save.
  8353. :type filename: str
  8354. :param quit_action: if the project saving will be followed by an app quit; boolean
  8355. :param silent: if True will not display status messages
  8356. :param from_tcl True is run from Tcl Shell
  8357. :return: None
  8358. """
  8359. self.log.debug("save_project()")
  8360. self.save_in_progress = True
  8361. with self.proc_container.new(_("Saving FlatCAM Project")):
  8362. # Capture the latest changes
  8363. # Current object
  8364. try:
  8365. current_object = self.collection.get_active()
  8366. if current_object:
  8367. current_object.read_form()
  8368. except Exception as e:
  8369. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8370. pass
  8371. # Serialize the whole project
  8372. d = {
  8373. "objs": [obj.to_dict() for obj in self.collection.get_list()],
  8374. "options": self.options,
  8375. "version": self.version
  8376. }
  8377. if self.defaults["global_save_compressed"] is True:
  8378. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8379. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8380. # # Write
  8381. f.write(g)
  8382. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8383. else:
  8384. # Open file
  8385. try:
  8386. f = open(filename, 'w')
  8387. except IOError:
  8388. App.log.error("Failed to open file for saving: %s", filename)
  8389. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8390. return
  8391. # Write
  8392. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8393. f.close()
  8394. # verification of the saved project
  8395. # Open and parse
  8396. try:
  8397. saved_f = open(filename, 'r')
  8398. except IOError:
  8399. if silent is False:
  8400. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8401. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8402. return
  8403. try:
  8404. saved_d = json.load(saved_f, object_hook=dict2obj)
  8405. except Exception:
  8406. if silent is False:
  8407. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8408. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8409. f.close()
  8410. return
  8411. saved_f.close()
  8412. if silent is False:
  8413. if 'version' in saved_d:
  8414. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8415. else:
  8416. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8417. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8418. tb_settings = QSettings("Open Source", "FlatCAM")
  8419. lock_state = self.ui.lock_action.isChecked()
  8420. tb_settings.setValue('toolbar_lock', lock_state)
  8421. # This will write the setting to the platform specific storage.
  8422. del tb_settings
  8423. # if quit:
  8424. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8425. # t.start()
  8426. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8427. def start_delayed_quit(self, delay, filename, should_quit=None):
  8428. """
  8429. :param delay: period of checking if project file size is more than zero; in seconds
  8430. :param filename: the name of the project file to be checked periodically for size more than zero
  8431. :param should_quit: if the task finished will be followed by an app quit; boolean
  8432. :return:
  8433. """
  8434. to_quit = should_quit
  8435. self.save_timer = QtCore.QTimer()
  8436. self.save_timer.setInterval(delay)
  8437. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8438. self.save_timer.start()
  8439. def check_project_file_size(self, filename, should_quit=None):
  8440. """
  8441. :param filename: the name of the project file to be checked periodically for size more than zero
  8442. :param should_quit: will quit the app if True; boolean
  8443. :return:
  8444. """
  8445. try:
  8446. if os.stat(filename).st_size > 0:
  8447. self.save_in_progress = False
  8448. self.save_timer.stop()
  8449. if should_quit:
  8450. self.app_quit.emit()
  8451. except Exception:
  8452. traceback.print_exc()
  8453. def save_project_auto(self):
  8454. """
  8455. Called periodically to save the project.
  8456. 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
  8457. # progress.
  8458. :return:
  8459. """
  8460. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8461. self.on_file_saveproject()
  8462. def save_project_auto_update(self):
  8463. """
  8464. Update the auto save time interval value.
  8465. :return:
  8466. """
  8467. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8468. try:
  8469. if self.autosave_timer.isActive():
  8470. self.autosave_timer.stop()
  8471. except Exception:
  8472. pass
  8473. if self.defaults['global_autosave'] is True:
  8474. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8475. self.autosave_timer.start()
  8476. def on_options_app2project(self):
  8477. """
  8478. Callback for Options->Transfer Options->App=>Project. Copies options
  8479. from application defaults to project defaults.
  8480. :return: None
  8481. """
  8482. self.defaults.report_usage("on_options_app2project")
  8483. self.preferencesUiManager.defaults_read_form()
  8484. self.options.update(self.defaults)
  8485. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8486. """
  8487. Shows a message on the FlatCAM Shell
  8488. :param msg: Message to display.
  8489. :param show: Opens the shell.
  8490. :param error: Shows the message as an error.
  8491. :param warning: Shows the message as an warning.
  8492. :param success: Shows the message as an success.
  8493. :param selected: Indicate that something was selected on canvas
  8494. :return: None
  8495. """
  8496. if show:
  8497. self.ui.shell_dock.show()
  8498. try:
  8499. if error:
  8500. self.shell.append_error(msg + "\n")
  8501. elif warning:
  8502. self.shell.append_warning(msg + "\n")
  8503. elif success:
  8504. self.shell.append_success(msg + "\n")
  8505. elif selected:
  8506. self.shell.append_selected(msg + "\n")
  8507. else:
  8508. self.shell.append_output(msg + "\n")
  8509. except AttributeError:
  8510. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8511. def dec_format(self, val, dec=None):
  8512. """
  8513. Returns a formatted float value with a certain number of decimals
  8514. """
  8515. dec_nr = dec if dec is not None else self.decimals
  8516. return float('%.*f' % (dec_nr, val))
  8517. class ArgsThread(QtCore.QObject):
  8518. open_signal = pyqtSignal(list)
  8519. start = pyqtSignal()
  8520. stop = pyqtSignal()
  8521. if sys.platform == 'win32':
  8522. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8523. else:
  8524. address = ('/tmp/testipc', 'AF_UNIX')
  8525. def __init__(self):
  8526. super().__init__()
  8527. self.listener = None
  8528. self.thread_exit = False
  8529. self.start.connect(self.run)
  8530. self.stop.connect(self.close_listener)
  8531. def my_loop(self, address):
  8532. try:
  8533. self.listener = Listener(*address)
  8534. while self.thread_exit is False:
  8535. conn = self.listener.accept()
  8536. self.serve(conn)
  8537. except socket.error:
  8538. try:
  8539. conn = Client(*address)
  8540. conn.send(sys.argv)
  8541. conn.send('close')
  8542. # close the current instance only if there are args
  8543. if len(sys.argv) > 1:
  8544. try:
  8545. self.listener.close()
  8546. except Exception:
  8547. pass
  8548. sys.exit()
  8549. except ConnectionRefusedError:
  8550. if sys.platform == 'win32':
  8551. pass
  8552. else:
  8553. os.system('rm /tmp/testipc')
  8554. self.listener = Listener(*address)
  8555. while True:
  8556. conn = self.listener.accept()
  8557. self.serve(conn)
  8558. def serve(self, conn):
  8559. while self.thread_exit is False:
  8560. msg = conn.recv()
  8561. if msg == 'close':
  8562. break
  8563. self.open_signal.emit(msg)
  8564. conn.close()
  8565. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8566. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8567. @pyqtSlot()
  8568. def run(self):
  8569. self.my_loop(self.address)
  8570. @pyqtSlot()
  8571. def close_listener(self):
  8572. self.thread_exit = True
  8573. self.listener.close()
  8574. # end of file