FlatCAMApp.py 482 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from shapely.geometry import Point, MultiPolygon
  21. from io import StringIO
  22. from reportlab.graphics import renderPDF
  23. from reportlab.pdfgen import canvas
  24. from reportlab.lib.units import inch, mm
  25. from reportlab.lib.pagesizes import landscape, portrait
  26. from svglib.svglib import svg2rlg
  27. import gc
  28. from xml.dom.minidom import parseString as parse_xml_string
  29. from multiprocessing.connection import Listener, Client
  30. from multiprocessing import Pool
  31. import socket
  32. # ####################################################################################################################
  33. # ################################### Imports part of FlatCAM #############################################
  34. # ####################################################################################################################
  35. # Diverse
  36. from FlatCAMCommon import LoudDict, color_variant
  37. from FlatCAMBookmark import BookmarkManager
  38. from FlatCAMDB import ToolsDB2
  39. from vispy.gloo.util import _screenshot
  40. from vispy.io import write_png
  41. # FlatCAM Objects
  42. from defaults import FlatCAMDefaults
  43. from flatcamObjects.ObjectCollection import *
  44. from flatcamObjects.FlatCAMObj import FlatCAMObj
  45. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  46. from flatcamObjects.FlatCAMDocument import DocumentObject
  47. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  48. from flatcamObjects.FlatCAMGeometry import GeometryObject
  49. from flatcamObjects.FlatCAMGerber import GerberObject
  50. from flatcamObjects.FlatCAMScript import ScriptObject
  51. # FlatCAM Parsing files
  52. from flatcamParsers.ParseExcellon import Excellon
  53. from flatcamParsers.ParseGerber import Gerber
  54. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  55. # FlatCAM GUI
  56. from flatcamGUI.PlotCanvas import *
  57. from flatcamGUI.PlotCanvasLegacy import *
  58. from flatcamGUI.FlatCAMGUI import *
  59. from flatcamGUI.GUIElements import FCFileSaveDialog
  60. # FlatCAM Pre-processors
  61. from FlatCAMPostProc import load_preprocessors
  62. # FlatCAM Editors
  63. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  64. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  65. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  66. from flatcamEditors.FlatCAMTextEditor import TextEditor
  67. from flatcamParsers.ParseHPGL2 import HPGL2
  68. # FlatCAM Workers
  69. from FlatCAMProcess import *
  70. from FlatCAMWorkerStack import WorkerStack
  71. # FlatCAM Tools
  72. from flatcamTools import *
  73. # FlatCAM Translation
  74. import gettext
  75. import FlatCAMTranslation as fcTranslate
  76. import builtins
  77. if sys.platform == 'win32':
  78. import winreg
  79. fcTranslate.apply_language('strings')
  80. if '_' not in builtins.__dict__:
  81. _ = gettext.gettext
  82. class App(QtCore.QObject):
  83. """
  84. The main application class. The constructor starts the GUI.
  85. """
  86. # ###############################################################################################################
  87. # ########################################## App ################################################################
  88. # ###############################################################################################################
  89. # ###############################################################################################################
  90. # ######################################### LOGGING #############################################################
  91. # ###############################################################################################################
  92. log = logging.getLogger('base')
  93. log.setLevel(logging.DEBUG)
  94. # log.setLevel(logging.WARNING)
  95. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  96. handler = logging.StreamHandler()
  97. handler.setFormatter(formatter)
  98. log.addHandler(handler)
  99. # ###############################################################################################################
  100. # #################################### Get Cmd Line Options #####################################################
  101. # ###############################################################################################################
  102. cmd_line_shellfile = ''
  103. cmd_line_shellvar = ''
  104. cmd_line_headless = None
  105. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  106. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  107. "FlatCam.py --headless=1"
  108. try:
  109. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  110. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  111. "shellvar=",
  112. "headless=",
  113. "multiprocessing-fork="])
  114. except getopt.GetoptError:
  115. print(cmd_line_help)
  116. sys.exit(2)
  117. for opt, arg in cmd_line_options:
  118. if opt == '-h':
  119. print(cmd_line_help)
  120. sys.exit()
  121. elif opt == '--shellfile':
  122. cmd_line_shellfile = arg
  123. elif opt == '--shellvar':
  124. cmd_line_shellvar = arg
  125. elif opt == '--headless':
  126. try:
  127. cmd_line_headless = eval(arg)
  128. except NameError:
  129. pass
  130. # ###############################################################################################################
  131. # ################################### Version and VERSION DATE ##################################################
  132. # ###############################################################################################################
  133. version = 8.992
  134. version_date = "2020/05/01"
  135. beta = True
  136. engine = '3D'
  137. # current date now
  138. date = str(datetime.today()).rpartition('.')[0]
  139. date = ''.join(c for c in date if c not in ':-')
  140. date = date.replace(' ', '_')
  141. # ###############################################################################################################
  142. # ############################################ URLS's ###########################################################
  143. # ###############################################################################################################
  144. # URL for update checks and statistics
  145. version_url = "http://flatcam.org/version"
  146. # App URL
  147. app_url = "http://flatcam.org"
  148. # Manual URL
  149. manual_url = "http://flatcam.org/manual/index.html"
  150. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  151. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  152. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  153. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  154. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  155. # this variable will hold the project status
  156. # if True it will mean that the project was modified and not saved
  157. should_we_save = False
  158. # flag is True if saving action has been triggered
  159. save_in_progress = False
  160. # ###############################################################################################################
  161. # ####################################### APP Signals ######################################################
  162. # ###############################################################################################################
  163. # Inform the user
  164. # Handled by:
  165. # * App.info() --> Print on the status bar
  166. inform = QtCore.pyqtSignal(str)
  167. app_quit = QtCore.pyqtSignal()
  168. # General purpose background task
  169. worker_task = QtCore.pyqtSignal(dict)
  170. # File opened
  171. # Handled by:
  172. # * register_folder()
  173. # * register_recent()
  174. # Note: Setting the parameters to unicode does not seem
  175. # to have an effect. Then are received as Qstring
  176. # anyway.
  177. # File type and filename
  178. file_opened = QtCore.pyqtSignal(str, str)
  179. # File type and filename
  180. file_saved = QtCore.pyqtSignal(str, str)
  181. # Percentage of progress
  182. progress = QtCore.pyqtSignal(int)
  183. plots_updated = QtCore.pyqtSignal()
  184. # Emitted by new_object() and passes the new object as argument, plot flag.
  185. # on_object_created() adds the object to the collection, plots on appropriate flag
  186. # and emits new_object_available.
  187. object_created = QtCore.pyqtSignal(object, bool, bool)
  188. # Emitted when a object has been changed (like scaled, mirrored)
  189. object_changed = QtCore.pyqtSignal(object)
  190. # Emitted after object has been plotted.
  191. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  192. object_plotted = QtCore.pyqtSignal(object)
  193. # Emitted when a new object has been added or deleted from/to the collection
  194. object_status_changed = QtCore.pyqtSignal(object, str, str)
  195. message = QtCore.pyqtSignal(str, str, str)
  196. # Emmited when shell command is finished(one command only)
  197. shell_command_finished = QtCore.pyqtSignal(object)
  198. # Emitted when multiprocess pool has been recreated
  199. pool_recreated = QtCore.pyqtSignal(object)
  200. # Emitted when an unhandled exception happens
  201. # in the worker task.
  202. thread_exception = QtCore.pyqtSignal(object)
  203. # used to signal that there are arguments for the app
  204. args_at_startup = QtCore.pyqtSignal(list)
  205. # a reusable signal to replot a list of objects
  206. # should be disconnected after use so it can be reused
  207. replot_signal = pyqtSignal(list)
  208. # signal emitted when jumping
  209. jump_signal = pyqtSignal(tuple)
  210. # signal emitted when jumping
  211. locate_signal = pyqtSignal(tuple, str)
  212. # close app signal
  213. close_app_signal = pyqtSignal()
  214. # will perform the cleanup operation after a Graceful Exit
  215. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  216. # graphic residues behind
  217. cleanup = pyqtSignal()
  218. def __init__(self, user_defaults=True):
  219. """
  220. Starts the application.
  221. :return: app
  222. :rtype: App
  223. """
  224. App.log.info("FlatCAM Starting...")
  225. self.main_thread = QtWidgets.QApplication.instance().thread()
  226. # ############################################################################################################
  227. # ################# Setup the listening thread for another instance launching with args ######################
  228. # ############################################################################################################
  229. if sys.platform == 'win32' or sys.platform == 'linux':
  230. # make sure the thread is stored by using a self. otherwise it's garbage collected
  231. self.th = QtCore.QThread()
  232. self.th.start(priority=QtCore.QThread.LowestPriority)
  233. self.new_launch = ArgsThread()
  234. self.new_launch.open_signal[list].connect(self.on_startup_args)
  235. self.new_launch.moveToThread(self.th)
  236. self.new_launch.start.emit()
  237. # ############################################################################################################
  238. # # ######################################## OS-specific #####################################################
  239. # ############################################################################################################
  240. portable = False
  241. # Folder for user settings.
  242. if sys.platform == 'win32':
  243. from win32comext.shell import shell, shellcon
  244. if platform.architecture()[0] == '32bit':
  245. App.log.debug("Win32!")
  246. else:
  247. App.log.debug("Win64!")
  248. # #######################################################################################################
  249. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  250. # #######################################################################################################
  251. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r'):
  254. pass
  255. except FileNotFoundError:
  256. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  257. try:
  258. with open(config_file, 'r') as f:
  259. try:
  260. for line in f:
  261. param = str(line).replace('\n', '').rpartition('=')
  262. if param[0] == 'portable':
  263. try:
  264. portable = eval(param[2])
  265. except NameError:
  266. portable = False
  267. if param[0] == 'headless':
  268. if param[2].lower() == 'true':
  269. self.cmd_line_headless = 1
  270. else:
  271. self.cmd_line_headless = None
  272. except Exception as e:
  273. log.debug('App.__init__() -->%s' % str(e))
  274. return
  275. except FileNotFoundError as e:
  276. log.debug(str(e))
  277. pass
  278. if portable is False:
  279. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  280. else:
  281. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  282. self.os = 'windows'
  283. else: # Linux/Unix/MacOS
  284. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  285. self.os = 'unix'
  286. # ############################################################################################################
  287. # ################################# Setup folders and files ##################################################
  288. # ############################################################################################################
  289. if not os.path.exists(self.data_path):
  290. os.makedirs(self.data_path)
  291. App.log.debug('Created data folder: ' + self.data_path)
  292. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  293. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  294. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  295. if not os.path.exists(self.preprocessorpaths):
  296. os.makedirs(self.preprocessorpaths)
  297. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  298. # create geo_tools_db.FlatDB file if there is none
  299. try:
  300. f = open(self.data_path + '/geo_tools_db.FlatDB')
  301. f.close()
  302. except IOError:
  303. App.log.debug('Creating empty geo_tool_db.FlatDB')
  304. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  305. json.dump({}, f)
  306. f.close()
  307. # create current_defaults.FlatConfig file if there is none
  308. try:
  309. f = open(self.data_path + '/current_defaults.FlatConfig')
  310. f.close()
  311. except IOError:
  312. App.log.debug('Creating empty current_defaults.FlatConfig')
  313. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  314. json.dump({}, f)
  315. f.close()
  316. # Write factory_defaults.FlatConfig file to disk
  317. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  318. # create a recent files json file if there is none
  319. try:
  320. f = open(self.data_path + '/recent.json')
  321. f.close()
  322. except IOError:
  323. App.log.debug('Creating empty recent.json')
  324. f = open(self.data_path + '/recent.json', 'w')
  325. json.dump([], f)
  326. f.close()
  327. # create a recent projects json file if there is none
  328. try:
  329. fp = open(self.data_path + '/recent_projects.json')
  330. fp.close()
  331. except IOError:
  332. App.log.debug('Creating empty recent_projects.json')
  333. fp = open(self.data_path + '/recent_projects.json', 'w')
  334. json.dump([], fp)
  335. fp.close()
  336. # Application directory. CHDIR to it. Otherwise, trying to load
  337. # GUI icons will fail as their path is relative.
  338. # This will fail under cx_freeze ...
  339. self.app_home = os.path.dirname(os.path.realpath(__file__))
  340. App.log.debug("Application path is " + self.app_home)
  341. App.log.debug("Started in " + os.getcwd())
  342. # cx_freeze workaround
  343. if os.path.isfile(self.app_home):
  344. self.app_home = os.path.dirname(self.app_home)
  345. os.chdir(self.app_home)
  346. # ############################################################################################################
  347. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  348. # ############################################################################################################
  349. self.defaults = FlatCAMDefaults()
  350. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  351. if user_defaults:
  352. self.defaults.load(filename=current_defaults_path)
  353. if self.defaults['units'] == 'MM':
  354. self.decimals = int(self.defaults['decimals_metric'])
  355. else:
  356. self.decimals = int(self.defaults['decimals_inch'])
  357. if self.defaults["global_gray_icons"] is False:
  358. self.resource_location = 'assets/resources'
  359. else:
  360. self.resource_location = 'assets/resources/dark_resources'
  361. self.current_units = self.defaults['units']
  362. # ###########################################################################################################
  363. # #################################### SETUP OBJECT CLASSES #################################################
  364. # ###########################################################################################################
  365. self.setup_obj_classes()
  366. # ###########################################################################################################
  367. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  368. # ###########################################################################################################
  369. self.pool = Pool()
  370. # ###########################################################################################################
  371. # ###################################### Setting the Splash Screen ##########################################
  372. # ###########################################################################################################
  373. splash_settings = QSettings("Open Source", "FlatCAM")
  374. if splash_settings.contains("splash_screen"):
  375. show_splash = splash_settings.value("splash_screen")
  376. else:
  377. splash_settings.setValue('splash_screen', 1)
  378. # This will write the setting to the platform specific storage.
  379. del splash_settings
  380. show_splash = 1
  381. if show_splash and self.cmd_line_headless != 1:
  382. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  383. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  384. # self.splash.setMask(splash_pix.mask())
  385. # move splashscreen to the current monitor
  386. desktop = QtWidgets.QApplication.desktop()
  387. screen = desktop.screenNumber(QtGui.QCursor.pos())
  388. current_screen_center = desktop.availableGeometry(screen).center()
  389. self.splash.move(current_screen_center - self.splash.rect().center())
  390. self.splash.show()
  391. self.splash.showMessage(_("FlatCAM is initializing ..."),
  392. alignment=Qt.AlignBottom | Qt.AlignLeft,
  393. color=QtGui.QColor("gray"))
  394. else:
  395. show_splash = 0
  396. # ###########################################################################################################
  397. # ######################################### Initialize GUI ##################################################
  398. # ###########################################################################################################
  399. # FlatCAM colors used in plotting
  400. self.FC_light_green = '#BBF268BF'
  401. self.FC_dark_green = '#006E20BF'
  402. self.FC_light_blue = '#a5a5ffbf'
  403. self.FC_dark_blue = '#0000ffbf'
  404. QtCore.QObject.__init__(self)
  405. self.ui = FlatCAMGUI(self)
  406. self.on_grid_snap_triggered(state=True)
  407. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  408. if theme_settings.contains("theme"):
  409. theme = theme_settings.value('theme', type=str)
  410. else:
  411. theme = 'white'
  412. if self.defaults["global_cursor_color_enabled"]:
  413. self.cursor_color_3D = self.defaults["global_cursor_color"]
  414. else:
  415. if theme == 'white':
  416. self.cursor_color_3D = 'black'
  417. else:
  418. self.cursor_color_3D = 'gray'
  419. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  420. self.ui.final_save.connect(self.final_save)
  421. # restore the toolbar view
  422. self.restore_toolbar_view()
  423. # restore the GUI geometry
  424. self.restore_main_win_geom()
  425. # set FlatCAM units in the Status bar
  426. self.set_screen_units(self.defaults['units'])
  427. # ###########################################################################################################
  428. # ########################################### AUTOSAVE SETUP ################################################
  429. # ###########################################################################################################
  430. self.block_autosave = False
  431. self.autosave_timer = QtCore.QTimer(self)
  432. self.save_project_auto_update()
  433. self.autosave_timer.timeout.connect(self.save_project_auto)
  434. # ###########################################################################################################
  435. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  436. # ###########################################################################################################
  437. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  438. inform=self.inform)
  439. self.preferencesUiManager.defaults_write_form()
  440. # When the self.defaults dictionary changes will update the Preferences GUI forms
  441. self.defaults.set_change_callback(self.on_defaults_dict_change)
  442. # ###########################################################################################################
  443. # ##################################### FIRST RUN SECTION ###################################################
  444. # ################################ It's done only once after install #####################################
  445. # ###########################################################################################################
  446. if self.defaults["first_run"] is True:
  447. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  448. initial_lay = 'minimal'
  449. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  450. # Set the combobox in Preferences to the current layout
  451. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  452. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  453. # after the first run, this object should be False
  454. self.defaults["first_run"] = False
  455. self.preferencesUiManager.save_defaults(silent=True)
  456. # ###########################################################################################################
  457. # ############################################ Data #########################################################
  458. # ###########################################################################################################
  459. self.recent = []
  460. self.recent_projects = []
  461. self.clipboard = QtWidgets.QApplication.clipboard()
  462. self.project_filename = None
  463. self.toggle_units_ignore = False
  464. # ###########################################################################################################
  465. # #################################### LOAD PREPROCESSORS ###################################################
  466. # ###########################################################################################################
  467. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  468. # the preprocessor file
  469. self.preprocessors = load_preprocessors(self)
  470. # make sure that always the 'default' preprocessor is the first item in the dictionary
  471. if 'default' in self.preprocessors.keys():
  472. new_ppp_dict = {}
  473. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  474. default_pp = self.preprocessors.pop('default')
  475. new_ppp_dict['default'] = default_pp
  476. # then add the rest of the keys
  477. for name, val_class in self.preprocessors.items():
  478. new_ppp_dict[name] = val_class
  479. # and now put back the ordered dict with 'default' key first
  480. self.preprocessors = new_ppp_dict
  481. for name in list(self.preprocessors.keys()):
  482. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  483. if name.partition('_')[0] == 'Paste':
  484. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  485. continue
  486. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  487. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  488. if name == 'hpgl':
  489. continue
  490. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  491. # ###########################################################################################################
  492. # ########################################## LOAD LANGUAGES ################################################
  493. # ###########################################################################################################
  494. self.languages = fcTranslate.load_languages()
  495. for name in sorted(self.languages.values()):
  496. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  497. # ###########################################################################################################
  498. # ####################################### APPLY APP LANGUAGE ################################################
  499. # ###########################################################################################################
  500. ret_val = fcTranslate.apply_language('strings')
  501. if ret_val == "no language":
  502. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  503. log.debug("Could not find the Language files. The App strings are missing.")
  504. else:
  505. # make the current language the current selection on the language combobox
  506. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  507. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  508. # ###########################################################################################################
  509. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  510. # ###########################################################################################################
  511. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  512. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  513. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  514. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  515. self.defaults.propagate_defaults()
  516. # ###########################################################################################################
  517. # ######################################## UPDATE THE OPTIONS ###############################################
  518. # ###########################################################################################################
  519. self.options = LoudDict()
  520. # -----------------------------------------------------------------------------------------------------------
  521. # Update the self.options from the self.defaults
  522. # The self.defaults holds the application defaults while the self.options holds the object defaults
  523. # -----------------------------------------------------------------------------------------------------------
  524. # Copy app defaults to project options
  525. for def_key, def_val in self.defaults.items():
  526. self.options[def_key] = deepcopy(def_val)
  527. self.preferencesUiManager.show_preferences_gui()
  528. # ### End of Data ####
  529. # ###########################################################################################################
  530. # #################################### SETUP OBJECT COLLECTION ##############################################
  531. # ###########################################################################################################
  532. self.collection = ObjectCollection(self)
  533. self.ui.project_tab_layout.addWidget(self.collection.view)
  534. # ### Adjust tabs width ## ##
  535. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  536. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  537. self.collection.view.setMinimumWidth(290)
  538. self.log.debug("Finished creating Object Collection.")
  539. # ###########################################################################################################
  540. # ######################################## SETUP Plot Area ##################################################
  541. # ###########################################################################################################
  542. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  543. if self.defaults["global_graphic_engine"] == '3D':
  544. self.is_legacy = False
  545. else:
  546. self.is_legacy = True
  547. # Event signals disconnect id holders
  548. self.mp = None
  549. self.mm = None
  550. self.mr = None
  551. self.mdc = None
  552. self.mp_zc = None
  553. self.kp = None
  554. # Matplotlib axis
  555. self.axes = None
  556. if show_splash:
  557. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  558. "Canvas initialization started."),
  559. alignment=Qt.AlignBottom | Qt.AlignLeft,
  560. color=QtGui.QColor("gray"))
  561. start_plot_time = time.time() # debug
  562. self.plotcanvas = None
  563. self.app_cursor = None
  564. self.hover_shapes = None
  565. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  566. # setup the PlotCanvas
  567. self.on_plotcanvas_setup()
  568. end_plot_time = time.time()
  569. self.used_time = end_plot_time - start_plot_time
  570. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  571. if show_splash:
  572. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  573. "Canvas initialization started.\n"
  574. "Canvas initialization finished in"), '%.2f' % self.used_time),
  575. alignment=Qt.AlignBottom | Qt.AlignLeft,
  576. color=QtGui.QColor("gray"))
  577. self.ui.splitter.setStretchFactor(1, 2)
  578. # ###########################################################################################################
  579. # ############################################### SYS TRAY ##################################################
  580. # ###########################################################################################################
  581. if self.defaults["global_systray_icon"]:
  582. self.parent_w = QtWidgets.QWidget()
  583. if self.cmd_line_headless == 1:
  584. self.trayIcon = FlatCAMSystemTray(app=self,
  585. icon=QtGui.QIcon(self.resource_location +
  586. '/flatcam_icon32_green.png'),
  587. headless=True,
  588. parent=self.parent_w)
  589. else:
  590. self.trayIcon = FlatCAMSystemTray(app=self,
  591. icon=QtGui.QIcon(self.resource_location +
  592. '/flatcam_icon32_green.png'),
  593. parent=self.parent_w)
  594. # ###########################################################################################################
  595. # ############################################### Worker SETUP ##############################################
  596. # ###########################################################################################################
  597. if self.defaults["global_worker_number"]:
  598. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  599. else:
  600. self.workers = WorkerStack(workers_number=2)
  601. self.worker_task.connect(self.workers.add_task)
  602. self.log.debug("Finished creating Workers crew.")
  603. # ###########################################################################################################
  604. # ############################################# Activity Monitor ###########################################
  605. # ###########################################################################################################
  606. self.activity_view = FlatCAMActivityView(app=self)
  607. self.ui.infobar.addWidget(self.activity_view)
  608. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  609. # ###########################################################################################################
  610. # ############################################# Signal handling #############################################
  611. # ###########################################################################################################
  612. # ########################################## Custom signals ################################################
  613. # signal for displaying messages in status bar
  614. self.inform.connect(self.info)
  615. # signal to be called when the app is quiting
  616. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  617. self.message.connect(self.message_dialog)
  618. # self.progress.connect(self.set_progress_bar)
  619. # signals that are emitted when object state changes
  620. self.object_created.connect(self.on_object_created)
  621. self.object_changed.connect(self.on_object_changed)
  622. self.object_plotted.connect(self.on_object_plotted)
  623. self.plots_updated.connect(self.on_plots_updated)
  624. # signals emitted when file state change
  625. self.file_opened.connect(self.register_recent)
  626. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  627. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  628. # ########################################## Standard signals ###############################################
  629. # ### Menu
  630. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  631. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  632. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  633. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  634. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  635. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  636. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  637. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  638. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  639. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  640. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  641. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  642. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  643. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  644. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  645. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  646. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  647. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  648. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  649. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  650. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  651. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  652. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  653. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  654. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  655. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  656. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  657. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  658. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  659. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  660. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  661. self.ui.menufile_exit.triggered.connect(self.final_save)
  662. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  663. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  664. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  665. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  666. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  667. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  668. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  669. self.ui.menueditdelete.triggered.connect(self.on_delete)
  670. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  671. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  672. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  673. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  674. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  675. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  676. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  677. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  678. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  679. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  680. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  681. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  682. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  683. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  684. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  685. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  686. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  687. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  688. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  689. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  690. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  691. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  692. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  693. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  694. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  695. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  696. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  697. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  698. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  699. self.ui.menuview_replot.triggered.connect(self.plot_all)
  700. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  701. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  702. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  703. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  704. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  705. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  706. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  707. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  708. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  709. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  710. self.ui.menuhelp_about.triggered.connect(self.on_about)
  711. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  712. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  713. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  714. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  715. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  716. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  717. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  718. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  719. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  720. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  721. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  722. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  723. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  724. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  725. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  726. # ToolBar signals
  727. self.connect_toolbar_signals()
  728. # Notebook and Plot Tab Area signals
  729. # make the right click on the notebook tab and plot tab area tab raise a menu
  730. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  731. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  732. self.on_tab_setup_context_menu()
  733. # activate initial state
  734. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  735. # Context Menu
  736. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  737. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  738. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  739. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  740. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  741. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  742. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  743. self.ui.clearplot.triggered.connect(self.clear_plots)
  744. self.ui.replot.triggered.connect(self.plot_all)
  745. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  746. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  747. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  748. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  749. self.ui.popmenu_move.triggered.connect(self.obj_move)
  750. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  751. # Project Context Menu -> Color Setting
  752. for act in self.ui.menuprojectcolor.actions():
  753. act.triggered.connect(self.on_set_color_action_triggered)
  754. # ###########################################################################################################
  755. # #################################### GUI PREFERENCES SIGNALS ##############################################
  756. # ###########################################################################################################
  757. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  758. lambda: self.on_toggle_units(no_pref=False))
  759. # ##################################### Workspace Setting Signals ###########################################
  760. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  761. self.on_workspace_modified)
  762. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  763. self.on_workspace_modified
  764. )
  765. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  766. # ###########################################################################################################
  767. # ######################################## GUI SETTINGS SIGNALS #############################################
  768. # ###########################################################################################################
  769. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  770. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  771. # ######################################## Tools related signals ############################################
  772. # Film Tool
  773. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  774. self.on_film_color_entry)
  775. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  776. self.on_film_color_button)
  777. # QRCode Tool
  778. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  779. self.on_qrcode_fill_color_entry)
  780. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  781. self.on_qrcode_fill_color_button)
  782. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  783. self.on_qrcode_back_color_entry)
  784. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  785. self.on_qrcode_back_color_button)
  786. # portability changed signal
  787. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  788. # Object list
  789. self.collection.view.activated.connect(self.on_row_activated)
  790. self.collection.item_selected.connect(self.on_row_selected)
  791. self.object_status_changed.connect(self.on_collection_updated)
  792. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  793. # Export Excellon parameters.
  794. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  795. self.on_update_exc_export
  796. )
  797. # call it once to make sure it is updated at startup
  798. self.on_update_exc_export(state=self.defaults["excellon_update"])
  799. # when there are arguments at application startup this get launched
  800. self.args_at_startup[list].connect(self.on_startup_args)
  801. # ###########################################################################################################
  802. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  803. # ###########################################################################################################
  804. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  805. lambda: self.restore_extensions(ext_type='excellon'))
  806. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  807. lambda: self.restore_extensions(ext_type='gcode'))
  808. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  809. lambda: self.restore_extensions(ext_type='gerber'))
  810. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  811. lambda: self.delete_all_extensions(ext_type='excellon'))
  812. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  813. lambda: self.delete_all_extensions(ext_type='gcode'))
  814. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  815. lambda: self.delete_all_extensions(ext_type='gerber'))
  816. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  817. lambda: self.add_extension(ext_type='excellon'))
  818. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  819. lambda: self.add_extension(ext_type='gcode'))
  820. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  821. lambda: self.add_extension(ext_type='gerber'))
  822. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  823. lambda: self.del_extension(ext_type='excellon'))
  824. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  825. lambda: self.del_extension(ext_type='gcode'))
  826. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  827. lambda: self.del_extension(ext_type='gerber'))
  828. # connect the 'Apply' buttons from the Preferences/File Associations
  829. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  830. lambda: self.on_register_files(obj_type='excellon'))
  831. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  832. lambda: self.on_register_files(obj_type='gcode'))
  833. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  834. lambda: self.on_register_files(obj_type='gerber'))
  835. # ###########################################################################################################
  836. # ########################################### KEYWORDS SIGNALS ##############################################
  837. # ###########################################################################################################
  838. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  839. lambda: self.restore_extensions(ext_type='keyword'))
  840. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  841. lambda: self.delete_all_extensions(ext_type='keyword'))
  842. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  843. lambda: self.add_extension(ext_type='keyword'))
  844. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  845. lambda: self.del_extension(ext_type='keyword'))
  846. # connect the abort_all_tasks related slots to the related signals
  847. self.proc_container.idle_flag.connect(self.app_is_idle)
  848. # signal emitted when a tab is closed in the Plot Area
  849. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  850. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  851. self.ui.snap_infobar_label.clicked.connect(self.on_grid_icon_snap_clicked)
  852. # signal to close the application
  853. self.close_app_signal.connect(self.kill_app)
  854. # ################################# FINISHED CONNECTING SIGNALS #############################################
  855. # ###########################################################################################################
  856. # ###########################################################################################################
  857. # ###########################################################################################################
  858. self.log.debug("Finished connecting Signals.")
  859. # ###########################################################################################################
  860. # ########################################## Other setups ###################################################
  861. # ###########################################################################################################
  862. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  863. # depending on from where those tools are called different actions can be done
  864. self.call_source = 'app'
  865. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  866. self.tool_tab_locked = False
  867. # decide if to show or hide the Notebook side of the screen at startup
  868. if self.defaults["global_project_at_startup"] is True:
  869. self.ui.splitter.setSizes([1, 1])
  870. else:
  871. self.ui.splitter.setSizes([0, 1])
  872. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  873. self.setup_component_editor()
  874. # ###########################################################################################################
  875. # ####################################### Auto-complete KEYWORDS ############################################
  876. # ###########################################################################################################
  877. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  878. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  879. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  880. 'export_exc',
  881. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  882. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  883. 'interiors', 'isolate', 'join_excellon',
  884. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  885. 'mirror', 'ncc',
  886. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  887. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  888. 'options', 'origin',
  889. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  890. 'save', 'save_project',
  891. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  892. 'skew', 'subtract_poly', 'subtract_rectangle',
  893. 'version', 'write_gcode'
  894. ]
  895. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  896. 'Paste_1',
  897. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  898. 'Toolchange_manual', 'True', 'Users',
  899. 'all', 'auto', 'axis',
  900. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  901. 'contour', 'default',
  902. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  903. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  904. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  905. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  906. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  907. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  908. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  909. 'spacing_columns',
  910. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  911. 'toolchange_xy', 'toolchangez', 'travelz',
  912. 'tooldia', 'use_threads', 'value',
  913. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  914. ]
  915. self.tcl_keywords = [
  916. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  917. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  918. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  919. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  920. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  921. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  922. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  923. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  924. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  925. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  926. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  927. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  928. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  929. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  930. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  931. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  932. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  933. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  934. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  935. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  936. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  937. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  938. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  939. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  940. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  941. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  942. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  943. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  944. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  945. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  946. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  947. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  948. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  949. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  950. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  951. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  952. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  953. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  954. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  955. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  956. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  957. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  958. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  959. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  960. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  961. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  962. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  963. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  964. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  965. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  966. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  967. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  968. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  969. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  970. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  971. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  972. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  973. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  974. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  975. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  976. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  977. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  978. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  979. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  980. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  981. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  982. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  983. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  984. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  985. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  986. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  987. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  988. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  989. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  990. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  991. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  992. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  993. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  994. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  995. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  996. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  997. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  998. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  999. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1000. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1001. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1002. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1003. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1004. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1005. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1006. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1007. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1008. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1009. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1010. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1011. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1012. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1013. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1014. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1015. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1016. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1017. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1018. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1019. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1020. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1021. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1022. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1023. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1024. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1025. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1026. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1027. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1028. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1029. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1030. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1031. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1032. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1033. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1034. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1035. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1036. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1037. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1038. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1039. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1040. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1041. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1042. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1043. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1044. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1045. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1046. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1047. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1048. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1049. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1050. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1051. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1052. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1053. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1054. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1055. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1056. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1057. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1058. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1059. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1060. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1061. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1062. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1063. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1064. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1065. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1066. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1067. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1068. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1069. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1070. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1071. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1072. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1073. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1074. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1075. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1076. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1077. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1078. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1079. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1080. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1081. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1082. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1083. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1084. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1085. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1086. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1087. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1088. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1089. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1090. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1091. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1092. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1093. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1094. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1095. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1096. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1097. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1098. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1099. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1100. ]
  1101. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1102. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1103. # ###########################################################################################################
  1104. # ############################################## Shell SETUP ################################################
  1105. # ###########################################################################################################
  1106. self.shell = FCShell(app=self, version=self.version)
  1107. self.ui.shell_dock.setWidget(self.shell)
  1108. self.log.debug("TCL Shell has been initialized.")
  1109. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1110. if self.defaults["global_shell_at_startup"]:
  1111. self.ui.shell_dock.show()
  1112. else:
  1113. self.ui.shell_dock.hide()
  1114. # ###########################################################################################################
  1115. # ########################################## Tools and Plugins ##############################################
  1116. # ###########################################################################################################
  1117. self.dblsidedtool = None
  1118. self.distance_tool = None
  1119. self.distance_min_tool = None
  1120. self.panelize_tool = None
  1121. self.film_tool = None
  1122. self.paste_tool = None
  1123. self.calculator_tool = None
  1124. self.rules_tool = None
  1125. self.sub_tool = None
  1126. self.move_tool = None
  1127. self.cutout_tool = None
  1128. self.ncclear_tool = None
  1129. self.optimal_tool = None
  1130. self.paint_tool = None
  1131. self.transform_tool = None
  1132. self.properties_tool = None
  1133. self.pdf_tool = None
  1134. self.image_tool = None
  1135. self.pcb_wizard_tool = None
  1136. self.cal_exc_tool = None
  1137. self.qrcode_tool = None
  1138. self.copper_thieving_tool = None
  1139. self.fiducial_tool = None
  1140. self.edrills_tool = None
  1141. self.align_objects_tool = None
  1142. self.punch_tool = None
  1143. self.invert_tool = None
  1144. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1145. try:
  1146. self.install_tools()
  1147. except AttributeError as e:
  1148. log.debug("App.__init__() install tools() --> %s" % str(e))
  1149. # ###########################################################################################################
  1150. # ############################################ SETUP RECENT ITEMS ###########################################
  1151. # ###########################################################################################################
  1152. self.setup_recent_items()
  1153. # ###########################################################################################################
  1154. # ######################################### BookMarks Manager ###############################################
  1155. # ###########################################################################################################
  1156. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1157. self.install_bookmarks()
  1158. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1159. # ###########################################################################################################
  1160. # ########################################### Tools Database ################################################
  1161. # ###########################################################################################################
  1162. self.tools_db_tab = None
  1163. # ### System Font Parsing ###
  1164. # self.f_parse = ParseFont(self)
  1165. # self.parse_system_fonts()
  1166. # ###########################################################################################################
  1167. # ######################################### Check for updates ###############################################
  1168. # ###########################################################################################################
  1169. # Separate thread (Not worker)
  1170. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1171. if (self.beta is False or self.beta is None) and \
  1172. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1173. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1174. # self.thr2 = QtCore.QThread()
  1175. self.worker_task.emit({'fcn': self.version_check,
  1176. 'params': []})
  1177. # self.thr2.start(QtCore.QThread.LowPriority)
  1178. # ###########################################################################################################
  1179. # ##################################### Register files with FlatCAM; #######################################
  1180. # ################################### It works only for Windows for now ####################################
  1181. # ###########################################################################################################
  1182. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1183. self.on_register_files()
  1184. # ###########################################################################################################
  1185. # ######################################## Variables for global usage #######################################
  1186. # ###########################################################################################################
  1187. # hold the App units
  1188. self.units = 'MM'
  1189. # coordinates for relative position display
  1190. self.rel_point1 = (0, 0)
  1191. self.rel_point2 = (0, 0)
  1192. # variable to store coordinates
  1193. self.pos = (0, 0)
  1194. self.pos_canvas = (0, 0)
  1195. self.pos_jump = (0, 0)
  1196. # variable to store mouse coordinates
  1197. self.mouse = [0, 0]
  1198. # variable to store the delta positions on cavnas
  1199. self.dx = 0
  1200. self.dy = 0
  1201. # decide if we have a double click or single click
  1202. self.doubleclick = False
  1203. # store here the is_dragging value
  1204. self.event_is_dragging = False
  1205. # variable to store if a command is active (then the var is not None) and which one it is
  1206. self.command_active = None
  1207. # variable to store the status of moving selection action
  1208. # None value means that it's not an selection action
  1209. # True value = a selection from left to right
  1210. # False value = a selection from right to left
  1211. self.selection_type = None
  1212. # List to store the objects that are currently loaded in FlatCAM
  1213. # This list is updated on each object creation or object delete
  1214. self.all_objects_list = []
  1215. self.objects_under_the_click_list = []
  1216. # List to store the objects that are selected
  1217. self.sel_objects_list = []
  1218. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1219. self.key_modifiers = None
  1220. # Variable to hold the status of the axis
  1221. self.toggle_axis = True
  1222. # Variable to hold the status of the grid lines
  1223. self.toggle_grid_lines = True
  1224. # Variable to store the status of the fullscreen event
  1225. self.toggle_fscreen = False
  1226. # Variable to store the status of the code editor
  1227. self.toggle_codeeditor = False
  1228. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1229. self.click_noproject = False
  1230. self.cursor = None
  1231. # Variable to store the GCODE that was edited
  1232. self.gcode_edited = ""
  1233. self.text_editor_tab = None
  1234. # reference for the self.ui.code_editor
  1235. self.reference_code_editor = None
  1236. self.script_code = ''
  1237. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1238. self.tools_db_changed_flag = False
  1239. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1240. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1241. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1242. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1243. 'tsm']
  1244. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1245. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1246. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1247. 'sbp', 'tap', 'xpi']
  1248. self.svg_list = ['svg']
  1249. self.dxf_list = ['dxf']
  1250. self.pdf_list = ['pdf']
  1251. self.prj_list = ['flatprj']
  1252. self.conf_list = ['flatconfig']
  1253. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1254. # flag for polygons not cleared
  1255. self.poly_not_cleared = False
  1256. # VisPy visuals
  1257. self.isHovering = False
  1258. self.notHovering = True
  1259. # Window geometry
  1260. self.x_pos = None
  1261. self.y_pos = None
  1262. self.width = None
  1263. self.height = None
  1264. # when True, the app has to return from any thread
  1265. self.abort_flag = False
  1266. # set the value used in the Windows Title
  1267. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1268. # this holds a widget that is installed in the Plot Area when View Source option is used
  1269. self.source_editor_tab = None
  1270. self.pagesize = {}
  1271. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1272. # VisPy visuals
  1273. if self.is_legacy is False:
  1274. try:
  1275. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1276. except AttributeError:
  1277. self.tool_shapes = None
  1278. else:
  1279. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1280. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1281. # used in the delayed shutdown self.start_delayed_quit() method
  1282. self.save_timer = None
  1283. # ###########################################################################################################
  1284. # ################################## ADDING FlatCAM EDITORS section #########################################
  1285. # ###########################################################################################################
  1286. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1287. # at the first launch of the App , the editors will not be functional.
  1288. try:
  1289. self.geo_editor = FlatCAMGeoEditor(self)
  1290. except AttributeError:
  1291. pass
  1292. try:
  1293. self.exc_editor = FlatCAMExcEditor(self)
  1294. except AttributeError:
  1295. pass
  1296. try:
  1297. self.grb_editor = FlatCAMGrbEditor(self)
  1298. except AttributeError:
  1299. pass
  1300. self.log.debug("Finished adding FlatCAM Editor's.")
  1301. self.set_ui_title(name=_("New Project - Not saved"))
  1302. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1303. current_platform = platform.architecture()[0]
  1304. if current_platform != '64bit':
  1305. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1306. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1307. # ###########################################################################################################
  1308. # ##################################### Finished the CONSTRUCTOR ############################################
  1309. # ###########################################################################################################
  1310. App.log.debug("END of constructor. Releasing control.")
  1311. # ###########################################################################################################
  1312. # ########################################## SHOW GUI #######################################################
  1313. # ###########################################################################################################
  1314. # if the app is not started as headless, show it
  1315. if self.cmd_line_headless != 1:
  1316. if show_splash:
  1317. # finish the splash
  1318. self.splash.finish(self.ui)
  1319. mgui_settings = QSettings("Open Source", "FlatCAM")
  1320. if mgui_settings.contains("maximized_gui"):
  1321. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1322. if maximized_ui is True:
  1323. self.ui.showMaximized()
  1324. else:
  1325. self.ui.show()
  1326. else:
  1327. self.ui.show()
  1328. if self.defaults["global_systray_icon"]:
  1329. self.trayIcon.show()
  1330. else:
  1331. log.warning("******************* RUNNING HEADLESS *******************")
  1332. # ###########################################################################################################
  1333. # ######################################## START-UP ARGUMENTS ###############################################
  1334. # ###########################################################################################################
  1335. # test if the program was started with a script as parameter
  1336. if self.cmd_line_shellvar:
  1337. try:
  1338. cnt = 0
  1339. command_tcl = 0
  1340. for i in self.cmd_line_shellvar.split(','):
  1341. if i is not None:
  1342. # noinspection PyBroadException
  1343. try:
  1344. command_tcl = eval(i)
  1345. except Exception:
  1346. command_tcl = i
  1347. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1348. cnt += 1
  1349. # if there are Windows paths then replace the path separator with a Unix like one
  1350. if sys.platform == 'win32':
  1351. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1352. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1353. except Exception as ext:
  1354. print("ERROR: ", ext)
  1355. sys.exit(2)
  1356. if self.cmd_line_shellfile:
  1357. if self.cmd_line_headless != 1:
  1358. if self.ui.shell_dock.isHidden():
  1359. self.ui.shell_dock.show()
  1360. try:
  1361. with open(self.cmd_line_shellfile, "r") as myfile:
  1362. # if show_splash:
  1363. # self.splash.showMessage('%s: %ssec\n%s' % (
  1364. # _("Canvas initialization started.\n"
  1365. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1366. # _("Executing Tcl Script ...")),
  1367. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1368. # color=QtGui.QColor("gray"))
  1369. cmd_line_shellfile_text = myfile.read()
  1370. if self.cmd_line_headless != 1:
  1371. self.shell.exec_command(cmd_line_shellfile_text)
  1372. else:
  1373. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1374. except Exception as ext:
  1375. print("ERROR: ", ext)
  1376. sys.exit(2)
  1377. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1378. # the path/file_name must be enclosed in quotes if it contain spaces
  1379. if App.args:
  1380. self.args_at_startup.emit(App.args)
  1381. if self.defaults.old_defaults_found is True:
  1382. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1383. "Please reboot the application to update."))
  1384. self.defaults.old_defaults_found = False
  1385. # ######################################### INIT FINISHED #######################################################
  1386. # #################################################################################################################
  1387. # #################################################################################################################
  1388. # #################################################################################################################
  1389. # #################################################################################################################
  1390. # #################################################################################################################
  1391. @staticmethod
  1392. def copy_and_overwrite(from_path, to_path):
  1393. """
  1394. From here:
  1395. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1396. :param from_path: source path
  1397. :param to_path: destination path
  1398. :return: None
  1399. """
  1400. if os.path.exists(to_path):
  1401. shutil.rmtree(to_path)
  1402. try:
  1403. shutil.copytree(from_path, to_path)
  1404. except FileNotFoundError:
  1405. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1406. shutil.copytree(from_new_path, to_path)
  1407. def on_startup_args(self, args, silent=False):
  1408. """
  1409. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1410. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1411. :param args: a list containing the application args at startup
  1412. :return: None
  1413. """
  1414. if args is not None:
  1415. args_to_process = args
  1416. else:
  1417. args_to_process = App.args
  1418. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1419. for argument in args_to_process:
  1420. if '.FlatPrj'.lower() in argument.lower():
  1421. try:
  1422. project_name = str(argument)
  1423. if project_name == "":
  1424. if silent is False:
  1425. self.inform.emit(_("Cancelled."))
  1426. else:
  1427. # self.open_project(project_name)
  1428. run_from_arg = True
  1429. # self.worker_task.emit({'fcn': self.open_project,
  1430. # 'params': [project_name, run_from_arg]})
  1431. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1432. except Exception as e:
  1433. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1434. elif '.FlatConfig'.lower() in argument.lower():
  1435. try:
  1436. file_name = str(argument)
  1437. if file_name == "":
  1438. if silent is False:
  1439. self.inform.emit(_("Open Config file failed."))
  1440. else:
  1441. run_from_arg = True
  1442. # self.worker_task.emit({'fcn': self.open_config_file,
  1443. # 'params': [file_name, run_from_arg]})
  1444. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1445. except Exception as e:
  1446. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1447. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1448. try:
  1449. file_name = str(argument)
  1450. if file_name == "":
  1451. if silent is False:
  1452. self.inform.emit(_("Open Script file failed."))
  1453. else:
  1454. if silent is False:
  1455. self.on_fileopenscript(name=file_name)
  1456. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1457. self.on_filerunscript(name=file_name)
  1458. except Exception as e:
  1459. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1460. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1461. log.debug("App.on_startup_args() --> Quit event.")
  1462. sys.exit()
  1463. elif 'save'.lower() in argument.lower():
  1464. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1465. self.preferencesUiManager.save_defaults()
  1466. else:
  1467. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1468. proc_arg = argument.lower()
  1469. for ext in exc_list:
  1470. proc_ext = ext.replace(' ', '')
  1471. proc_ext = '.%s' % proc_ext
  1472. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1473. file_name = str(argument)
  1474. if file_name == "":
  1475. if silent is False:
  1476. self.inform.emit(_("Open Excellon file failed."))
  1477. else:
  1478. self.on_fileopenexcellon(name=file_name, signal=None)
  1479. return
  1480. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1481. for ext in gco_list:
  1482. proc_ext = ext.replace(' ', '')
  1483. proc_ext = '.%s' % proc_ext
  1484. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1485. file_name = str(argument)
  1486. if file_name == "":
  1487. if silent is False:
  1488. self.inform.emit(_("Open GCode file failed."))
  1489. else:
  1490. self.on_fileopengcode(name=file_name, signal=None)
  1491. return
  1492. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1493. for ext in grb_list:
  1494. proc_ext = ext.replace(' ', '')
  1495. proc_ext = '.%s' % proc_ext
  1496. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1497. file_name = str(argument)
  1498. if file_name == "":
  1499. if silent is False:
  1500. self.inform.emit(_("Open Gerber file failed."))
  1501. else:
  1502. self.on_fileopengerber(name=file_name, signal=None)
  1503. return
  1504. # if it reached here without already returning then the app was registered with a file that it does not
  1505. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1506. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1507. # for arg in args_to_process:
  1508. # if 'FlatCAM.exe' in arg:
  1509. # continue
  1510. # else:
  1511. # sys.exit(2)
  1512. def set_ui_title(self, name):
  1513. """
  1514. Sets the title of the main window.
  1515. :param name: String that store the project path and project name
  1516. :return: None
  1517. """
  1518. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1519. (self.version,
  1520. ('BETA' if self.beta else ''),
  1521. platform.architecture()[0],
  1522. self.engine,
  1523. name)
  1524. )
  1525. def on_app_restart(self):
  1526. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1527. # be left in the SySTray
  1528. try:
  1529. self.trayIcon.hide()
  1530. except Exception:
  1531. pass
  1532. fcTranslate.restart_program(app=self)
  1533. def clear_pool(self):
  1534. """
  1535. Clear the multiprocessing pool and calls garbage collector.
  1536. :return: None
  1537. """
  1538. self.pool.close()
  1539. self.pool = Pool()
  1540. self.pool_recreated.emit(self.pool)
  1541. gc.collect()
  1542. def install_tools(self):
  1543. """
  1544. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1545. Instantiation of the Tools classes.
  1546. The order that the tools are installed is important as they can depend on each other install position.
  1547. :return: None
  1548. """
  1549. self.distance_tool = Distance(self)
  1550. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1551. before=self.ui.menueditorigin,
  1552. separator=False)
  1553. self.distance_min_tool = DistanceMin(self)
  1554. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1555. pos=self.ui.menuedit,
  1556. before=self.ui.menueditorigin,
  1557. separator=True)
  1558. self.dblsidedtool = DblSidedTool(self)
  1559. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1560. self.cal_exc_tool = ToolCalibration(self)
  1561. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1562. before=self.dblsidedtool.menuAction,
  1563. separator=False)
  1564. self.align_objects_tool = AlignObjects(self)
  1565. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1566. self.edrills_tool = ToolExtractDrills(self)
  1567. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1568. self.panelize_tool = Panelize(self)
  1569. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1570. self.film_tool = Film(self)
  1571. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1572. self.paste_tool = SolderPaste(self)
  1573. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1574. self.calculator_tool = ToolCalculator(self)
  1575. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1576. self.sub_tool = ToolSub(self)
  1577. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1578. pos=self.ui.menutool, separator=True)
  1579. self.rules_tool = RulesCheck(self)
  1580. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1581. pos=self.ui.menutool, separator=False)
  1582. self.optimal_tool = ToolOptimal(self)
  1583. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1584. pos=self.ui.menutool, separator=True)
  1585. self.move_tool = ToolMove(self)
  1586. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1587. before=self.ui.menueditorigin, separator=True)
  1588. self.cutout_tool = CutOut(self)
  1589. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1590. before=self.sub_tool.menuAction)
  1591. self.ncclear_tool = NonCopperClear(self)
  1592. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1593. before=self.sub_tool.menuAction, separator=True)
  1594. self.paint_tool = ToolPaint(self)
  1595. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1596. before=self.sub_tool.menuAction, separator=True)
  1597. self.copper_thieving_tool = ToolCopperThieving(self)
  1598. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1599. pos=self.ui.menutool)
  1600. self.fiducial_tool = ToolFiducials(self)
  1601. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1602. pos=self.ui.menutool)
  1603. self.qrcode_tool = QRCode(self)
  1604. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1605. pos=self.ui.menutool)
  1606. self.punch_tool = ToolPunchGerber(self)
  1607. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1608. self.invert_tool = ToolInvertGerber(self)
  1609. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1610. self.transform_tool = ToolTransform(self)
  1611. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1612. pos=self.ui.menuoptions, separator=True)
  1613. self.properties_tool = Properties(self)
  1614. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1615. pos=self.ui.menuoptions)
  1616. self.pdf_tool = ToolPDF(self)
  1617. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1618. pos=self.ui.menufileimport,
  1619. separator=True)
  1620. self.image_tool = ToolImage(self)
  1621. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1622. pos=self.ui.menufileimport,
  1623. separator=True)
  1624. self.pcb_wizard_tool = PcbWizard(self)
  1625. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1626. pos=self.ui.menufileimport)
  1627. self.log.debug("Tools are installed.")
  1628. def remove_tools(self):
  1629. """
  1630. Will remove all the actions in the Tool menu.
  1631. :return: None
  1632. """
  1633. for act in self.ui.menutool.actions():
  1634. self.ui.menutool.removeAction(act)
  1635. def init_tools(self):
  1636. """
  1637. Initialize the Tool tab in the notebook side of the central widget.
  1638. Remove the actions in the Tools menu.
  1639. Instantiate again the FlatCAM tools (plugins).
  1640. All this is required when changing the layout: standard, compact etc.
  1641. :return: None
  1642. """
  1643. log.debug("init_tools()")
  1644. # delete the data currently in the Tools Tab and the Tab itself
  1645. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1646. if widget is not None:
  1647. widget.deleteLater()
  1648. self.ui.notebook.removeTab(2)
  1649. # rebuild the Tools Tab
  1650. self.ui.tool_tab = QtWidgets.QWidget()
  1651. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1652. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1653. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1654. self.ui.tool_scroll_area = VerticalScrollArea()
  1655. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1656. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1657. # first remove all of them
  1658. self.remove_tools()
  1659. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1660. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1661. '&Command Line\tS')
  1662. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1663. # third install all of them
  1664. try:
  1665. self.install_tools()
  1666. except AttributeError:
  1667. pass
  1668. self.log.debug("Tools are initialized.")
  1669. # def parse_system_fonts(self):
  1670. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1671. # 'params': []})
  1672. def connect_toolbar_signals(self):
  1673. """
  1674. Reconnect the signals to the actions in the toolbar.
  1675. This has to be done each time after the FlatCAM tools are removed/installed.
  1676. :return: None
  1677. """
  1678. # Toolbar
  1679. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1680. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1681. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1682. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1683. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1684. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1685. self.ui.replot_btn.triggered.connect(self.plot_all)
  1686. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1687. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1688. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1689. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1690. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1691. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1692. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1693. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1694. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1695. self.ui.delete_btn.triggered.connect(self.on_delete)
  1696. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1697. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1698. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1699. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1700. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1701. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1702. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1703. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1704. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1705. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1706. # Tools Toolbar Signals
  1707. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1708. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1709. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1710. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1711. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1712. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1713. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1714. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1715. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1716. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1717. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1718. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1719. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1720. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1721. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1722. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1723. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1724. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1725. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1726. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1727. def object2editor(self):
  1728. """
  1729. Send the current Geometry or Excellon object (if any) into the it's editor.
  1730. :return: None
  1731. """
  1732. self.defaults.report_usage("object2editor()")
  1733. # disable the objects menu as it may interfere with the Editors
  1734. self.ui.menuobjects.setDisabled(True)
  1735. edited_object = self.collection.get_active()
  1736. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1737. isinstance(edited_object, ExcellonObject):
  1738. pass
  1739. else:
  1740. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1741. return
  1742. if isinstance(edited_object, GeometryObject):
  1743. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1744. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1745. # we set the notebook to hidden
  1746. # self.ui.splitter.setSizes([0, 1])
  1747. if edited_object.multigeo is True:
  1748. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1749. if len(sel_rows) > 1:
  1750. self.inform.emit('[WARNING_NOTCL] %s' %
  1751. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1752. "is not possible.\n"
  1753. "Edit only one geometry at a time."))
  1754. # determine the tool dia of the selected tool
  1755. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1756. # now find the key in the edited_object.tools that has this tooldia
  1757. multi_tool = 1
  1758. for tool in edited_object.tools:
  1759. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1760. multi_tool = tool
  1761. break
  1762. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1763. else:
  1764. self.geo_editor.edit_fcgeometry(edited_object)
  1765. # set call source to the Editor we go into
  1766. self.call_source = 'geo_editor'
  1767. elif isinstance(edited_object, ExcellonObject):
  1768. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1769. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1770. if self.ui.splitter.sizes()[0] == 0:
  1771. self.ui.splitter.setSizes([1, 1])
  1772. self.exc_editor.edit_fcexcellon(edited_object)
  1773. # set call source to the Editor we go into
  1774. self.call_source = 'exc_editor'
  1775. elif isinstance(edited_object, GerberObject):
  1776. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1777. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1778. if self.ui.splitter.sizes()[0] == 0:
  1779. self.ui.splitter.setSizes([1, 1])
  1780. self.grb_editor.edit_fcgerber(edited_object)
  1781. # set call source to the Editor we go into
  1782. self.call_source = 'grb_editor'
  1783. # reset the following variables so the UI is built again after edit
  1784. edited_object.ui_build = False
  1785. edited_object.build_aperture_storage = False
  1786. # make sure that we can't select another object while in Editor Mode:
  1787. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1788. self.ui.project_frame.setDisabled(True)
  1789. # delete any selection shape that might be active as they are not relevant in Editor
  1790. self.delete_selection_shape()
  1791. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1792. self.ui.plot_tab_area.protectTab(0)
  1793. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1794. self.should_we_save = True
  1795. def editor2object(self, cleanup=None):
  1796. """
  1797. Transfers the Geometry or Excellon from it's editor to the current object.
  1798. :return: None
  1799. """
  1800. self.defaults.report_usage("editor2object()")
  1801. # re-enable the objects menu that was disabled on entry in Editor mode
  1802. self.ui.menuobjects.setDisabled(False)
  1803. # do not update a geometry or excellon object unless it comes out of an editor
  1804. if self.call_source != 'app':
  1805. edited_obj = self.collection.get_active()
  1806. if cleanup is None:
  1807. msgbox = QtWidgets.QMessageBox()
  1808. msgbox.setText(_("Do you want to save the edited object?"))
  1809. msgbox.setWindowTitle(_("Close Editor"))
  1810. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1811. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1812. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1813. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1814. msgbox.setDefaultButton(bt_yes)
  1815. msgbox.exec_()
  1816. response = msgbox.clickedButton()
  1817. if response == bt_yes:
  1818. # clean the Tools Tab
  1819. self.ui.tool_scroll_area.takeWidget()
  1820. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1821. self.ui.notebook.setTabText(2, "Tool")
  1822. if isinstance(edited_obj, GeometryObject):
  1823. obj_type = "Geometry"
  1824. if cleanup is None:
  1825. self.geo_editor.update_fcgeometry(edited_obj)
  1826. # self.geo_editor.update_options(edited_obj)
  1827. self.geo_editor.deactivate()
  1828. # restore GUI to the Selected TAB
  1829. # Remove anything else in the GUI
  1830. self.ui.tool_scroll_area.takeWidget()
  1831. # update the geo object options so it is including the bounding box values
  1832. try:
  1833. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1834. edited_obj.options['xmin'] = xmin
  1835. edited_obj.options['ymin'] = ymin
  1836. edited_obj.options['xmax'] = xmax
  1837. edited_obj.options['ymax'] = ymax
  1838. except AttributeError as e:
  1839. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1840. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1841. edited_obj.build_ui()
  1842. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1843. elif isinstance(edited_obj, GerberObject):
  1844. obj_type = "Gerber"
  1845. if cleanup is None:
  1846. self.grb_editor.update_fcgerber()
  1847. self.grb_editor.update_options(edited_obj)
  1848. self.grb_editor.deactivate_grb_editor()
  1849. # delete the old object (the source object) if it was an empty one
  1850. try:
  1851. if len(edited_obj.solid_geometry) == 0:
  1852. old_name = edited_obj.options['name']
  1853. self.collection.set_active(old_name)
  1854. self.collection.delete_active()
  1855. except TypeError:
  1856. # if the solid_geometry is a single Polygon the len() will not work
  1857. # in any case, falling here means that we have something in the solid_geometry, even if only
  1858. # a single Polygon, therefore we pass this
  1859. pass
  1860. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1861. # restore GUI to the Selected TAB
  1862. # Remove anything else in the GUI
  1863. self.ui.selected_scroll_area.takeWidget()
  1864. elif isinstance(edited_obj, ExcellonObject):
  1865. obj_type = "Excellon"
  1866. if cleanup is None:
  1867. self.exc_editor.update_fcexcellon(edited_obj)
  1868. # self.exc_editor.update_options(edited_obj)
  1869. self.exc_editor.deactivate()
  1870. # restore GUI to the Selected TAB
  1871. # Remove anything else in the GUI
  1872. self.ui.tool_scroll_area.takeWidget()
  1873. # delete the old object (the source object) if it was an empty one
  1874. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1875. old_name = edited_obj.options['name']
  1876. self.collection.delete_by_name(name=old_name)
  1877. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1878. else:
  1879. self.inform.emit('[WARNING_NOTCL] %s' %
  1880. _("Select a Gerber, Geometry or Excellon Object to update."))
  1881. return
  1882. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1883. elif response == bt_no:
  1884. # clean the Tools Tab
  1885. self.ui.tool_scroll_area.takeWidget()
  1886. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1887. self.ui.notebook.setTabText(2, "Tool")
  1888. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1889. if isinstance(edited_obj, GeometryObject):
  1890. self.geo_editor.deactivate()
  1891. edited_obj.build_ui()
  1892. elif isinstance(edited_obj, GerberObject):
  1893. self.grb_editor.deactivate_grb_editor()
  1894. edited_obj.build_ui()
  1895. elif isinstance(edited_obj, ExcellonObject):
  1896. self.exc_editor.deactivate()
  1897. edited_obj.build_ui()
  1898. else:
  1899. self.inform.emit('[WARNING_NOTCL] %s' %
  1900. _("Select a Gerber, Geometry or Excellon Object to update."))
  1901. return
  1902. elif response == bt_cancel:
  1903. return
  1904. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1905. # edited_obj.build_ui()
  1906. # Switch notebook to Selected page
  1907. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1908. else:
  1909. if isinstance(edited_obj, GeometryObject):
  1910. self.geo_editor.deactivate()
  1911. elif isinstance(edited_obj, GerberObject):
  1912. self.grb_editor.deactivate_grb_editor()
  1913. elif isinstance(edited_obj, ExcellonObject):
  1914. self.exc_editor.deactivate()
  1915. else:
  1916. self.inform.emit('[WARNING_NOTCL] %s' %
  1917. _("Select a Gerber, Geometry or Excellon Object to update."))
  1918. return
  1919. # if notebook is hidden we show it
  1920. if self.ui.splitter.sizes()[0] == 0:
  1921. self.ui.splitter.setSizes([1, 1])
  1922. # restore the call_source to app
  1923. self.call_source = 'app'
  1924. edited_obj.plot()
  1925. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1926. self.ui.plot_tab_area.protectTab(0)
  1927. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1928. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1929. self.ui.project_frame.setDisabled(False)
  1930. def get_last_folder(self):
  1931. """
  1932. Get the folder path from where the last file was opened.
  1933. :return: String, last opened folder path
  1934. """
  1935. return self.defaults["global_last_folder"]
  1936. def get_last_save_folder(self):
  1937. """
  1938. Get the folder path from where the last file was saved.
  1939. :return: String, last saved folder path
  1940. """
  1941. loc = self.defaults["global_last_save_folder"]
  1942. if loc is None:
  1943. loc = self.defaults["global_last_folder"]
  1944. if loc is None:
  1945. loc = os.path.dirname(__file__)
  1946. return loc
  1947. def info(self, msg):
  1948. """
  1949. Informs the user. Normally on the status bar, optionally
  1950. also on the shell.
  1951. :param msg: Text to write.
  1952. :return: None
  1953. """
  1954. # Type of message in brackets at the beginning of the message.
  1955. match = re.search(r"\[(.*)\](.*)", msg)
  1956. if match:
  1957. level = match.group(1)
  1958. msg_ = match.group(2)
  1959. self.ui.fcinfo.set_status(str(msg_), level=level)
  1960. if level.lower() == "error":
  1961. self.shell_message(msg, error=True, show=True)
  1962. elif level.lower() == "warning":
  1963. self.shell_message(msg, warning=True, show=True)
  1964. elif level.lower() == "error_notcl":
  1965. self.shell_message(msg, error=True, show=False)
  1966. elif level.lower() == "warning_notcl":
  1967. self.shell_message(msg, warning=True, show=False)
  1968. elif level.lower() == "success":
  1969. self.shell_message(msg, success=True, show=False)
  1970. elif level.lower() == "selected":
  1971. self.shell_message(msg, selected=True, show=False)
  1972. else:
  1973. self.shell_message(msg, show=False)
  1974. else:
  1975. self.ui.fcinfo.set_status(str(msg), level="info")
  1976. # make sure that if the message is to clear the infobar with a space
  1977. # is not printed over and over on the shell
  1978. if msg != '':
  1979. self.shell_message(msg)
  1980. def restore_toolbar_view(self):
  1981. """
  1982. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1983. was saved in the defaults dictionary.
  1984. :return: None
  1985. """
  1986. tb = self.defaults["global_toolbar_view"]
  1987. if tb & 1:
  1988. self.ui.toolbarfile.setVisible(True)
  1989. else:
  1990. self.ui.toolbarfile.setVisible(False)
  1991. if tb & 2:
  1992. self.ui.toolbargeo.setVisible(True)
  1993. else:
  1994. self.ui.toolbargeo.setVisible(False)
  1995. if tb & 4:
  1996. self.ui.toolbarview.setVisible(True)
  1997. else:
  1998. self.ui.toolbarview.setVisible(False)
  1999. if tb & 8:
  2000. self.ui.toolbartools.setVisible(True)
  2001. else:
  2002. self.ui.toolbartools.setVisible(False)
  2003. if tb & 16:
  2004. self.ui.exc_edit_toolbar.setVisible(True)
  2005. else:
  2006. self.ui.exc_edit_toolbar.setVisible(False)
  2007. if tb & 32:
  2008. self.ui.geo_edit_toolbar.setVisible(True)
  2009. else:
  2010. self.ui.geo_edit_toolbar.setVisible(False)
  2011. if tb & 64:
  2012. self.ui.grb_edit_toolbar.setVisible(True)
  2013. else:
  2014. self.ui.grb_edit_toolbar.setVisible(False)
  2015. if tb & 128:
  2016. self.ui.snap_toolbar.setVisible(True)
  2017. else:
  2018. self.ui.snap_toolbar.setVisible(False)
  2019. if tb & 256:
  2020. self.ui.toolbarshell.setVisible(True)
  2021. else:
  2022. self.ui.toolbarshell.setVisible(False)
  2023. def on_import_preferences(self):
  2024. """
  2025. Loads the application default settings from a saved file into
  2026. ``self.defaults`` dictionary.
  2027. :return: None
  2028. """
  2029. self.defaults.report_usage("on_import_preferences")
  2030. App.log.debug("App.on_import_preferences()")
  2031. # Show file chooser
  2032. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2033. try:
  2034. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2035. directory=self.data_path,
  2036. filter=filter_)
  2037. except TypeError:
  2038. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2039. filter=filter_)
  2040. filename = str(filename)
  2041. if filename == "":
  2042. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2043. return
  2044. # Load in the defaults from the chosen file
  2045. self.defaults.load(filename=filename)
  2046. self.preferencesUiManager.on_preferences_edited()
  2047. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2048. def on_export_preferences(self):
  2049. """
  2050. Save the defaults dictionary to a file.
  2051. :return: None
  2052. """
  2053. self.defaults.report_usage("on_export_preferences")
  2054. App.log.debug("on_export_preferences()")
  2055. defaults_file_content = None
  2056. # Show file chooser
  2057. date = str(datetime.today()).rpartition('.')[0]
  2058. date = ''.join(c for c in date if c not in ':-')
  2059. date = date.replace(' ', '_')
  2060. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2061. try:
  2062. filename, _f = FCFileSaveDialog.get_saved_filename(
  2063. caption=_("Export FlatCAM Preferences"),
  2064. directory=self.data_path + '/preferences_' + date,
  2065. filter=filter__
  2066. )
  2067. except TypeError:
  2068. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2069. filename = str(filename)
  2070. if filename == "":
  2071. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2072. return
  2073. # Update options
  2074. self.preferencesUiManager.defaults_read_form()
  2075. self.defaults.propagate_defaults()
  2076. # Save update options
  2077. try:
  2078. self.defaults.write(filename=filename)
  2079. except Exception:
  2080. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2081. return
  2082. if self.defaults["global_open_style"] is False:
  2083. self.file_opened.emit("preferences", filename)
  2084. self.file_saved.emit("preferences", filename)
  2085. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2086. def save_to_file(self, content_to_save, txt_content):
  2087. """
  2088. Save something to a file.
  2089. :return: None
  2090. """
  2091. self.defaults.report_usage("save_to_file")
  2092. App.log.debug("save_to_file()")
  2093. self.date = str(datetime.today()).rpartition('.')[0]
  2094. self.date = ''.join(c for c in self.date if c not in ':-')
  2095. self.date = self.date.replace(' ', '_')
  2096. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2097. path_to_save = self.defaults["global_last_save_folder"] if\
  2098. self.defaults["global_last_save_folder"] is not None else self.data_path
  2099. try:
  2100. filename, _f = FCFileSaveDialog.get_saved_filename(
  2101. caption=_("Save to file"),
  2102. directory=path_to_save + '/file_' + self.date,
  2103. filter=filter__
  2104. )
  2105. except TypeError:
  2106. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2107. filename = str(filename)
  2108. if filename == "":
  2109. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2110. return
  2111. else:
  2112. try:
  2113. with open(filename, 'w') as f:
  2114. ___ = f.read()
  2115. except PermissionError:
  2116. self.inform.emit('[WARNING] %s' %
  2117. _("Permission denied, saving not possible.\n"
  2118. "Most likely another app is holding the file open and not accessible."))
  2119. return
  2120. except IOError:
  2121. App.log.debug('Creating a new file ...')
  2122. f = open(filename, 'w')
  2123. f.close()
  2124. except Exception:
  2125. e = sys.exc_info()[0]
  2126. App.log.error("Could not load the file.")
  2127. App.log.error(str(e))
  2128. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2129. return
  2130. # Save content
  2131. if filename.rpartition('.')[2].lower() == 'html':
  2132. file_content = content_to_save
  2133. else:
  2134. file_content = txt_content
  2135. try:
  2136. with open(filename, "w") as f:
  2137. f.write(file_content)
  2138. except Exception:
  2139. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2140. return
  2141. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2142. def save_geometry(self, x, y, width, height, notebook_width):
  2143. """
  2144. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2145. launch of the application.
  2146. :param x: X position of the main window
  2147. :param y: Y position of the main window
  2148. :param width: width of the main window
  2149. :param height: height of the main window
  2150. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2151. :return: None
  2152. """
  2153. self.defaults["global_def_win_x"] = x
  2154. self.defaults["global_def_win_y"] = y
  2155. self.defaults["global_def_win_w"] = width
  2156. self.defaults["global_def_win_h"] = height
  2157. self.defaults["global_def_notebook_width"] = notebook_width
  2158. self.preferencesUiManager.save_defaults()
  2159. def restore_main_win_geom(self):
  2160. try:
  2161. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2162. self.defaults["global_def_win_y"],
  2163. self.defaults["global_def_win_w"],
  2164. self.defaults["global_def_win_h"])
  2165. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2166. except KeyError as e:
  2167. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2168. def message_dialog(self, title, message, kind="info"):
  2169. """
  2170. Builds and show a custom QMessageBox to be used in FlatCAM.
  2171. :param title: title of the QMessageBox
  2172. :param message: message to be displayed
  2173. :param kind: type of QMessageBox; will display a specific icon.
  2174. :return:
  2175. """
  2176. icon = {"info": QtWidgets.QMessageBox.Information,
  2177. "warning": QtWidgets.QMessageBox.Warning,
  2178. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2179. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2180. dlg.setText(message)
  2181. dlg.exec_()
  2182. def register_recent(self, kind, filename):
  2183. """
  2184. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2185. dictionary.
  2186. :param kind: type of file that was opened
  2187. :param filename: the path and file name for the file that was opened
  2188. :return:
  2189. """
  2190. self.log.debug("register_recent()")
  2191. self.log.debug(" %s" % kind)
  2192. self.log.debug(" %s" % filename)
  2193. record = {'kind': str(kind), 'filename': str(filename)}
  2194. if record in self.recent:
  2195. return
  2196. if record in self.recent_projects:
  2197. return
  2198. if record['kind'] == 'project':
  2199. self.recent_projects.insert(0, record)
  2200. else:
  2201. self.recent.insert(0, record)
  2202. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2203. self.recent.pop()
  2204. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2205. self.recent_projects.pop()
  2206. try:
  2207. f = open(self.data_path + '/recent.json', 'w')
  2208. except IOError:
  2209. App.log.error("Failed to open recent items file for writing.")
  2210. self.inform.emit('[ERROR_NOTCL] %s' %
  2211. _('Failed to open recent files file for writing.'))
  2212. return
  2213. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2214. f.close()
  2215. try:
  2216. fp = open(self.data_path + '/recent_projects.json', 'w')
  2217. except IOError:
  2218. App.log.error("Failed to open recent items file for writing.")
  2219. self.inform.emit('[ERROR_NOTCL] %s' %
  2220. _('Failed to open recent projects file for writing.'))
  2221. return
  2222. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2223. fp.close()
  2224. # Re-build the recent items menu
  2225. self.setup_recent_items()
  2226. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2227. """
  2228. Creates a new specialized FlatCAMObj and attaches it to the application,
  2229. this is, updates the GUI accordingly, any other records and plots it.
  2230. This method is thread-safe.
  2231. Notes:
  2232. * If the name is in use, the self.collection will modify it
  2233. when appending it to the collection. There is no need to handle
  2234. name conflicts here.
  2235. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2236. :type kind: str
  2237. :param name: Name for the object.
  2238. :type name: str
  2239. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2240. The function is called with 2 parameters: the new object and the App instance.
  2241. :type initialize: function
  2242. :param active:
  2243. :param fit:
  2244. :param plot: If to plot the resulting object
  2245. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2246. self.collection
  2247. :return: None
  2248. :rtype: None
  2249. """
  2250. App.log.debug("new_object()")
  2251. obj_plot = plot
  2252. obj_autoselected = autoselected
  2253. t0 = time.time() # Debug
  2254. # ## Create object
  2255. classdict = {
  2256. "gerber": GerberObject,
  2257. "excellon": ExcellonObject,
  2258. "cncjob": CNCJobObject,
  2259. "geometry": GeometryObject,
  2260. "script": ScriptObject,
  2261. "document": DocumentObject
  2262. }
  2263. App.log.debug("Calling object constructor...")
  2264. # Object creation/instantiation
  2265. obj = classdict[kind](name)
  2266. obj.units = self.options["units"]
  2267. # IMPORTANT
  2268. # The key names in defaults and options dictionary's are not random:
  2269. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2270. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2271. # copied to self.options. After that, below, depending on the type of
  2272. # object that is created, it will strip the name of the object and the underline (if the original key was
  2273. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2274. # "toolchange"
  2275. for option in self.options:
  2276. if option.find(kind + "_") == 0:
  2277. oname = option[len(kind) + 1:]
  2278. obj.options[oname] = self.options[option]
  2279. obj.isHovering = False
  2280. obj.notHovering = True
  2281. # Initialize as per user request
  2282. # User must take care to implement initialize
  2283. # in a thread-safe way as is is likely that we
  2284. # have been invoked in a separate thread.
  2285. t1 = time.time()
  2286. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2287. try:
  2288. return_value = initialize(obj, self)
  2289. except Exception as e:
  2290. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2291. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2292. msg += traceback.format_exc()
  2293. self.inform.emit(msg)
  2294. return "fail"
  2295. t2 = time.time()
  2296. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2297. if return_value == 'fail':
  2298. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2299. return "fail"
  2300. # Check units and convert if necessary
  2301. # This condition CAN be true because initialize() can change obj.units
  2302. if self.options["units"].upper() != obj.units.upper():
  2303. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2304. obj.convert_units(self.options["units"])
  2305. t3 = time.time()
  2306. self.log.debug("%f seconds converting units." % (t3 - t2))
  2307. # Create the bounding box for the object and then add the results to the obj.options
  2308. # But not for Scripts or for Documents
  2309. if kind != 'document' and kind != 'script':
  2310. try:
  2311. xmin, ymin, xmax, ymax = obj.bounds()
  2312. obj.options['xmin'] = xmin
  2313. obj.options['ymin'] = ymin
  2314. obj.options['xmax'] = xmax
  2315. obj.options['ymax'] = ymax
  2316. except Exception as e:
  2317. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2318. return "fail"
  2319. try:
  2320. if kind == 'excellon':
  2321. obj.fill_color = self.defaults["excellon_plot_fill"]
  2322. obj.outline_color = self.defaults["excellon_plot_line"]
  2323. if kind == 'gerber':
  2324. obj.fill_color = self.defaults["gerber_plot_fill"]
  2325. obj.outline_color = self.defaults["gerber_plot_line"]
  2326. except Exception as e:
  2327. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2328. # update the KeyWords list with the name of the file
  2329. self.myKeywords.append(obj.options['name'])
  2330. log.debug("Moving new object back to main thread.")
  2331. # Move the object to the main thread and let the app know that it is available.
  2332. obj.moveToThread(self.main_thread)
  2333. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2334. return obj
  2335. def new_excellon_object(self):
  2336. """
  2337. Creates a new, blank Excellon object.
  2338. :return: None
  2339. """
  2340. self.defaults.report_usage("new_excellon_object()")
  2341. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2342. def new_geometry_object(self):
  2343. """
  2344. Creates a new, blank and single-tool Geometry object.
  2345. :return: None
  2346. """
  2347. self.defaults.report_usage("new_geometry_object()")
  2348. def initialize(obj, app):
  2349. obj.multitool = False
  2350. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2351. def new_gerber_object(self):
  2352. """
  2353. Creates a new, blank Gerber object.
  2354. :return: None
  2355. """
  2356. self.defaults.report_usage("new_gerber_object()")
  2357. def initialize(grb_obj, app):
  2358. grb_obj.multitool = False
  2359. grb_obj.source_file = []
  2360. grb_obj.multigeo = False
  2361. grb_obj.follow = False
  2362. grb_obj.apertures = {}
  2363. grb_obj.solid_geometry = []
  2364. try:
  2365. grb_obj.options['xmin'] = 0
  2366. grb_obj.options['ymin'] = 0
  2367. grb_obj.options['xmax'] = 0
  2368. grb_obj.options['ymax'] = 0
  2369. except KeyError:
  2370. pass
  2371. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2372. def new_script_object(self, name=None, text=None):
  2373. """
  2374. Creates a new, blank TCL Script object.
  2375. :param name: a name for the new object
  2376. :param text: pass a source file to the newly created script to be loaded in it
  2377. :return: None
  2378. """
  2379. self.defaults.report_usage("new_script_object()")
  2380. if text is not None:
  2381. new_source_file = text
  2382. else:
  2383. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2384. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2385. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2386. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2387. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2388. # "ListSys, MillDrills,\n" \
  2389. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2390. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2391. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2392. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2393. # "# SubtractRectangle, Version, WriteGCode\n"
  2394. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2395. '# %s:\n' % _('TCL Tutorial is here') + \
  2396. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2397. '# %s:\n' % _("FlatCAM commands list")
  2398. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2399. "(displayed in Tcl Shell).")
  2400. def initialize(obj, app):
  2401. obj.source_file = deepcopy(new_source_file)
  2402. if name is None:
  2403. outname = 'new_script'
  2404. else:
  2405. outname = name
  2406. self.new_object('script', outname, initialize, plot=False)
  2407. def new_document_object(self):
  2408. """
  2409. Creates a new, blank Document object.
  2410. :return: None
  2411. """
  2412. self.defaults.report_usage("new_document_object()")
  2413. def initialize(obj, app):
  2414. obj.source_file = ""
  2415. self.new_object('document', 'new_document', initialize, plot=False)
  2416. def on_object_created(self, obj, plot, auto_select):
  2417. """
  2418. Event callback for object creation.
  2419. It will add the new object to the collection. After that it will plot the object in a threaded way
  2420. :param obj: The newly created FlatCAM object.
  2421. :param plot: if the newly create object t obe plotted
  2422. :param auto_select: if the newly created object to be autoselected after creation
  2423. :return: None
  2424. """
  2425. t0 = time.time() # DEBUG
  2426. self.log.debug("on_object_created()")
  2427. # The Collection might change the name if there is a collision
  2428. self.collection.append(obj)
  2429. # after adding the object to the collection always update the list of objects that are in the collection
  2430. self.all_objects_list = self.collection.get_list()
  2431. # self.inform.emit('[selected] %s created & selected: %s' %
  2432. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2433. if obj.kind == 'gerber':
  2434. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2435. kind=obj.kind.capitalize(),
  2436. color='green',
  2437. name=str(obj.options['name']), tx=_("created/selected"))
  2438. )
  2439. elif obj.kind == 'excellon':
  2440. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2441. kind=obj.kind.capitalize(),
  2442. color='brown',
  2443. name=str(obj.options['name']), tx=_("created/selected"))
  2444. )
  2445. elif obj.kind == 'cncjob':
  2446. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2447. kind=obj.kind.capitalize(),
  2448. color='blue',
  2449. name=str(obj.options['name']), tx=_("created/selected"))
  2450. )
  2451. elif obj.kind == 'geometry':
  2452. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2453. kind=obj.kind.capitalize(),
  2454. color='red',
  2455. name=str(obj.options['name']), tx=_("created/selected"))
  2456. )
  2457. elif obj.kind == 'script':
  2458. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2459. kind=obj.kind.capitalize(),
  2460. color='orange',
  2461. name=str(obj.options['name']), tx=_("created/selected"))
  2462. )
  2463. elif obj.kind == 'document':
  2464. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2465. kind=obj.kind.capitalize(),
  2466. color='darkCyan',
  2467. name=str(obj.options['name']), tx=_("created/selected"))
  2468. )
  2469. # update the SHELL auto-completer model with the name of the new object
  2470. self.shell._edit.set_model_data(self.myKeywords)
  2471. if auto_select:
  2472. # select the just opened object but deselect the previous ones
  2473. self.collection.set_all_inactive()
  2474. self.collection.set_active(obj.options["name"])
  2475. else:
  2476. self.collection.set_all_inactive()
  2477. # here it is done the object plotting
  2478. def worker_task(t_obj):
  2479. with self.proc_container.new(_("Plotting")):
  2480. if isinstance(t_obj, CNCJobObject):
  2481. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2482. else:
  2483. t_obj.plot()
  2484. t1 = time.time() # DEBUG
  2485. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2486. self.object_plotted.emit(t_obj)
  2487. # Send to worker
  2488. # self.worker.add_task(worker_task, [self])
  2489. if plot is True:
  2490. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2491. def on_object_changed(self, obj):
  2492. """
  2493. Called whenever the geometry of the object was changed in some way.
  2494. This require the update of it's bounding values so it can be the selected on canvas.
  2495. Update the bounding box data from obj.options
  2496. :param obj: the object that was changed
  2497. :return: None
  2498. """
  2499. xmin, ymin, xmax, ymax = obj.bounds()
  2500. obj.options['xmin'] = xmin
  2501. obj.options['ymin'] = ymin
  2502. obj.options['xmax'] = xmax
  2503. obj.options['ymax'] = ymax
  2504. log.debug("Object changed, updating the bounding box data on self.options")
  2505. # delete the old selection shape
  2506. self.delete_selection_shape()
  2507. self.should_we_save = True
  2508. def on_object_plotted(self):
  2509. """
  2510. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2511. :return: None
  2512. """
  2513. self.on_zoom_fit(None)
  2514. def on_about(self):
  2515. """
  2516. Displays the "about" dialog found in the Menu --> Help.
  2517. :return: None
  2518. """
  2519. self.defaults.report_usage("on_about")
  2520. version = self.version
  2521. version_date = self.version_date
  2522. beta = self.beta
  2523. class AboutDialog(QtWidgets.QDialog):
  2524. def __init__(self, app, parent=None):
  2525. QtWidgets.QDialog.__init__(self, parent)
  2526. self.app = app
  2527. # Icon and title
  2528. self.setWindowIcon(parent.app_icon)
  2529. self.setWindowTitle(_("About FlatCAM"))
  2530. self.resize(600, 200)
  2531. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2532. # self.setStyleSheet(
  2533. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2534. # "background-attachment: fixed"
  2535. # )
  2536. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2537. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2538. # palette = QtGui.QPalette()
  2539. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2540. # self.setPalette(palette)
  2541. logo = QtWidgets.QLabel()
  2542. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2543. title = QtWidgets.QLabel(
  2544. "<font size=8><B>FlatCAM</B></font><BR>"
  2545. "{title}<BR>"
  2546. "<BR>"
  2547. "<BR>"
  2548. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2549. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2550. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2551. "<B>{issue}</B></a><BR>".format(
  2552. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2553. devel=_("Development"),
  2554. down=_("DOWNLOAD"),
  2555. issue=_("Issue tracker"))
  2556. )
  2557. title.setOpenExternalLinks(True)
  2558. closebtn = QtWidgets.QPushButton(_("Close"))
  2559. tab_widget = QtWidgets.QTabWidget()
  2560. description_label = QtWidgets.QLabel(
  2561. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2562. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2563. version=version,
  2564. beta=('BETA' if beta else ''),
  2565. date=version_date,
  2566. arch=platform.architecture()[0])
  2567. )
  2568. description_label.setOpenExternalLinks(True)
  2569. lic_lbl_header = QtWidgets.QLabel(
  2570. '%s:<br>%s<br>' % (
  2571. _('Licensed under the MIT license'),
  2572. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2573. "http://www.opensource.org/licenses/mit-license.php</a>"
  2574. )
  2575. )
  2576. lic_lbl_header.setOpenExternalLinks(True)
  2577. lic_lbl_body = QtWidgets.QLabel(
  2578. _(
  2579. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2580. 'of this software and associated documentation files (the "Software"), to deal\n'
  2581. 'in the Software without restriction, including without limitation the rights\n'
  2582. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2583. 'copies of the Software, and to permit persons to whom the Software is\n'
  2584. 'furnished to do so, subject to the following conditions:\n\n'
  2585. 'The above copyright notice and this permission notice shall be included in\n'
  2586. 'all copies or substantial portions of the Software.\n\n'
  2587. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2588. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2589. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2590. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2591. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2592. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2593. 'THE SOFTWARE.'
  2594. )
  2595. )
  2596. attributions_label = QtWidgets.QLabel(
  2597. _(
  2598. 'Some of the icons used are from the following sources:<br>'
  2599. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2600. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2601. 'title="Flaticon">www.flaticon.com</a></div>'
  2602. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2603. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2604. )
  2605. )
  2606. attributions_label.setOpenExternalLinks(True)
  2607. # layouts
  2608. layout1 = QtWidgets.QVBoxLayout()
  2609. layout1_1 = QtWidgets.QHBoxLayout()
  2610. layout1_2 = QtWidgets.QHBoxLayout()
  2611. layout2 = QtWidgets.QHBoxLayout()
  2612. layout3 = QtWidgets.QHBoxLayout()
  2613. self.setLayout(layout1)
  2614. layout1.addLayout(layout1_1)
  2615. layout1.addLayout(layout1_2)
  2616. layout1.addLayout(layout2)
  2617. layout1.addLayout(layout3)
  2618. layout1_1.addStretch()
  2619. layout1_1.addWidget(description_label)
  2620. layout1_2.addWidget(tab_widget)
  2621. self.splash_tab = QtWidgets.QWidget()
  2622. self.splash_tab.setObjectName("splash_about")
  2623. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2624. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2625. tab_widget.addTab(self.splash_tab, _("Splash"))
  2626. self.programmmers_tab = QtWidgets.QWidget()
  2627. self.programmmers_tab.setObjectName("programmers_about")
  2628. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2629. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2630. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2631. self.translators_tab = QtWidgets.QWidget()
  2632. self.translators_tab.setObjectName("translators_about")
  2633. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2634. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2635. tab_widget.addTab(self.translators_tab, _("Translators"))
  2636. self.license_tab = QtWidgets.QWidget()
  2637. self.license_tab.setObjectName("license_about")
  2638. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2639. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2640. tab_widget.addTab(self.license_tab, _("License"))
  2641. self.attributions_tab = QtWidgets.QWidget()
  2642. self.attributions_tab.setObjectName("attributions_about")
  2643. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2644. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2645. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2646. self.splash_tab_layout.addWidget(logo, stretch=0)
  2647. self.splash_tab_layout.addWidget(title, stretch=1)
  2648. pal = QtGui.QPalette()
  2649. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2650. self.prog_grid_lay = QtWidgets.QGridLayout()
  2651. self.prog_grid_lay.setHorizontalSpacing(20)
  2652. self.prog_grid_lay.setColumnStretch(0, 0)
  2653. self.prog_grid_lay.setColumnStretch(2, 1)
  2654. prog_widget = QtWidgets.QWidget()
  2655. prog_widget.setLayout(self.prog_grid_lay)
  2656. prog_scroll = QtWidgets.QScrollArea()
  2657. prog_scroll.setWidget(prog_widget)
  2658. prog_scroll.setWidgetResizable(True)
  2659. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2660. prog_scroll.setPalette(pal)
  2661. self.programmmers_tab_layout.addWidget(prog_scroll)
  2662. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2663. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2664. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2665. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2704. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2705. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2706. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2707. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2708. self.translator_grid_lay = QtWidgets.QGridLayout()
  2709. self.translator_grid_lay.setColumnStretch(0, 0)
  2710. self.translator_grid_lay.setColumnStretch(1, 0)
  2711. self.translator_grid_lay.setColumnStretch(2, 1)
  2712. self.translator_grid_lay.setColumnStretch(3, 0)
  2713. # trans_widget = QtWidgets.QWidget()
  2714. # trans_widget.setLayout(self.translator_grid_lay)
  2715. # self.translators_tab_layout.addWidget(trans_widget)
  2716. # self.translators_tab_layout.addStretch()
  2717. trans_widget = QtWidgets.QWidget()
  2718. trans_widget.setLayout(self.translator_grid_lay)
  2719. trans_scroll = QtWidgets.QScrollArea()
  2720. trans_scroll.setWidget(trans_widget)
  2721. trans_scroll.setWidgetResizable(True)
  2722. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2723. trans_scroll.setPalette(pal)
  2724. self.translators_tab_layout.addWidget(trans_scroll)
  2725. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2726. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2727. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2728. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  2750. self.translator_grid_lay.setColumnStretch(0, 0)
  2751. self.translators_tab_layout.addStretch()
  2752. self.license_tab_layout.addWidget(lic_lbl_header)
  2753. self.license_tab_layout.addWidget(lic_lbl_body)
  2754. self.license_tab_layout.addStretch()
  2755. self.attributions_tab_layout.addWidget(attributions_label)
  2756. self.attributions_tab_layout.addStretch()
  2757. layout3.addStretch()
  2758. layout3.addWidget(closebtn)
  2759. closebtn.clicked.connect(self.accept)
  2760. AboutDialog(app=self, parent=self.ui).exec_()
  2761. def install_bookmarks(self, book_dict=None):
  2762. """
  2763. Install the bookmarks actions in the Help menu -> Bookmarks
  2764. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2765. :return: None
  2766. """
  2767. if book_dict is None:
  2768. self.defaults["global_bookmarks"].update(
  2769. {
  2770. '1': ['FlatCAM', "http://flatcam.org"],
  2771. '2': ['Backup Site', ""]
  2772. }
  2773. )
  2774. else:
  2775. self.defaults["global_bookmarks"].clear()
  2776. self.defaults["global_bookmarks"].update(book_dict)
  2777. # first try to disconnect if somehow they get connected from elsewhere
  2778. for act in self.ui.menuhelp_bookmarks.actions():
  2779. try:
  2780. act.triggered.disconnect()
  2781. except TypeError:
  2782. pass
  2783. # clear all actions except the last one who is the Bookmark manager
  2784. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2785. pass
  2786. else:
  2787. self.ui.menuhelp_bookmarks.removeAction(act)
  2788. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2789. if self.defaults["global_bookmarks"]:
  2790. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2791. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2792. # the JSON is first making the keys as strings (therefore I have to use strings too
  2793. # or do the conversion :(
  2794. # )
  2795. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2796. # the '10' entry jsut after '1' therefore ordering as strings
  2797. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2798. key=lambda x: int(x[0]))
  2799. for entry, bookmark in sorted_bookmarks:
  2800. title = bookmark[0]
  2801. weblink = bookmark[1]
  2802. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2803. act.setText(title)
  2804. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2805. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2806. if title == 'Backup Site' and weblink == "":
  2807. act.triggered.connect(self.on_backup_site)
  2808. else:
  2809. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2810. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2811. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2812. def on_bookmarks_manager(self):
  2813. """
  2814. Adds the bookmark manager in a Tab in Plot Area
  2815. :return:
  2816. """
  2817. for idx in range(self.ui.plot_tab_area.count()):
  2818. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2819. # there can be only one instance of Bookmark Manager at one time
  2820. return
  2821. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2822. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2823. # add the tab if it was closed
  2824. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2825. # delete the absolute and relative position and messages in the infobar
  2826. self.ui.position_label.setText("")
  2827. self.ui.rel_position_label.setText("")
  2828. # Switch plot_area to preferences page
  2829. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2830. def on_backup_site(self):
  2831. msgbox = QtWidgets.QMessageBox()
  2832. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2833. "1. FlatCAM.org website is down\n"
  2834. "2. Someone forked FlatCAM project and wants to point\n"
  2835. "to his own website\n\n"
  2836. "If you can't get any informations about FlatCAM beta\n"
  2837. "use the YouTube channel link from the Help menu."))
  2838. msgbox.setWindowTitle(_("Alternative website"))
  2839. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2840. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2841. msgbox.setDefaultButton(bt_yes)
  2842. msgbox.exec_()
  2843. # response = msgbox.clickedButton()
  2844. def on_file_savedefaults(self):
  2845. """
  2846. Callback for menu item File->Save Defaults. Saves application default options
  2847. ``self.defaults`` to current_defaults.FlatConfig.
  2848. :return: None
  2849. """
  2850. self.preferencesUiManager.save_defaults()
  2851. def final_save(self):
  2852. """
  2853. Callback for doing a preferences save to file whenever the application is about to quit.
  2854. If the project has changes, it will ask the user to save the project.
  2855. :return: None
  2856. """
  2857. if self.save_in_progress:
  2858. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2859. return
  2860. if self.should_we_save and self.collection.get_list():
  2861. msgbox = QtWidgets.QMessageBox()
  2862. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2863. "\n"
  2864. "Do you want to Save the project?"))
  2865. msgbox.setWindowTitle(_("Save changes"))
  2866. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2867. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2868. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2869. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2870. msgbox.setDefaultButton(bt_yes)
  2871. msgbox.exec_()
  2872. response = msgbox.clickedButton()
  2873. if response == bt_yes:
  2874. try:
  2875. self.trayIcon.hide()
  2876. except Exception:
  2877. pass
  2878. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2879. elif response == bt_no:
  2880. try:
  2881. self.trayIcon.hide()
  2882. except Exception:
  2883. pass
  2884. self.quit_application()
  2885. elif response == bt_cancel:
  2886. return
  2887. else:
  2888. try:
  2889. self.trayIcon.hide()
  2890. except Exception:
  2891. pass
  2892. self.quit_application()
  2893. def quit_application(self):
  2894. """
  2895. Called (as a pyslot or not) when the application is quit.
  2896. :return: None
  2897. """
  2898. self.preferencesUiManager.save_defaults(silent=True)
  2899. log.debug("App.quit_application() --> App Defaults saved.")
  2900. if self.cmd_line_headless != 1:
  2901. # save app state to file
  2902. stgs = QSettings("Open Source", "FlatCAM")
  2903. stgs.setValue('saved_gui_state', self.ui.saveState())
  2904. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2905. stgs.setValue(
  2906. 'language',
  2907. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2908. )
  2909. stgs.setValue(
  2910. 'notebook_font_size',
  2911. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2912. )
  2913. stgs.setValue(
  2914. 'axis_font_size',
  2915. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2916. )
  2917. stgs.setValue(
  2918. 'textbox_font_size',
  2919. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2920. )
  2921. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2922. stgs.setValue(
  2923. 'machinist',
  2924. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2925. )
  2926. # This will write the setting to the platform specific storage.
  2927. del stgs
  2928. log.debug("App.quit_application() --> App UI state saved.")
  2929. # try to quit the Socket opened by ArgsThread class
  2930. try:
  2931. self.new_launch.thread_exit = True
  2932. self.new_launch.listener.close()
  2933. except Exception as err:
  2934. log.debug("App.quit_application() --> %s" % str(err))
  2935. # try to quit the QThread that run ArgsThread class
  2936. try:
  2937. self.th.terminate()
  2938. except Exception as e:
  2939. log.debug("App.quit_application() --> %s" % str(e))
  2940. # terminate workers
  2941. self.workers.__del__()
  2942. # quit app by signalling for self.kill_app() method
  2943. # self.close_app_signal.emit()
  2944. QtWidgets.qApp.quit()
  2945. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2946. # we use the following command
  2947. # sys.exit(0)
  2948. os._exit(0) # fix to work with Python 3.8
  2949. @staticmethod
  2950. def kill_app():
  2951. # QtCore.QCoreApplication.quit()
  2952. QtWidgets.qApp.quit()
  2953. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2954. # we use the following command
  2955. sys.exit(0)
  2956. def on_portable_checked(self, state):
  2957. """
  2958. Callback called when the checkbox in Preferences GUI is checked.
  2959. It will set the application as portable by creating the preferences and recent files in the
  2960. 'config' folder found in the FlatCAM installation folder.
  2961. :param state: boolean, the state of the checkbox when clicked/checked
  2962. :return:
  2963. """
  2964. line_no = 0
  2965. data = None
  2966. if sys.platform != 'win32':
  2967. # this won't work in Linux or MacOS
  2968. return
  2969. # test if the app was frozen and choose the path for the configuration file
  2970. if getattr(sys, "frozen", False) is True:
  2971. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2972. else:
  2973. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2974. config_file = current_data_path + '\\configuration.txt'
  2975. try:
  2976. with open(config_file, 'r') as f:
  2977. try:
  2978. data = f.readlines()
  2979. except Exception as e:
  2980. log.debug('App.__init__() -->%s' % str(e))
  2981. return
  2982. except FileNotFoundError:
  2983. pass
  2984. for line in data:
  2985. line = line.strip('\n')
  2986. param = str(line).rpartition('=')
  2987. if param[0] == 'portable':
  2988. break
  2989. line_no += 1
  2990. if state:
  2991. data[line_no] = 'portable=True\n'
  2992. # create the new defauults files
  2993. # create current_defaults.FlatConfig file if there is none
  2994. try:
  2995. f = open(current_data_path + '/current_defaults.FlatConfig')
  2996. f.close()
  2997. except IOError:
  2998. App.log.debug('Creating empty current_defaults.FlatConfig')
  2999. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3000. json.dump({}, f)
  3001. f.close()
  3002. # create factory_defaults.FlatConfig file if there is none
  3003. try:
  3004. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3005. f.close()
  3006. except IOError:
  3007. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3008. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3009. json.dump({}, f)
  3010. f.close()
  3011. try:
  3012. f = open(current_data_path + '/recent.json')
  3013. f.close()
  3014. except IOError:
  3015. App.log.debug('Creating empty recent.json')
  3016. f = open(current_data_path + '/recent.json', 'w')
  3017. json.dump([], f)
  3018. f.close()
  3019. try:
  3020. fp = open(current_data_path + '/recent_projects.json')
  3021. fp.close()
  3022. except IOError:
  3023. App.log.debug('Creating empty recent_projects.json')
  3024. fp = open(current_data_path + '/recent_projects.json', 'w')
  3025. json.dump([], fp)
  3026. fp.close()
  3027. # save the current defaults to the new defaults file
  3028. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3029. else:
  3030. data[line_no] = 'portable=False\n'
  3031. with open(config_file, 'w') as f:
  3032. f.writelines(data)
  3033. def on_register_files(self, obj_type=None):
  3034. """
  3035. Called whenever there is a need to register file extensions with FlatCAM.
  3036. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3037. :param obj_type: the type of object to be register for.
  3038. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3039. :return: None
  3040. """
  3041. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3042. new_reg_path = 'Software\\Classes\\'
  3043. # find if the current user is admin
  3044. try:
  3045. is_admin = os.getuid() == 0
  3046. except AttributeError:
  3047. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3048. if is_admin is True:
  3049. root_path = winreg.HKEY_LOCAL_MACHINE
  3050. else:
  3051. root_path = winreg.HKEY_CURRENT_USER
  3052. # create the keys
  3053. def set_reg(name, root_path, new_reg_path, value):
  3054. try:
  3055. winreg.CreateKey(root_path, new_reg_path)
  3056. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3057. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3058. return True
  3059. except WindowsError:
  3060. return False
  3061. # delete key in registry
  3062. def delete_reg(root_path, reg_path, key_to_del):
  3063. key_to_del_path = reg_path + key_to_del
  3064. try:
  3065. winreg.DeleteKey(root_path, key_to_del_path)
  3066. return True
  3067. except WindowsError:
  3068. return False
  3069. if obj_type is None or obj_type == 'excellon':
  3070. exc_list = \
  3071. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3072. exc_list = [x for x in exc_list if x != '']
  3073. # register all keys in the Preferences window
  3074. for ext in exc_list:
  3075. new_k = new_reg_path + '.%s' % ext
  3076. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3077. # and unregister those that are no longer in the Preferences windows but are in the file
  3078. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3079. if ext not in exc_list:
  3080. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3081. # now write the updated extensions to the self.defaults
  3082. # new_ext = ''
  3083. # for ext in exc_list:
  3084. # new_ext = new_ext + ext + ', '
  3085. # self.defaults["fa_excellon"] = new_ext
  3086. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3087. if obj_type is None or obj_type == 'gcode':
  3088. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3089. gco_list = [x for x in gco_list if x != '']
  3090. # register all keys in the Preferences window
  3091. for ext in gco_list:
  3092. new_k = new_reg_path + '.%s' % ext
  3093. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3094. # and unregister those that are no longer in the Preferences windows but are in the file
  3095. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3096. if ext not in gco_list:
  3097. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3098. # now write the updated extensions to the self.defaults
  3099. # new_ext = ''
  3100. # for ext in gco_list:
  3101. # new_ext = new_ext + ext + ', '
  3102. # self.defaults["fa_gcode"] = new_ext
  3103. self.inform.emit('[success] %s' %
  3104. _("Selected GCode file extensions registered with FlatCAM."))
  3105. if obj_type is None or obj_type == 'gerber':
  3106. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3107. grb_list = [x for x in grb_list if x != '']
  3108. # register all keys in the Preferences window
  3109. for ext in grb_list:
  3110. new_k = new_reg_path + '.%s' % ext
  3111. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3112. # and unregister those that are no longer in the Preferences windows but are in the file
  3113. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3114. if ext not in grb_list:
  3115. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3116. # now write the updated extensions to the self.defaults
  3117. # new_ext = ''
  3118. # for ext in grb_list:
  3119. # new_ext = new_ext + ext + ', '
  3120. # self.defaults["fa_gerber"] = new_ext
  3121. self.inform.emit('[success] %s' %
  3122. _("Selected Gerber file extensions registered with FlatCAM."))
  3123. def add_extension(self, ext_type):
  3124. """
  3125. Add a file extension to the list for a specific object
  3126. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3127. :return:
  3128. """
  3129. if ext_type == 'excellon':
  3130. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3131. if new_ext == '':
  3132. return
  3133. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3134. if new_ext in old_val:
  3135. return
  3136. old_val.append(new_ext)
  3137. old_val.sort()
  3138. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3139. if ext_type == 'gcode':
  3140. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3141. if new_ext == '':
  3142. return
  3143. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3144. if new_ext in old_val:
  3145. return
  3146. old_val.append(new_ext)
  3147. old_val.sort()
  3148. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3149. if ext_type == 'gerber':
  3150. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3151. if new_ext == '':
  3152. return
  3153. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3154. if new_ext in old_val:
  3155. return
  3156. old_val.append(new_ext)
  3157. old_val.sort()
  3158. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3159. if ext_type == 'keyword':
  3160. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3161. if new_kw == '':
  3162. return
  3163. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3164. if new_kw in old_val:
  3165. return
  3166. old_val.append(new_kw)
  3167. old_val.sort()
  3168. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3169. # update the self.myKeywords so the model is updated
  3170. self.autocomplete_kw_list = \
  3171. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3172. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3173. self.shell._edit.set_model_data(self.myKeywords)
  3174. def del_extension(self, ext_type):
  3175. """
  3176. Remove a file extension from the list for a specific object
  3177. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3178. :return:
  3179. """
  3180. if ext_type == 'excellon':
  3181. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3182. if new_ext == '':
  3183. return
  3184. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3185. if new_ext not in old_val:
  3186. return
  3187. old_val.remove(new_ext)
  3188. old_val.sort()
  3189. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3190. if ext_type == 'gcode':
  3191. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3192. if new_ext == '':
  3193. return
  3194. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3195. if new_ext not in old_val:
  3196. return
  3197. old_val.remove(new_ext)
  3198. old_val.sort()
  3199. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3200. if ext_type == 'gerber':
  3201. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3202. if new_ext == '':
  3203. return
  3204. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3205. if new_ext not in old_val:
  3206. return
  3207. old_val.remove(new_ext)
  3208. old_val.sort()
  3209. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3210. if ext_type == 'keyword':
  3211. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3212. if new_kw == '':
  3213. return
  3214. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3215. if new_kw not in old_val:
  3216. return
  3217. old_val.remove(new_kw)
  3218. old_val.sort()
  3219. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3220. # update the self.myKeywords so the model is updated
  3221. self.autocomplete_kw_list = \
  3222. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3223. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3224. self.shell._edit.set_model_data(self.myKeywords)
  3225. def restore_extensions(self, ext_type):
  3226. """
  3227. Restore all file extensions associations with FlatCAM, for a specific object
  3228. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3229. :return:
  3230. """
  3231. if ext_type == 'excellon':
  3232. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3233. # for the ability to open Excellon files with .txt extension
  3234. new_exc_list = deepcopy(self.exc_list)
  3235. try:
  3236. new_exc_list.remove('txt')
  3237. except ValueError:
  3238. pass
  3239. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3240. if ext_type == 'gcode':
  3241. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3242. if ext_type == 'gerber':
  3243. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3244. if ext_type == 'keyword':
  3245. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3246. # update the self.myKeywords so the model is updated
  3247. self.autocomplete_kw_list = self.default_keywords
  3248. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3249. self.shell._edit.set_model_data(self.myKeywords)
  3250. def delete_all_extensions(self, ext_type):
  3251. """
  3252. Delete all file extensions associations with FlatCAM, for a specific object
  3253. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3254. :return:
  3255. """
  3256. if ext_type == 'excellon':
  3257. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3258. if ext_type == 'gcode':
  3259. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3260. if ext_type == 'gerber':
  3261. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3262. if ext_type == 'keyword':
  3263. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3264. # update the self.myKeywords so the model is updated
  3265. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3266. self.shell._edit.set_model_data(self.myKeywords)
  3267. def on_edit_join(self, name=None):
  3268. """
  3269. Callback for Edit->Join. Joins the selected geometry objects into
  3270. a new one.
  3271. :return: None
  3272. """
  3273. self.defaults.report_usage("on_edit_join()")
  3274. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3275. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3276. geo_type_set = set()
  3277. objs = self.collection.get_selected()
  3278. if len(objs) < 2:
  3279. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3280. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3281. return 'fail'
  3282. for obj in objs:
  3283. geo_type_set.add(obj.multigeo)
  3284. # if len(geo_type_list) == 1 means that all list elements are the same
  3285. if len(geo_type_set) != 1:
  3286. self.inform.emit('[ERROR] %s' %
  3287. _("Failed join. The Geometry objects are of different types.\n"
  3288. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3289. "convert from one to another and retry joining \n"
  3290. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3291. "the result may not be what was expected. \n"
  3292. "Check the generated GCODE."))
  3293. return
  3294. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3295. if True in geo_type_set:
  3296. def initialize(geo_obj, app):
  3297. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  3298. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3299. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3300. for v in geo_obj.tools.values():
  3301. v['data']['name'] = obj_name_multi
  3302. self.new_object("geometry", obj_name_multi, initialize)
  3303. else:
  3304. def initialize(geo_obj, app):
  3305. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  3306. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3307. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3308. for v in geo_obj.tools.values():
  3309. v['data']['name'] = obj_name_single
  3310. self.new_object("geometry", obj_name_single, initialize)
  3311. self.should_we_save = True
  3312. def on_edit_join_exc(self):
  3313. """
  3314. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3315. a new Excellon.
  3316. :return: None
  3317. """
  3318. self.defaults.report_usage("on_edit_join_exc()")
  3319. objs = self.collection.get_selected()
  3320. for obj in objs:
  3321. if not isinstance(obj, ExcellonObject):
  3322. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3323. return
  3324. if len(objs) < 2:
  3325. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3326. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3327. return 'fail'
  3328. def initialize(exc_obj, app):
  3329. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj)
  3330. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3331. self.new_object("excellon", 'Combo_Excellon', initialize)
  3332. self.should_we_save = True
  3333. def on_edit_join_grb(self):
  3334. """
  3335. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3336. a new Gerber object.
  3337. :return: None
  3338. """
  3339. self.defaults.report_usage("on_edit_join_grb()")
  3340. objs = self.collection.get_selected()
  3341. for obj in objs:
  3342. if not isinstance(obj, GerberObject):
  3343. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3344. return
  3345. if len(objs) < 2:
  3346. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3347. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3348. return 'fail'
  3349. def initialize(grb_obj, app):
  3350. GerberObject.merge(self, grb_list=objs, grb_final=grb_obj)
  3351. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3352. self.new_object("gerber", 'Combo_Gerber', initialize)
  3353. self.should_we_save = True
  3354. def on_convert_singlegeo_to_multigeo(self):
  3355. """
  3356. Called for converting a Geometry object from single-geo to multi-geo.
  3357. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3358. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3359. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3360. the solid-geometry of that tool.
  3361. :return: None
  3362. """
  3363. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3364. obj = self.collection.get_active()
  3365. if obj is None:
  3366. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3367. return
  3368. if not isinstance(obj, GeometryObject):
  3369. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3370. return
  3371. obj.multigeo = True
  3372. for tooluid, dict_value in obj.tools.items():
  3373. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3374. if not isinstance(obj.solid_geometry, list):
  3375. obj.solid_geometry = [obj.solid_geometry]
  3376. obj.solid_geometry[:] = []
  3377. obj.plot()
  3378. self.should_we_save = True
  3379. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3380. def on_convert_multigeo_to_singlegeo(self):
  3381. """
  3382. Called for converting a Geometry object from multi-geo to single-geo.
  3383. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3384. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3385. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3386. the solid-geometry of that tool.
  3387. :return: None
  3388. """
  3389. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3390. obj = self.collection.get_active()
  3391. if obj is None:
  3392. self.inform.emit('[ERROR_NOTCL] %s' %
  3393. _("Failed. Select a Geometry Object and try again."))
  3394. return
  3395. if not isinstance(obj, GeometryObject):
  3396. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3397. (_("Expected a GeometryObject, got"), type(obj)))
  3398. return
  3399. obj.multigeo = False
  3400. total_solid_geometry = []
  3401. for tooluid, dict_value in obj.tools.items():
  3402. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3403. # clear the original geometry
  3404. dict_value['solid_geometry'][:] = []
  3405. obj.solid_geometry = deepcopy(total_solid_geometry)
  3406. obj.plot()
  3407. self.should_we_save = True
  3408. self.inform.emit('[success] %s' %
  3409. _("A Geometry object was converted to SingleGeo type."))
  3410. def on_defaults_dict_change(self, field):
  3411. """
  3412. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3413. Edit -> Preferences tab window.
  3414. :param field: the key of the self.defaults dictionary that was changed.
  3415. :return: None
  3416. """
  3417. self.preferencesUiManager.defaults_write_form_field(field=field)
  3418. if field == "units":
  3419. self.set_screen_units(self.defaults['units'])
  3420. def set_screen_units(self, units):
  3421. """
  3422. Set the FlatCAM units on the status bar.
  3423. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3424. :return: None
  3425. """
  3426. self.ui.units_label.setText("[" + units.lower() + "]")
  3427. def on_toggle_units_click(self):
  3428. try:
  3429. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3430. except (TypeError, AttributeError):
  3431. pass
  3432. if self.defaults["units"] == 'MM':
  3433. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3434. else:
  3435. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3436. self.on_toggle_units(no_pref=True)
  3437. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3438. lambda: self.on_toggle_units(no_pref=False))
  3439. def on_toggle_units(self, no_pref=False):
  3440. """
  3441. Callback for the Units radio-button change in the Preferences tab.
  3442. Changes the application's default units adn for the project too.
  3443. If changing the project's units, the change propagates to all of
  3444. the objects in the project.
  3445. :return: None
  3446. """
  3447. self.defaults.report_usage("on_toggle_units")
  3448. if self.toggle_units_ignore:
  3449. return
  3450. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3451. # If option is the same, then ignore
  3452. if new_units == self.defaults["units"].upper():
  3453. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3454. return
  3455. # Options to scale
  3456. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  3457. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3458. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3459. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3460. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3461. "excellon_feedrate_probe",
  3462. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3463. "excellon_editor_slot_lin_pitch",
  3464. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3465. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3466. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3467. "geometry_z_pdepth",
  3468. "geometry_feedrate_probe", "geometry_startz",
  3469. 'cncjob_tooldia',
  3470. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3471. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3472. "tools_nccnewdia",
  3473. "tools_2sided_drilldia", "tools_film_boundary",
  3474. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3475. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3476. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3477. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3478. "tools_transform_offset_y",
  3479. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3480. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3481. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3482. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3483. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3484. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3485. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  3486. "tools_fiducials_line_thickness",
  3487. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3488. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3489. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3490. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3491. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3492. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3493. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3494. def scale_defaults(sfactor):
  3495. for dim in dimensions:
  3496. if dim == 'excellon_toolchangexy':
  3497. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3498. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3499. coords_xy[0] *= sfactor
  3500. coords_xy[1] *= sfactor
  3501. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3502. self.decimals, coords_xy[1])
  3503. elif dim == 'geometry_toolchangexy':
  3504. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3505. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3506. coords_xy[0] *= sfactor
  3507. coords_xy[1] *= sfactor
  3508. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3509. self.decimals, coords_xy[1])
  3510. elif dim == 'excellon_endxy':
  3511. coordinates = self.defaults["excellon_endxy"].split(",")
  3512. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3513. end_coords_xy[0] *= sfactor
  3514. end_coords_xy[1] *= sfactor
  3515. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3516. self.decimals, end_coords_xy[1])
  3517. elif dim == 'geometry_endxy':
  3518. coordinates = self.defaults["geometry_endxy"].split(",")
  3519. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3520. end_coords_xy[0] *= sfactor
  3521. end_coords_xy[1] *= sfactor
  3522. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3523. self.decimals, end_coords_xy[1])
  3524. elif dim == 'geometry_cnctooldia':
  3525. if type(self.defaults["geometry_cnctooldia"]) == float:
  3526. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  3527. else:
  3528. try:
  3529. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3530. tools_diameters = [eval(a) for a in tools_string if a != '']
  3531. except Exception as e:
  3532. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3533. continue
  3534. self.defaults['geometry_cnctooldia'] = ''
  3535. for t in range(len(tools_diameters)):
  3536. tools_diameters[t] *= sfactor
  3537. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  3538. elif dim == 'tools_ncctools':
  3539. if type(self.defaults["tools_ncctools"]) == float:
  3540. ncctools = [self.defaults["tools_ncctools"]]
  3541. else:
  3542. try:
  3543. tools_string = self.defaults["tools_ncctools"].split(",")
  3544. ncctools = [eval(a) for a in tools_string if a != '']
  3545. except Exception as e:
  3546. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3547. continue
  3548. self.defaults['tools_ncctools'] = ''
  3549. for t in range(len(ncctools)):
  3550. ncctools[t] *= sfactor
  3551. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  3552. elif dim == 'tools_solderpaste_tools':
  3553. if type(self.defaults["tools_solderpaste_tools"]) == float:
  3554. sptools = [self.defaults["tools_solderpaste_tools"]]
  3555. else:
  3556. try:
  3557. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3558. sptools = [eval(a) for a in tools_string if a != '']
  3559. except Exception as e:
  3560. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3561. continue
  3562. self.defaults['tools_solderpaste_tools'] = ""
  3563. for t in range(len(sptools)):
  3564. sptools[t] *= sfactor
  3565. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  3566. elif dim == 'tools_solderpaste_xy_toolchange':
  3567. try:
  3568. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3569. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3570. sp_coords[0] *= sfactor
  3571. sp_coords[1] *= sfactor
  3572. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  3573. self.decimals, sp_coords[1])
  3574. except Exception as e:
  3575. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3576. continue
  3577. elif dim == 'global_gridx' or dim == 'global_gridy':
  3578. if new_units == 'IN':
  3579. try:
  3580. val = float(self.defaults[dim]) * sfactor
  3581. except Exception as e:
  3582. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3583. continue
  3584. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3585. else:
  3586. try:
  3587. val = float(self.defaults[dim]) * sfactor
  3588. except Exception as e:
  3589. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3590. continue
  3591. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3592. else:
  3593. if self.defaults[dim]:
  3594. try:
  3595. val = float(self.defaults[dim]) * sfactor
  3596. except Exception as e:
  3597. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3598. continue
  3599. self.defaults[dim] = val
  3600. # The scaling factor depending on choice of units.
  3601. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3602. # Changing project units. Warn user.
  3603. msgbox = QtWidgets.QMessageBox()
  3604. msgbox.setWindowTitle(_("Toggle Units"))
  3605. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3606. msgbox.setText(_("Changing the units of the project\n"
  3607. "will scale all objects.\n\n"
  3608. "Do you want to continue?"))
  3609. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3610. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3611. msgbox.setDefaultButton(bt_ok)
  3612. msgbox.exec_()
  3613. response = msgbox.clickedButton()
  3614. if response == bt_ok:
  3615. if no_pref is False:
  3616. self.preferencesUiManager.defaults_read_form()
  3617. scale_defaults(factor)
  3618. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3619. self.defaults["units"] = new_units
  3620. # update the defaults from form, some may assume that the conversion is enough and it's not
  3621. self.on_options_app2project()
  3622. # update the objects
  3623. for obj in self.collection.get_list():
  3624. obj.convert_units(new_units)
  3625. # make that the properties stored in the object are also updated
  3626. self.object_changed.emit(obj)
  3627. # rebuild the object UI
  3628. obj.build_ui()
  3629. # change this only if the workspace is active
  3630. if self.defaults['global_workspace'] is True:
  3631. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3632. # adjust the grid values on the main toolbar
  3633. val_x = float(self.defaults['global_gridx']) * factor
  3634. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3635. current = self.collection.get_active()
  3636. if current is not None:
  3637. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3638. if not isinstance(current, GeometryObject):
  3639. current.to_form()
  3640. # replot all objects
  3641. self.plot_all()
  3642. # set the status labels to reflect the current FlatCAM units
  3643. self.set_screen_units(new_units)
  3644. # signal to the app that we changed the object properties and it shoud save the project
  3645. self.should_we_save = True
  3646. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3647. else:
  3648. # Undo toggling
  3649. self.toggle_units_ignore = True
  3650. if self.defaults['units'].upper() == 'MM':
  3651. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3652. else:
  3653. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3654. self.toggle_units_ignore = False
  3655. # store the grid values so they are not changed in the next step
  3656. val_x = float(self.defaults['global_gridx'])
  3657. val_y = float(self.defaults['global_gridy'])
  3658. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3659. self.preferencesUiManager.defaults_read_form()
  3660. # the self.preferencesUiManager.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  3661. # I don't want it for the grid values, so I update them here
  3662. self.defaults['global_gridx'] = val_x
  3663. self.defaults['global_gridy'] = val_y
  3664. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3665. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3666. def on_fullscreen(self, disable=False):
  3667. self.defaults.report_usage("on_fullscreen()")
  3668. flags = self.ui.windowFlags()
  3669. if self.toggle_fscreen is False and disable is False:
  3670. # self.ui.showFullScreen()
  3671. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3672. a = self.ui.geometry()
  3673. self.x_pos = a.x()
  3674. self.y_pos = a.y()
  3675. self.width = a.width()
  3676. self.height = a.height()
  3677. # set new geometry to full desktop rect
  3678. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3679. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3680. # everything else will not work without this hack. This happen in Windows.
  3681. # https://bugreports.qt.io/browse/QTBUG-41309
  3682. desktop = QtWidgets.QApplication.desktop()
  3683. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3684. rec = desktop.screenGeometry(screen)
  3685. x = rec.x() - 1
  3686. y = rec.y() - 1
  3687. h = rec.height() + 2
  3688. w = rec.width() + 2
  3689. self.ui.setGeometry(x, y, w, h)
  3690. self.ui.show()
  3691. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3692. tb.setVisible(False)
  3693. self.ui.splitter_left.setVisible(False)
  3694. self.toggle_fscreen = True
  3695. elif self.toggle_fscreen is True or disable is True:
  3696. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3697. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3698. self.ui.showNormal()
  3699. self.restore_toolbar_view()
  3700. self.ui.splitter_left.setVisible(True)
  3701. self.toggle_fscreen = False
  3702. def on_toggle_plotarea(self):
  3703. self.defaults.report_usage("on_toggle_plotarea()")
  3704. try:
  3705. name = self.ui.plot_tab_area.widget(0).objectName()
  3706. except AttributeError:
  3707. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3708. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3709. self.ui.plot_tab_area.protectTab(0)
  3710. return
  3711. if name != 'plotarea':
  3712. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3713. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3714. self.ui.plot_tab_area.protectTab(0)
  3715. else:
  3716. self.ui.plot_tab_area.closeTab(0)
  3717. def on_toggle_notebook(self):
  3718. if self.ui.splitter.sizes()[0] == 0:
  3719. self.ui.splitter.setSizes([1, 1])
  3720. self.ui.menu_toggle_nb.setChecked(True)
  3721. else:
  3722. self.ui.splitter.setSizes([0, 1])
  3723. self.ui.menu_toggle_nb.setChecked(False)
  3724. def on_toggle_axis(self):
  3725. self.defaults.report_usage("on_toggle_axis()")
  3726. if self.toggle_axis is False:
  3727. if self.is_legacy is False:
  3728. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3729. parent=self.plotcanvas.view.scene)
  3730. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3731. parent=self.plotcanvas.view.scene)
  3732. else:
  3733. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3734. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3735. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3736. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3737. self.plotcanvas.canvas.draw()
  3738. self.toggle_axis = True
  3739. else:
  3740. if self.is_legacy is False:
  3741. self.plotcanvas.v_line.parent = None
  3742. self.plotcanvas.h_line.parent = None
  3743. else:
  3744. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3745. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3746. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3747. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3748. self.plotcanvas.canvas.draw()
  3749. self.toggle_axis = False
  3750. def on_toggle_grid(self):
  3751. self.defaults.report_usage("on_toggle_grid()")
  3752. self.ui.grid_snap_btn.trigger()
  3753. self.on_grid_snap_triggered(state=True)
  3754. def on_toggle_grid_lines(self):
  3755. self.defaults.report_usage("on_toggle_grd_lines()")
  3756. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3757. if tt_settings.contains("theme"):
  3758. theme = tt_settings.value('theme', type=str)
  3759. else:
  3760. theme = 'white'
  3761. if self.toggle_grid_lines is False:
  3762. if self.is_legacy is False:
  3763. if theme == 'white':
  3764. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3765. else:
  3766. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3767. else:
  3768. self.plotcanvas.axes.grid(True)
  3769. try:
  3770. self.plotcanvas.canvas.draw()
  3771. except IndexError:
  3772. pass
  3773. pass
  3774. self.toggle_grid_lines = True
  3775. else:
  3776. if self.is_legacy is False:
  3777. if theme == 'white':
  3778. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3779. else:
  3780. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3781. else:
  3782. self.plotcanvas.axes.grid(False)
  3783. try:
  3784. self.plotcanvas.canvas.draw()
  3785. except IndexError:
  3786. pass
  3787. self.toggle_grid_lines = False
  3788. if self.is_legacy is False:
  3789. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3790. # - perhaps is a bug in VisPy implementation
  3791. if self.grid_status() is True:
  3792. self.app_cursor.enabled = False
  3793. self.app_cursor.enabled = True
  3794. else:
  3795. self.app_cursor.enabled = True
  3796. self.app_cursor.enabled = False
  3797. def on_update_exc_export(self, state):
  3798. """
  3799. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3800. if the update_excellon_cb checkbox is checked
  3801. :param state: state of the checkbox whose signals is tied to his slot
  3802. :return:
  3803. """
  3804. if state:
  3805. # first try to disconnect
  3806. try:
  3807. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3808. disconnect(self.on_excellon_format_changed)
  3809. except TypeError:
  3810. pass
  3811. try:
  3812. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3813. disconnect(self.on_excellon_format_changed)
  3814. except TypeError:
  3815. pass
  3816. try:
  3817. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3818. disconnect(self.on_excellon_format_changed)
  3819. except TypeError:
  3820. pass
  3821. try:
  3822. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3823. disconnect(self.on_excellon_format_changed)
  3824. except TypeError:
  3825. pass
  3826. try:
  3827. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3828. disconnect(self.on_excellon_zeros_changed)
  3829. except TypeError:
  3830. pass
  3831. try:
  3832. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3833. disconnect(self.on_excellon_zeros_changed)
  3834. except TypeError:
  3835. pass
  3836. # the connect them
  3837. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3838. self.on_excellon_format_changed)
  3839. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3840. self.on_excellon_format_changed)
  3841. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3842. self.on_excellon_format_changed)
  3843. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3844. self.on_excellon_format_changed)
  3845. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3846. self.on_excellon_zeros_changed)
  3847. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3848. self.on_excellon_units_changed)
  3849. else:
  3850. # disconnect the signals
  3851. try:
  3852. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3853. disconnect(self.on_excellon_format_changed)
  3854. except TypeError:
  3855. pass
  3856. try:
  3857. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3858. disconnect(self.on_excellon_format_changed)
  3859. except TypeError:
  3860. pass
  3861. try:
  3862. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3863. disconnect(self.on_excellon_format_changed)
  3864. except TypeError:
  3865. pass
  3866. try:
  3867. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3868. disconnect(self.on_excellon_format_changed)
  3869. except TypeError:
  3870. pass
  3871. try:
  3872. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3873. disconnect(self.on_excellon_zeros_changed)
  3874. except TypeError:
  3875. pass
  3876. try:
  3877. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3878. disconnect(self.on_excellon_zeros_changed)
  3879. except TypeError:
  3880. pass
  3881. def on_excellon_format_changed(self):
  3882. """
  3883. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3884. :return: None
  3885. """
  3886. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3887. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3888. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3889. )
  3890. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3891. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3892. )
  3893. else:
  3894. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3895. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3896. )
  3897. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3898. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3899. )
  3900. def on_excellon_zeros_changed(self):
  3901. """
  3902. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3903. :return: None
  3904. """
  3905. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3906. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3907. )
  3908. def on_excellon_units_changed(self):
  3909. """
  3910. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3911. :return: None
  3912. """
  3913. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3914. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3915. )
  3916. self.on_excellon_format_changed()
  3917. def on_film_color_entry(self):
  3918. self.defaults['tools_film_color'] = \
  3919. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3920. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3921. "background-color:%s;"
  3922. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3923. )
  3924. def on_film_color_button(self):
  3925. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3926. c_dialog = QtWidgets.QColorDialog()
  3927. film_color = c_dialog.getColor(initial=current_color)
  3928. if film_color.isValid() is False:
  3929. return
  3930. # if new color is different then mark that the Preferences are changed
  3931. if film_color != current_color:
  3932. self.preferencesUiManager.on_preferences_edited()
  3933. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3934. "background-color:%s;"
  3935. "border-color: dimgray" % str(film_color.name())
  3936. )
  3937. new_val_sel = str(film_color.name())
  3938. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3939. self.defaults['tools_film_color'] = new_val_sel
  3940. def on_qrcode_fill_color_entry(self):
  3941. self.defaults['tools_qrcode_fill_color'] = \
  3942. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3943. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3944. "background-color:%s;"
  3945. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3946. )
  3947. def on_qrcode_fill_color_button(self):
  3948. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3949. c_dialog = QtWidgets.QColorDialog()
  3950. fill_color = c_dialog.getColor(initial=current_color)
  3951. if fill_color.isValid() is False:
  3952. return
  3953. # if new color is different then mark that the Preferences are changed
  3954. if fill_color != current_color:
  3955. self.preferencesUiManager.on_preferences_edited()
  3956. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3957. "background-color:%s;"
  3958. "border-color: dimgray" % str(fill_color.name())
  3959. )
  3960. new_val_sel = str(fill_color.name())
  3961. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3962. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3963. def on_qrcode_back_color_entry(self):
  3964. self.defaults['tools_qrcode_back_color'] = \
  3965. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3966. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3967. "background-color:%s;"
  3968. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3969. )
  3970. def on_qrcode_back_color_button(self):
  3971. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3972. c_dialog = QtWidgets.QColorDialog()
  3973. back_color = c_dialog.getColor(initial=current_color)
  3974. if back_color.isValid() is False:
  3975. return
  3976. # if new color is different then mark that the Preferences are changed
  3977. if back_color != current_color:
  3978. self.preferencesUiManager.on_preferences_edited()
  3979. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3980. "background-color:%s;"
  3981. "border-color: dimgray" % str(back_color.name())
  3982. )
  3983. new_val_sel = str(back_color.name())
  3984. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3985. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3986. def on_tab_rmb_click(self, checked):
  3987. self.ui.notebook.set_detachable(val=checked)
  3988. self.defaults["global_tabs_detachable"] = checked
  3989. self.ui.plot_tab_area.set_detachable(val=checked)
  3990. self.defaults["global_tabs_detachable"] = checked
  3991. def on_tab_setup_context_menu(self):
  3992. initial_checked = self.defaults["global_tabs_detachable"]
  3993. action_name = str(_("Detachable Tabs"))
  3994. action = QtWidgets.QAction(self)
  3995. action.setCheckable(True)
  3996. action.setText(action_name)
  3997. action.setChecked(initial_checked)
  3998. self.ui.notebook.tabBar.addAction(action)
  3999. self.ui.plot_tab_area.tabBar.addAction(action)
  4000. try:
  4001. action.triggered.disconnect()
  4002. except TypeError:
  4003. pass
  4004. action.triggered.connect(self.on_tab_rmb_click)
  4005. def on_deselect_all(self):
  4006. self.collection.set_all_inactive()
  4007. self.delete_selection_shape()
  4008. def on_workspace_modified(self):
  4009. # self.save_defaults(silent=True)
  4010. if self.is_legacy is True:
  4011. self.plotcanvas.delete_workspace()
  4012. self.preferencesUiManager.defaults_read_form()
  4013. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4014. def on_workspace(self):
  4015. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4016. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4017. else:
  4018. self.plotcanvas.delete_workspace()
  4019. self.preferencesUiManager.defaults_read_form()
  4020. # self.save_defaults(silent=True)
  4021. def on_workspace_toggle(self):
  4022. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4023. try:
  4024. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4025. except TypeError:
  4026. pass
  4027. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4028. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4029. self.on_workspace()
  4030. def on_cursor_type(self, val):
  4031. """
  4032. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4033. :return: None
  4034. """
  4035. self.app_cursor.enabled = False
  4036. if val == 'small':
  4037. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4038. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4039. self.app_cursor = self.plotcanvas.new_cursor()
  4040. else:
  4041. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4042. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4043. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4044. if self.ui.grid_snap_btn.isChecked():
  4045. self.app_cursor.enabled = True
  4046. else:
  4047. self.app_cursor.enabled = False
  4048. def on_tool_add_keypress(self):
  4049. # ## Current application units in Upper Case
  4050. self.units = self.defaults['units'].upper()
  4051. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4052. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4053. if notebook_widget_name == 'selected_tab':
  4054. if self.collection.get_active().kind == 'geometry':
  4055. # Tool add works for Geometry only if Advanced is True in Preferences
  4056. if self.defaults["global_app_level"] == 'a':
  4057. tool_add_popup = FCInputDialog(title="New Tool ...",
  4058. text='Enter a Tool Diameter:',
  4059. min=0.0000, max=99.9999, decimals=4)
  4060. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4061. val, ok = tool_add_popup.get_value()
  4062. if ok:
  4063. if float(val) == 0:
  4064. self.inform.emit('[WARNING_NOTCL] %s' %
  4065. _("Please enter a tool diameter with non-zero value, in Float format."))
  4066. return
  4067. self.collection.get_active().on_tool_add(dia=float(val))
  4068. else:
  4069. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4070. else:
  4071. msgbox = QtWidgets.QMessageBox()
  4072. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4073. "Go to Preferences -> General - Show Advanced Options."))
  4074. msgbox.setWindowTitle("Tool adding ...")
  4075. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4076. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4077. msgbox.setDefaultButton(bt_ok)
  4078. msgbox.exec_()
  4079. # work only if the notebook tab on focus is the Tools_Tab
  4080. if notebook_widget_name == 'tool_tab':
  4081. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4082. # and only if the tool is NCC Tool
  4083. if tool_widget == self.ncclear_tool.toolName:
  4084. self.ncclear_tool.on_add_tool_by_key()
  4085. # and only if the tool is Paint Area Tool
  4086. elif tool_widget == self.paint_tool.toolName:
  4087. self.paint_tool.on_add_tool_by_key()
  4088. # and only if the tool is Solder Paste Dispensing Tool
  4089. elif tool_widget == self.paste_tool.toolName:
  4090. self.paste_tool.on_add_tool_by_key()
  4091. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4092. # See description bellow.
  4093. def on_delete_keypress(self):
  4094. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4095. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4096. if notebook_widget_name == 'selected_tab':
  4097. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4098. self.collection.get_active().on_tool_delete()
  4099. # work only if the notebook tab on focus is the Tools_Tab
  4100. elif notebook_widget_name == 'tool_tab':
  4101. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4102. # and only if the tool is NCC Tool
  4103. if tool_widget == self.ncclear_tool.toolName:
  4104. self.ncclear_tool.on_tool_delete()
  4105. # and only if the tool is Paint Tool
  4106. elif tool_widget == self.paint_tool.toolName:
  4107. self.paint_tool.on_tool_delete()
  4108. # and only if the tool is Solder Paste Dispensing Tool
  4109. elif tool_widget == self.paste_tool.toolName:
  4110. self.paste_tool.on_tool_delete()
  4111. else:
  4112. self.on_delete()
  4113. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4114. # some screens you have to be careful where you hover with your mouse.
  4115. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4116. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4117. # Complicated, I know :)
  4118. def on_delete(self, force_deletion=False):
  4119. """
  4120. Delete the currently selected FlatCAMObjs.
  4121. :param force_deletion: used by Tcl command
  4122. :return: None
  4123. """
  4124. self.defaults.report_usage("on_delete()")
  4125. response = None
  4126. bt_ok = None
  4127. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4128. # a geometry object before we update it.
  4129. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4130. and self.grb_editor.editor_active is False:
  4131. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4132. msgbox = QtWidgets.QMessageBox()
  4133. msgbox.setWindowTitle(_("Delete objects"))
  4134. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4135. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4136. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4137. "the selected objects?"))
  4138. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4139. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4140. msgbox.setDefaultButton(bt_ok)
  4141. msgbox.exec_()
  4142. response = msgbox.clickedButton()
  4143. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4144. response = bt_ok
  4145. if response == bt_ok:
  4146. if self.collection.get_active():
  4147. self.log.debug("App.on_delete()")
  4148. for obj_active in self.collection.get_selected():
  4149. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4150. if isinstance(obj_active, GerberObject):
  4151. for el in obj_active.mark_shapes:
  4152. obj_active.mark_shapes[el].clear(update=True)
  4153. obj_active.mark_shapes[el].enabled = False
  4154. # obj_active.mark_shapes[el] = None
  4155. del el
  4156. elif isinstance(obj_active, CNCJobObject):
  4157. try:
  4158. obj_active.text_col.enabled = False
  4159. del obj_active.text_col
  4160. obj_active.annotation.clear(update=True)
  4161. del obj_active.annotation
  4162. except AttributeError as e:
  4163. log.debug(
  4164. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4165. )
  4166. while self.collection.get_selected():
  4167. self.delete_first_selected()
  4168. self.inform.emit('%s...' % _("Object(s) deleted"))
  4169. # make sure that the selection shape is deleted, too
  4170. self.delete_selection_shape()
  4171. else:
  4172. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4173. else:
  4174. self.inform.emit(_("Save the work in Editor and try again ..."))
  4175. def delete_first_selected(self):
  4176. # Keep this for later
  4177. try:
  4178. sel_obj = self.collection.get_active()
  4179. name = sel_obj.options["name"]
  4180. isPlotted = sel_obj.options["plot"]
  4181. except AttributeError:
  4182. self.log.debug("Nothing selected for deletion")
  4183. return
  4184. if self.is_legacy is True:
  4185. # Remove plot only if the object was plotted otherwise delaxes will fail
  4186. if isPlotted:
  4187. try:
  4188. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4189. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4190. except Exception as e:
  4191. log.debug("App.delete_first_selected() --> %s" % str(e))
  4192. self.plotcanvas.auto_adjust_axes()
  4193. # Remove from dictionary
  4194. self.collection.delete_active()
  4195. # Clear form
  4196. self.setup_component_editor()
  4197. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4198. def on_set_origin(self):
  4199. """
  4200. Set the origin to the left mouse click position
  4201. :return: None
  4202. """
  4203. # display the message for the user
  4204. # and ask him to click on the desired position
  4205. self.defaults.report_usage("on_set_origin()")
  4206. def origin_replot():
  4207. def worker_task():
  4208. with self.proc_container.new('%s...' % _("Plotting")):
  4209. for obj in self.collection.get_list():
  4210. obj.plot()
  4211. self.plotcanvas.fit_view()
  4212. if self.is_legacy:
  4213. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4214. else:
  4215. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4216. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4217. self.inform.emit(_('Click to set the origin ...'))
  4218. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4219. # first disconnect it as it may have been used by something else
  4220. try:
  4221. self.replot_signal.disconnect()
  4222. except TypeError:
  4223. pass
  4224. self.replot_signal[list].connect(origin_replot)
  4225. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4226. """
  4227. :param event:
  4228. :param location:
  4229. :param noplot:
  4230. :param use_thread:
  4231. :return:
  4232. """
  4233. noplot_sig = noplot
  4234. def worker_task():
  4235. with self.proc_container.new(_("Setting Origin...")):
  4236. obj_list = self.collection.get_list()
  4237. for obj in obj_list:
  4238. obj.offset((x, y))
  4239. self.object_changed.emit(obj)
  4240. # Update the object bounding box options
  4241. a, b, c, d = obj.bounds()
  4242. obj.options['xmin'] = a
  4243. obj.options['ymin'] = b
  4244. obj.options['xmax'] = c
  4245. obj.options['ymax'] = d
  4246. self.inform.emit('[success] %s...' % _('Origin set'))
  4247. for obj in obj_list:
  4248. out_name = obj.options["name"]
  4249. if obj.kind == 'gerber':
  4250. obj.source_file = self.export_gerber(
  4251. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4252. elif obj.kind == 'excellon':
  4253. obj.source_file = self.export_excellon(
  4254. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4255. if noplot_sig is False:
  4256. self.replot_signal.emit([])
  4257. if location is not None:
  4258. if len(location) != 2:
  4259. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4260. return 'fail'
  4261. x, y = location
  4262. if use_thread is True:
  4263. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4264. else:
  4265. worker_task()
  4266. self.should_we_save = True
  4267. return
  4268. if event.button == 1:
  4269. if self.is_legacy is False:
  4270. event_pos = event.pos
  4271. else:
  4272. event_pos = (event.xdata, event.ydata)
  4273. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4274. if self.grid_status():
  4275. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4276. else:
  4277. pos = pos_canvas
  4278. x = 0 - pos[0]
  4279. y = 0 - pos[1]
  4280. if use_thread is True:
  4281. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4282. else:
  4283. worker_task()
  4284. self.should_we_save = True
  4285. def on_move2origin(self, use_thread=True):
  4286. """
  4287. Move selected objects to origin.
  4288. :param use_thread: Control if to use threaded operation. Boolean.
  4289. :return:
  4290. """
  4291. def worker_task():
  4292. with self.proc_container.new(_("Moving to Origin...")):
  4293. obj_list = self.collection.get_selected()
  4294. if not obj_list:
  4295. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4296. return
  4297. xminlist = []
  4298. yminlist = []
  4299. # first get a bounding box to fit all
  4300. for obj in obj_list:
  4301. xmin, ymin, xmax, ymax = obj.bounds()
  4302. xminlist.append(xmin)
  4303. yminlist.append(ymin)
  4304. # get the minimum x,y for all objects selected
  4305. x = min(xminlist)
  4306. y = min(yminlist)
  4307. for obj in obj_list:
  4308. obj.offset((-x, -y))
  4309. self.object_changed.emit(obj)
  4310. # Update the object bounding box options
  4311. a, b, c, d = obj.bounds()
  4312. obj.options['xmin'] = a
  4313. obj.options['ymin'] = b
  4314. obj.options['xmax'] = c
  4315. obj.options['ymax'] = d
  4316. for obj in obj_list:
  4317. obj.plot()
  4318. for obj in obj_list:
  4319. out_name = obj.options["name"]
  4320. if obj.kind == 'gerber':
  4321. obj.source_file = self.export_gerber(
  4322. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4323. elif obj.kind == 'excellon':
  4324. obj.source_file = self.export_excellon(
  4325. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4326. self.inform.emit('[success] %s...' % _('Origin set'))
  4327. if use_thread is True:
  4328. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4329. else:
  4330. worker_task()
  4331. self.should_we_save = True
  4332. def on_jump_to(self, custom_location=None, fit_center=True):
  4333. """
  4334. Jump to a location by setting the mouse cursor location.
  4335. :param custom_location: Jump to a specified point. (x, y) tuple.
  4336. :param fit_center: If to fit view. Boolean.
  4337. :return:
  4338. """
  4339. self.defaults.report_usage("on_jump_to()")
  4340. if not custom_location:
  4341. dia_box_location = None
  4342. try:
  4343. dia_box_location = eval(self.clipboard.text())
  4344. except Exception:
  4345. pass
  4346. if type(dia_box_location) == tuple:
  4347. dia_box_location = str(dia_box_location)
  4348. else:
  4349. dia_box_location = None
  4350. # dia_box = Dialog_box(title=_("Jump to ..."),
  4351. # label=_("Enter the coordinates in format X,Y:"),
  4352. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4353. # initial_text=dia_box_location)
  4354. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4355. label=_("Enter the coordinates in format X,Y:"),
  4356. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4357. initial_text=dia_box_location,
  4358. reference=self.defaults['global_jump_ref'])
  4359. if dia_box.ok is True:
  4360. try:
  4361. location = eval(dia_box.location)
  4362. if not isinstance(location, tuple):
  4363. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4364. return
  4365. if dia_box.reference == 'rel':
  4366. rel_x = self.mouse[0] + location[0]
  4367. rel_y = self.mouse[1] + location[1]
  4368. location = (rel_x, rel_y)
  4369. self.defaults['global_jump_ref'] = dia_box.reference
  4370. except Exception:
  4371. return
  4372. else:
  4373. return
  4374. else:
  4375. location = custom_location
  4376. self.jump_signal.emit(location)
  4377. if fit_center:
  4378. self.plotcanvas.fit_center(loc=location)
  4379. cursor = QtGui.QCursor()
  4380. if self.is_legacy is False:
  4381. # I don't know where those differences come from but they are constant for the current
  4382. # execution of the application and they are multiples of a value around 0.0263mm.
  4383. # In a random way sometimes they are more sometimes they are less
  4384. # if units == 'MM':
  4385. # cal_factor = 0.0263
  4386. # else:
  4387. # cal_factor = 0.0263 / 25.4
  4388. cal_location = (location[0], location[1])
  4389. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4390. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4391. j_pos = (
  4392. int(canvas_origin.x() + round(jump_loc[0])),
  4393. int(canvas_origin.y() + round(jump_loc[1]))
  4394. )
  4395. cursor.setPos(j_pos[0], j_pos[1])
  4396. else:
  4397. # find the canvas origin which is in the top left corner
  4398. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4399. # determine the coordinates for the lowest left point of the canvas
  4400. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4401. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4402. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4403. # canvas) and the point (width, height) is in the top-right location
  4404. loc = self.plotcanvas.axes.transData.transform_point(location)
  4405. j_pos = (
  4406. int(x0 + loc[0]),
  4407. int(y0 - loc[1])
  4408. )
  4409. cursor.setPos(j_pos[0], j_pos[1])
  4410. self.plotcanvas.mouse = [location[0], location[1]]
  4411. if self.defaults["global_cursor_color_enabled"] is True:
  4412. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4413. else:
  4414. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4415. if self.grid_status():
  4416. # Update cursor
  4417. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4418. symbol='++', edge_color=self.cursor_color_3D,
  4419. edge_width=self.defaults["global_cursor_width"],
  4420. size=self.defaults["global_cursor_size"])
  4421. # Set the position label
  4422. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4423. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4424. # Set the relative position label
  4425. dx = location[0] - float(self.rel_point1[0])
  4426. dy = location[1] - float(self.rel_point1[1])
  4427. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4428. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4429. self.inform.emit('[success] %s' % _("Done."))
  4430. return location
  4431. def on_locate(self, obj, fit_center=True):
  4432. """
  4433. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4434. :param obj: The object on which to locate certain points
  4435. :param fit_center: If to fit view. Boolean.
  4436. :return: A point location. (x, y) tuple.
  4437. """
  4438. self.defaults.report_usage("on_locate()")
  4439. if obj is None:
  4440. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4441. return 'fail'
  4442. class DialogBoxChoice(QtWidgets.QDialog):
  4443. def __init__(self, title=None, icon=None, choice='bl'):
  4444. """
  4445. :param title: string with the window title
  4446. """
  4447. super(DialogBoxChoice, self).__init__()
  4448. self.ok = False
  4449. self.setWindowIcon(icon)
  4450. self.setWindowTitle(str(title))
  4451. self.form = QtWidgets.QFormLayout(self)
  4452. self.ref_radio = RadioSet([
  4453. {"label": _("Bottom-Left"), "value": "bl"},
  4454. {"label": _("Top-Left"), "value": "tl"},
  4455. {"label": _("Bottom-Right"), "value": "br"},
  4456. {"label": _("Top-Right"), "value": "tr"},
  4457. {"label": _("Center"), "value": "c"}
  4458. ], orientation='vertical', stretch=False)
  4459. self.ref_radio.set_value(choice)
  4460. self.form.addRow(self.ref_radio)
  4461. self.button_box = QtWidgets.QDialogButtonBox(
  4462. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4463. Qt.Horizontal, parent=self)
  4464. self.form.addRow(self.button_box)
  4465. self.button_box.accepted.connect(self.accept)
  4466. self.button_box.rejected.connect(self.reject)
  4467. if self.exec_() == QtWidgets.QDialog.Accepted:
  4468. self.ok = True
  4469. self.location_point = self.ref_radio.get_value()
  4470. else:
  4471. self.ok = False
  4472. self.location_point = None
  4473. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4474. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4475. choice=self.defaults['global_locate_pt'])
  4476. if dia_box.ok is True:
  4477. try:
  4478. location_point = dia_box.location_point
  4479. self.defaults['global_locate_pt'] = dia_box.location_point
  4480. except Exception:
  4481. return
  4482. else:
  4483. return
  4484. loc_b = obj.bounds()
  4485. if location_point == 'bl':
  4486. location = (loc_b[0], loc_b[1])
  4487. elif location_point == 'tl':
  4488. location = (loc_b[0], loc_b[3])
  4489. elif location_point == 'br':
  4490. location = (loc_b[2], loc_b[1])
  4491. elif location_point == 'tr':
  4492. location = (loc_b[2], loc_b[3])
  4493. else:
  4494. # center
  4495. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4496. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4497. location = (cx, cy)
  4498. self.locate_signal.emit(location, location_point)
  4499. if fit_center:
  4500. self.plotcanvas.fit_center(loc=location)
  4501. cursor = QtGui.QCursor()
  4502. if self.is_legacy is False:
  4503. # I don't know where those differences come from but they are constant for the current
  4504. # execution of the application and they are multiples of a value around 0.0263mm.
  4505. # In a random way sometimes they are more sometimes they are less
  4506. # if units == 'MM':
  4507. # cal_factor = 0.0263
  4508. # else:
  4509. # cal_factor = 0.0263 / 25.4
  4510. cal_location = (location[0], location[1])
  4511. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4512. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4513. j_pos = (
  4514. int(canvas_origin.x() + round(jump_loc[0])),
  4515. int(canvas_origin.y() + round(jump_loc[1]))
  4516. )
  4517. cursor.setPos(j_pos[0], j_pos[1])
  4518. else:
  4519. # find the canvas origin which is in the top left corner
  4520. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4521. # determine the coordinates for the lowest left point of the canvas
  4522. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4523. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4524. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4525. # canvas) and the point (width, height) is in the top-right location
  4526. loc = self.plotcanvas.axes.transData.transform_point(location)
  4527. j_pos = (
  4528. int(x0 + loc[0]),
  4529. int(y0 - loc[1])
  4530. )
  4531. cursor.setPos(j_pos[0], j_pos[1])
  4532. self.plotcanvas.mouse = [location[0], location[1]]
  4533. if self.defaults["global_cursor_color_enabled"] is True:
  4534. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4535. else:
  4536. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4537. if self.grid_status():
  4538. # Update cursor
  4539. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4540. symbol='++', edge_color=self.cursor_color_3D,
  4541. edge_width=self.defaults["global_cursor_width"],
  4542. size=self.defaults["global_cursor_size"])
  4543. # Set the position label
  4544. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4545. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4546. # Set the relative position label
  4547. self.dx = location[0] - float(self.rel_point1[0])
  4548. self.dy = location[1] - float(self.rel_point1[1])
  4549. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4550. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4551. self.inform.emit('[success] %s' % _("Done."))
  4552. return location
  4553. def on_copy_command(self):
  4554. """
  4555. Will copy a selection of objects, creating new objects.
  4556. :return:
  4557. """
  4558. self.defaults.report_usage("on_copy_command()")
  4559. def initialize(obj_init, app):
  4560. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4561. try:
  4562. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4563. except AttributeError:
  4564. pass
  4565. try:
  4566. obj_init.apertures = deepcopy(obj.apertures)
  4567. except AttributeError:
  4568. pass
  4569. try:
  4570. if obj.tools:
  4571. obj_init.tools = deepcopy(obj.tools)
  4572. except Exception as err:
  4573. log.debug("App.on_copy_command() --> %s" % str(err))
  4574. try:
  4575. obj_init.source_file = deepcopy(obj.source_file)
  4576. except (AttributeError, TypeError):
  4577. pass
  4578. def initialize_excellon(obj_init, app):
  4579. obj_init.source_file = deepcopy(obj.source_file)
  4580. obj_init.tools = deepcopy(obj.tools)
  4581. # drills are offset, so they need to be deep copied
  4582. obj_init.drills = deepcopy(obj.drills)
  4583. # slots are offset, so they need to be deep copied
  4584. obj_init.slots = deepcopy(obj.slots)
  4585. obj_init.create_geometry()
  4586. def initialize_script(obj_init, app_obj):
  4587. obj_init.source_file = deepcopy(obj.source_file)
  4588. def initialize_document(obj_init, app_obj):
  4589. obj_init.source_file = deepcopy(obj.source_file)
  4590. for obj in self.collection.get_selected():
  4591. obj_name = obj.options["name"]
  4592. try:
  4593. if isinstance(obj, ExcellonObject):
  4594. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4595. elif isinstance(obj, GerberObject):
  4596. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4597. elif isinstance(obj, GeometryObject):
  4598. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4599. elif isinstance(obj, ScriptObject):
  4600. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4601. elif isinstance(obj, DocumentObject):
  4602. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4603. except Exception as e:
  4604. return "Operation failed: %s" % str(e)
  4605. def on_copy_object2(self, custom_name):
  4606. def initialize_geometry(obj_init, app):
  4607. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4608. try:
  4609. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4610. except AttributeError:
  4611. pass
  4612. try:
  4613. obj_init.apertures = deepcopy(obj.apertures)
  4614. except AttributeError:
  4615. pass
  4616. try:
  4617. if obj.tools:
  4618. obj_init.tools = deepcopy(obj.tools)
  4619. except Exception as ee:
  4620. log.debug("on_copy_object2() --> %s" % str(ee))
  4621. def initialize_gerber(obj_init, app):
  4622. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4623. obj_init.apertures = deepcopy(obj.apertures)
  4624. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4625. def initialize_excellon(obj_init, app):
  4626. obj_init.tools = deepcopy(obj.tools)
  4627. # drills are offset, so they need to be deep copied
  4628. obj_init.drills = deepcopy(obj.drills)
  4629. # slots are offset, so they need to be deep copied
  4630. obj_init.slots = deepcopy(obj.slots)
  4631. obj_init.create_geometry()
  4632. for obj in self.collection.get_selected():
  4633. obj_name = obj.options["name"]
  4634. try:
  4635. if isinstance(obj, ExcellonObject):
  4636. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4637. elif isinstance(obj, GerberObject):
  4638. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4639. elif isinstance(obj, GeometryObject):
  4640. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4641. except Exception as er:
  4642. return "Operation failed: %s" % str(er)
  4643. def on_rename_object(self, text):
  4644. """
  4645. Will rename an object.
  4646. :param text: New name for the object.
  4647. :return:
  4648. """
  4649. self.defaults.report_usage("on_rename_object()")
  4650. named_obj = self.collection.get_active()
  4651. for obj in named_obj:
  4652. if obj is list:
  4653. self.on_rename_object(text)
  4654. else:
  4655. try:
  4656. obj.options['name'] = text
  4657. except Exception as e:
  4658. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4659. def convert_any2geo(self):
  4660. """
  4661. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4662. :return:
  4663. """
  4664. self.defaults.report_usage("convert_any2geo()")
  4665. def initialize(obj_init, app):
  4666. obj_init.solid_geometry = obj.solid_geometry
  4667. try:
  4668. obj_init.follow_geometry = obj.follow_geometry
  4669. except AttributeError:
  4670. pass
  4671. try:
  4672. obj_init.apertures = obj.apertures
  4673. except AttributeError:
  4674. pass
  4675. try:
  4676. if obj.tools:
  4677. obj_init.tools = obj.tools
  4678. except AttributeError:
  4679. pass
  4680. def initialize_excellon(obj_init, app):
  4681. # objs = self.collection.get_selected()
  4682. # GeometryObject.merge(objs, obj)
  4683. solid_geo = []
  4684. for tool in obj.tools:
  4685. for geo in obj.tools[tool]['solid_geometry']:
  4686. solid_geo.append(geo)
  4687. obj_init.solid_geometry = deepcopy(solid_geo)
  4688. if not self.collection.get_selected():
  4689. log.warning("App.convert_any2geo --> No object selected")
  4690. self.inform.emit('[WARNING_NOTCL] %s' %
  4691. _("No object is selected. Select an object and try again."))
  4692. return
  4693. for obj in self.collection.get_selected():
  4694. obj_name = obj.options["name"]
  4695. try:
  4696. if isinstance(obj, ExcellonObject):
  4697. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4698. else:
  4699. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4700. except Exception as e:
  4701. return "Operation failed: %s" % str(e)
  4702. def convert_any2gerber(self):
  4703. """
  4704. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4705. :return:
  4706. """
  4707. self.defaults.report_usage("convert_any2gerber()")
  4708. def initialize_geometry(obj_init, app):
  4709. apertures = {}
  4710. apid = 0
  4711. apertures[str(apid)] = {}
  4712. apertures[str(apid)]['geometry'] = []
  4713. for obj_orig in obj.solid_geometry:
  4714. new_elem = {}
  4715. new_elem['solid'] = obj_orig
  4716. try:
  4717. new_elem['follow'] = obj_orig.exterior
  4718. except AttributeError:
  4719. pass
  4720. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4721. apertures[str(apid)]['size'] = 0.0
  4722. apertures[str(apid)]['type'] = 'C'
  4723. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4724. obj_init.apertures = deepcopy(apertures)
  4725. def initialize_excellon(obj_init, app):
  4726. apertures = {}
  4727. apid = 10
  4728. for tool in obj.tools:
  4729. apertures[str(apid)] = {}
  4730. apertures[str(apid)]['geometry'] = []
  4731. for geo in obj.tools[tool]['solid_geometry']:
  4732. new_el = {}
  4733. new_el['solid'] = geo
  4734. new_el['follow'] = geo.exterior
  4735. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4736. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4737. apertures[str(apid)]['type'] = 'C'
  4738. apid += 1
  4739. # create solid_geometry
  4740. solid_geometry = []
  4741. for apid in apertures:
  4742. for geo_el in apertures[apid]['geometry']:
  4743. solid_geometry.append(geo_el['solid'])
  4744. solid_geometry = MultiPolygon(solid_geometry)
  4745. solid_geometry = solid_geometry.buffer(0.0000001)
  4746. obj_init.solid_geometry = deepcopy(solid_geometry)
  4747. obj_init.apertures = deepcopy(apertures)
  4748. # clear the working objects (perhaps not necessary due of Python GC)
  4749. apertures.clear()
  4750. if not self.collection.get_selected():
  4751. log.warning("App.convert_any2gerber --> No object selected")
  4752. self.inform.emit('[WARNING_NOTCL] %s' %
  4753. _("No object is selected. Select an object and try again."))
  4754. return
  4755. for obj in self.collection.get_selected():
  4756. obj_name = obj.options["name"]
  4757. try:
  4758. if isinstance(obj, ExcellonObject):
  4759. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4760. elif isinstance(obj, GeometryObject):
  4761. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4762. else:
  4763. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4764. except Exception as e:
  4765. return "Operation failed: %s" % str(e)
  4766. def abort_all_tasks(self):
  4767. """
  4768. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4769. on the first possible occasion.
  4770. :return:
  4771. """
  4772. if self.abort_flag is False:
  4773. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4774. self.abort_flag = True
  4775. self.cleanup.emit()
  4776. def app_is_idle(self):
  4777. if self.abort_flag:
  4778. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4779. self.abort_flag = False
  4780. def on_selectall(self):
  4781. """
  4782. Will draw a selection box shape around the selected objects.
  4783. :return:
  4784. """
  4785. self.defaults.report_usage("on_selectall()")
  4786. # delete the possible selection box around a possible selected object
  4787. self.delete_selection_shape()
  4788. for name in self.collection.get_names():
  4789. self.collection.set_active(name)
  4790. curr_sel_obj = self.collection.get_by_name(name)
  4791. # create the selection box around the selected object
  4792. if self.defaults['global_selection_shape'] is True:
  4793. self.draw_selection_shape(curr_sel_obj)
  4794. def on_preferences(self):
  4795. """
  4796. Adds the Preferences in a Tab in Plot Area
  4797. :return:
  4798. """
  4799. # add the tab if it was closed
  4800. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4801. # delete the absolute and relative position and messages in the infobar
  4802. self.ui.position_label.setText("")
  4803. self.ui.rel_position_label.setText("")
  4804. # Switch plot_area to preferences page
  4805. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4806. # self.ui.show()
  4807. # detect changes in the preferences
  4808. for idx in range(self.ui.pref_tab_area.count()):
  4809. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4810. try:
  4811. try:
  4812. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4813. except (TypeError, AttributeError):
  4814. pass
  4815. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4816. except AttributeError:
  4817. pass
  4818. try:
  4819. try:
  4820. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4821. except (TypeError, AttributeError):
  4822. pass
  4823. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4824. except AttributeError:
  4825. pass
  4826. try:
  4827. try:
  4828. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4829. except (TypeError, AttributeError):
  4830. pass
  4831. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4832. except AttributeError:
  4833. pass
  4834. try:
  4835. try:
  4836. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4837. except (TypeError, AttributeError):
  4838. pass
  4839. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4840. except AttributeError:
  4841. pass
  4842. try:
  4843. try:
  4844. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4845. except (TypeError, AttributeError):
  4846. pass
  4847. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4848. except AttributeError:
  4849. pass
  4850. def on_tools_database(self, source='app'):
  4851. """
  4852. Adds the Tools Database in a Tab in Plot Area.
  4853. :return:
  4854. """
  4855. for idx in range(self.ui.plot_tab_area.count()):
  4856. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4857. # there can be only one instance of Tools Database at one time
  4858. return
  4859. if source == 'app':
  4860. self.tools_db_tab = ToolsDB2(
  4861. app=self,
  4862. parent=self.ui,
  4863. callback_on_edited=self.on_tools_db_edited,
  4864. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4865. )
  4866. elif source == 'ncc':
  4867. self.tools_db_tab = ToolsDB2(
  4868. app=self,
  4869. parent=self.ui,
  4870. callback_on_edited=self.on_tools_db_edited,
  4871. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4872. )
  4873. elif source == 'paint':
  4874. self.tools_db_tab = ToolsDB2(
  4875. app=self,
  4876. parent=self.ui,
  4877. callback_on_edited=self.on_tools_db_edited,
  4878. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4879. )
  4880. # add the tab if it was closed
  4881. try:
  4882. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4883. self.tools_db_tab.setObjectName("database_tab")
  4884. except Exception as e:
  4885. log.debug("App.on_tools_database() --> %s" % str(e))
  4886. return
  4887. # delete the absolute and relative position and messages in the infobar
  4888. self.ui.position_label.setText("")
  4889. self.ui.rel_position_label.setText("")
  4890. # Switch plot_area to preferences page
  4891. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4892. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4893. self.tools_db_tab.ui_connect()
  4894. def on_tools_db_edited(self):
  4895. """
  4896. Executed whenever a tool is edited in Tools Database.
  4897. Will color the text of the Tools Database tab to Red color.
  4898. :return:
  4899. """
  4900. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4901. for idx in range(self.ui.plot_tab_area.count()):
  4902. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4903. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4904. self.tools_db_changed_flag = True
  4905. def on_geometry_tool_add_from_db_executed(self, tool):
  4906. """
  4907. Here add the tool from DB in the selected geometry object.
  4908. :return:
  4909. """
  4910. tool_from_db = deepcopy(tool)
  4911. obj = self.collection.get_active()
  4912. if isinstance(obj, GeometryObject):
  4913. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4914. # close the tab and delete it
  4915. for idx in range(self.ui.plot_tab_area.count()):
  4916. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4917. wdg = self.ui.plot_tab_area.widget(idx)
  4918. wdg.deleteLater()
  4919. self.ui.plot_tab_area.removeTab(idx)
  4920. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4921. else:
  4922. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4923. def on_plot_area_tab_closed(self, title):
  4924. """
  4925. Executed whenever a tab is closed in the Plot Area.
  4926. :param title: The name of the tab that was closed.
  4927. :return:
  4928. """
  4929. # FIXME: doing this based on translated title doesn't seem very robust.
  4930. if title == _("Preferences"):
  4931. self.preferencesUiManager.on_close_preferences_tab()
  4932. if title == _("Tools Database"):
  4933. # disconnect the signals from the table widget in tab
  4934. self.tools_db_tab.ui_disconnect()
  4935. if self.tools_db_changed_flag is True:
  4936. msgbox = QtWidgets.QMessageBox()
  4937. msgbox.setText(_("One or more Tools are edited.\n"
  4938. "Do you want to update the Tools Database?"))
  4939. msgbox.setWindowTitle(_("Save Tools Database"))
  4940. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4941. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4942. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4943. msgbox.setDefaultButton(bt_yes)
  4944. msgbox.exec_()
  4945. response = msgbox.clickedButton()
  4946. if response == bt_yes:
  4947. self.tools_db_tab.on_save_tools_db()
  4948. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4949. else:
  4950. self.tools_db_changed_flag = False
  4951. self.inform.emit('')
  4952. return
  4953. self.tools_db_tab.deleteLater()
  4954. if title == _("Code Editor"):
  4955. self.toggle_codeeditor = False
  4956. if title == _("Bookmarks Manager"):
  4957. self.book_dialog_tab.rebuild_actions()
  4958. self.book_dialog_tab.deleteLater()
  4959. def on_plotarea_tab_closed(self, tab_idx):
  4960. """
  4961. :param tab_idx: Index of the Tab from the plotarea that was closed
  4962. :return:
  4963. """
  4964. widget = self.ui.plot_tab_area.widget(tab_idx)
  4965. if widget is not None:
  4966. widget.deleteLater()
  4967. self.ui.plot_tab_area.removeTab(tab_idx)
  4968. def on_flipy(self):
  4969. """
  4970. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4971. :return:
  4972. """
  4973. self.defaults.report_usage("on_flipy()")
  4974. obj_list = self.collection.get_selected()
  4975. xminlist = []
  4976. yminlist = []
  4977. xmaxlist = []
  4978. ymaxlist = []
  4979. if not obj_list:
  4980. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4981. else:
  4982. try:
  4983. # first get a bounding box to fit all
  4984. for obj in obj_list:
  4985. xmin, ymin, xmax, ymax = obj.bounds()
  4986. xminlist.append(xmin)
  4987. yminlist.append(ymin)
  4988. xmaxlist.append(xmax)
  4989. ymaxlist.append(ymax)
  4990. # get the minimum x,y and maximum x,y for all objects selected
  4991. xminimal = min(xminlist)
  4992. yminimal = min(yminlist)
  4993. xmaximal = max(xmaxlist)
  4994. ymaximal = max(ymaxlist)
  4995. px = 0.5 * (xminimal + xmaximal)
  4996. py = 0.5 * (yminimal + ymaximal)
  4997. # execute mirroring
  4998. for obj in obj_list:
  4999. obj.mirror('X', [px, py])
  5000. obj.plot()
  5001. self.object_changed.emit(obj)
  5002. self.inform.emit('[success] %s' %
  5003. _("Flip on Y axis done."))
  5004. except Exception as e:
  5005. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5006. return
  5007. def on_flipx(self):
  5008. """
  5009. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5010. :return:
  5011. """
  5012. self.defaults.report_usage("on_flipx()")
  5013. obj_list = self.collection.get_selected()
  5014. xminlist = []
  5015. yminlist = []
  5016. xmaxlist = []
  5017. ymaxlist = []
  5018. if not obj_list:
  5019. self.inform.emit('[WARNING_NOTCL] %s' %
  5020. _("No object selected to Flip on X axis."))
  5021. else:
  5022. try:
  5023. # first get a bounding box to fit all
  5024. for obj in obj_list:
  5025. xmin, ymin, xmax, ymax = obj.bounds()
  5026. xminlist.append(xmin)
  5027. yminlist.append(ymin)
  5028. xmaxlist.append(xmax)
  5029. ymaxlist.append(ymax)
  5030. # get the minimum x,y and maximum x,y for all objects selected
  5031. xminimal = min(xminlist)
  5032. yminimal = min(yminlist)
  5033. xmaximal = max(xmaxlist)
  5034. ymaximal = max(ymaxlist)
  5035. px = 0.5 * (xminimal + xmaximal)
  5036. py = 0.5 * (yminimal + ymaximal)
  5037. # execute mirroring
  5038. for obj in obj_list:
  5039. obj.mirror('Y', [px, py])
  5040. obj.plot()
  5041. self.object_changed.emit(obj)
  5042. self.inform.emit('[success] %s' %
  5043. _("Flip on X axis done."))
  5044. except Exception as e:
  5045. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5046. return
  5047. def on_rotate(self, silent=False, preset=None):
  5048. """
  5049. Executed when Options -> Rotate Selection menu entry is clicked.
  5050. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5051. :param preset: A value to be used as predefined angle for rotation.
  5052. :return:
  5053. """
  5054. self.defaults.report_usage("on_rotate()")
  5055. obj_list = self.collection.get_selected()
  5056. xminlist = []
  5057. yminlist = []
  5058. xmaxlist = []
  5059. ymaxlist = []
  5060. if not obj_list:
  5061. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5062. else:
  5063. if silent is False:
  5064. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5065. min=-360, max=360, decimals=4,
  5066. init_val=float(self.defaults['tools_transform_rotate']))
  5067. num, ok = rotatebox.get_value()
  5068. else:
  5069. num = preset
  5070. ok = True
  5071. if ok:
  5072. try:
  5073. # first get a bounding box to fit all
  5074. for obj in obj_list:
  5075. xmin, ymin, xmax, ymax = obj.bounds()
  5076. xminlist.append(xmin)
  5077. yminlist.append(ymin)
  5078. xmaxlist.append(xmax)
  5079. ymaxlist.append(ymax)
  5080. # get the minimum x,y and maximum x,y for all objects selected
  5081. xminimal = min(xminlist)
  5082. yminimal = min(yminlist)
  5083. xmaximal = max(xmaxlist)
  5084. ymaximal = max(ymaxlist)
  5085. px = 0.5 * (xminimal + xmaximal)
  5086. py = 0.5 * (yminimal + ymaximal)
  5087. for sel_obj in obj_list:
  5088. sel_obj.rotate(-float(num), point=(px, py))
  5089. sel_obj.plot()
  5090. self.object_changed.emit(sel_obj)
  5091. self.inform.emit('[success] %s' %
  5092. _("Rotation done."))
  5093. except Exception as e:
  5094. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5095. return
  5096. def on_skewx(self):
  5097. """
  5098. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5099. :return:
  5100. """
  5101. self.defaults.report_usage("on_skewx()")
  5102. obj_list = self.collection.get_selected()
  5103. xminlist = []
  5104. yminlist = []
  5105. if not obj_list:
  5106. self.inform.emit('[WARNING_NOTCL] %s' %
  5107. _("No object selected to Skew/Shear on X axis."))
  5108. else:
  5109. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5110. min=-360, max=360, decimals=4,
  5111. init_val=float(self.defaults['tools_transform_skew_x']))
  5112. num, ok = skewxbox.get_value()
  5113. if ok:
  5114. # first get a bounding box to fit all
  5115. for obj in obj_list:
  5116. xmin, ymin, xmax, ymax = obj.bounds()
  5117. xminlist.append(xmin)
  5118. yminlist.append(ymin)
  5119. # get the minimum x,y and maximum x,y for all objects selected
  5120. xminimal = min(xminlist)
  5121. yminimal = min(yminlist)
  5122. for obj in obj_list:
  5123. obj.skew(num, 0, point=(xminimal, yminimal))
  5124. obj.plot()
  5125. self.object_changed.emit(obj)
  5126. self.inform.emit('[success] %s' %
  5127. _("Skew on X axis done."))
  5128. def on_skewy(self):
  5129. """
  5130. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5131. :return:
  5132. """
  5133. self.defaults.report_usage("on_skewy()")
  5134. obj_list = self.collection.get_selected()
  5135. xminlist = []
  5136. yminlist = []
  5137. if not obj_list:
  5138. self.inform.emit('[WARNING_NOTCL] %s' %
  5139. _("No object selected to Skew/Shear on Y axis."))
  5140. else:
  5141. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5142. min=-360, max=360, decimals=4,
  5143. init_val=float(self.defaults['tools_transform_skew_y']))
  5144. num, ok = skewybox.get_value()
  5145. if ok:
  5146. # first get a bounding box to fit all
  5147. for obj in obj_list:
  5148. xmin, ymin, xmax, ymax = obj.bounds()
  5149. xminlist.append(xmin)
  5150. yminlist.append(ymin)
  5151. # get the minimum x,y and maximum x,y for all objects selected
  5152. xminimal = min(xminlist)
  5153. yminimal = min(yminlist)
  5154. for obj in obj_list:
  5155. obj.skew(0, num, point=(xminimal, yminimal))
  5156. obj.plot()
  5157. self.object_changed.emit(obj)
  5158. self.inform.emit('[success] %s' %
  5159. _("Skew on Y axis done."))
  5160. def on_plots_updated(self):
  5161. """
  5162. Callback used to report when the plots have changed.
  5163. Adjust axes and zooms to fit.
  5164. :return: None
  5165. """
  5166. if self.is_legacy is False:
  5167. self.plotcanvas.update()
  5168. else:
  5169. self.plotcanvas.auto_adjust_axes()
  5170. self.on_zoom_fit(None)
  5171. self.collection.update_view()
  5172. # self.inform.emit(_("Plots updated ..."))
  5173. def on_toolbar_replot(self):
  5174. """
  5175. Callback for toolbar button. Re-plots all objects.
  5176. :return: None
  5177. """
  5178. self.defaults.report_usage("on_toolbar_replot")
  5179. self.log.debug("on_toolbar_replot()")
  5180. try:
  5181. self.collection.get_active().read_form()
  5182. except AttributeError:
  5183. self.log.debug("on_toolbar_replot(): AttributeError")
  5184. pass
  5185. self.plot_all()
  5186. def on_row_activated(self, index):
  5187. if index.isValid():
  5188. if index.internalPointer().parent_item != self.collection.root_item:
  5189. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5190. self.collection.on_item_activated(index)
  5191. def on_row_selected(self, obj_name):
  5192. """
  5193. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5194. It mean we clicked outside of the items and deselected all
  5195. :param obj_name:
  5196. :return:
  5197. """
  5198. if obj_name == 'none':
  5199. for act in self.ui.menuobjects.actions():
  5200. act.setChecked(False)
  5201. return
  5202. # get the name of the selected objects and add them to a list
  5203. name_list = []
  5204. for obj in self.collection.get_selected():
  5205. name_list.append(obj.options['name'])
  5206. # set all actions as unchecked but the ones selected make them checked
  5207. for act in self.ui.menuobjects.actions():
  5208. act.setChecked(False)
  5209. if act.text() in name_list:
  5210. act.setChecked(True)
  5211. def on_collection_updated(self, obj, state, old_name):
  5212. """
  5213. Create a menu from the object loaded in the collection.
  5214. :param obj: object that was changed (added, deleted, renamed)
  5215. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5216. :param old_name: the old name of the object before the action that triggered this slot happened
  5217. :return: None
  5218. """
  5219. icon_files = {
  5220. "gerber": self.resource_location + "/flatcam_icon16.png",
  5221. "excellon": self.resource_location + "/drill16.png",
  5222. "cncjob": self.resource_location + "/cnc16.png",
  5223. "geometry": self.resource_location + "/geometry16.png",
  5224. "script": self.resource_location + "/script_new16.png",
  5225. "document": self.resource_location + "/notes16_1.png"
  5226. }
  5227. if state == 'append':
  5228. for act in self.ui.menuobjects.actions():
  5229. try:
  5230. act.triggered.disconnect()
  5231. except TypeError:
  5232. pass
  5233. self.ui.menuobjects.clear()
  5234. gerber_list = []
  5235. exc_list = []
  5236. cncjob_list = []
  5237. geo_list = []
  5238. script_list = []
  5239. doc_list = []
  5240. for name in self.collection.get_names():
  5241. obj_named = self.collection.get_by_name(name)
  5242. if obj_named.kind == 'gerber':
  5243. gerber_list.append(name)
  5244. elif obj_named.kind == 'excellon':
  5245. exc_list.append(name)
  5246. elif obj_named.kind == 'cncjob':
  5247. cncjob_list.append(name)
  5248. elif obj_named.kind == 'geometry':
  5249. geo_list.append(name)
  5250. elif obj_named.kind == 'script':
  5251. script_list.append(name)
  5252. elif obj_named.kind == 'document':
  5253. doc_list.append(name)
  5254. def add_act(o_name):
  5255. obj_for_icon = self.collection.get_by_name(o_name)
  5256. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5257. add_action.setCheckable(True)
  5258. add_action.setText(o_name)
  5259. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5260. add_action.triggered.connect(
  5261. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5262. self.collection.set_inactive(o_name))
  5263. self.ui.menuobjects.addAction(add_action)
  5264. for name in gerber_list:
  5265. add_act(name)
  5266. self.ui.menuobjects.addSeparator()
  5267. for name in exc_list:
  5268. add_act(name)
  5269. self.ui.menuobjects.addSeparator()
  5270. for name in cncjob_list:
  5271. add_act(name)
  5272. self.ui.menuobjects.addSeparator()
  5273. for name in geo_list:
  5274. add_act(name)
  5275. self.ui.menuobjects.addSeparator()
  5276. for name in script_list:
  5277. add_act(name)
  5278. self.ui.menuobjects.addSeparator()
  5279. for name in doc_list:
  5280. add_act(name)
  5281. self.ui.menuobjects.addSeparator()
  5282. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5283. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5284. _('Select All')
  5285. )
  5286. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5287. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5288. _('Deselect All')
  5289. )
  5290. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5291. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5292. elif state == 'delete':
  5293. for act in self.ui.menuobjects.actions():
  5294. if act.text() == obj.options['name']:
  5295. try:
  5296. act.triggered.disconnect()
  5297. except TypeError:
  5298. pass
  5299. self.ui.menuobjects.removeAction(act)
  5300. break
  5301. elif state == 'rename':
  5302. for act in self.ui.menuobjects.actions():
  5303. if act.text() == old_name:
  5304. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5305. add_action.setText(obj.options['name'])
  5306. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5307. add_action.triggered.connect(
  5308. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5309. self.collection.set_inactive(obj.options['name']))
  5310. self.ui.menuobjects.insertAction(act, add_action)
  5311. try:
  5312. act.triggered.disconnect()
  5313. except TypeError:
  5314. pass
  5315. self.ui.menuobjects.removeAction(act)
  5316. break
  5317. elif state == 'delete_all':
  5318. for act in self.ui.menuobjects.actions():
  5319. try:
  5320. act.triggered.disconnect()
  5321. except TypeError:
  5322. pass
  5323. self.ui.menuobjects.clear()
  5324. self.ui.menuobjects.addSeparator()
  5325. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5326. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5327. _('Select All')
  5328. )
  5329. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5330. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5331. _('Deselect All')
  5332. )
  5333. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5334. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5335. def on_objects_selection(self, on_off):
  5336. obj_list = self.collection.get_names()
  5337. if on_off is True:
  5338. self.collection.set_all_active()
  5339. for act in self.ui.menuobjects.actions():
  5340. try:
  5341. act.setChecked(True)
  5342. except Exception:
  5343. pass
  5344. if obj_list:
  5345. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5346. else:
  5347. self.collection.set_all_inactive()
  5348. for act in self.ui.menuobjects.actions():
  5349. try:
  5350. act.setChecked(False)
  5351. except Exception:
  5352. pass
  5353. if obj_list:
  5354. self.inform.emit('%s' % _("Objects selection is cleared."))
  5355. else:
  5356. self.inform.emit('')
  5357. def grid_status(self):
  5358. if self.ui.grid_snap_btn.isChecked():
  5359. return True
  5360. else:
  5361. return False
  5362. def populate_cmenu_grids(self):
  5363. units = self.defaults['units'].lower()
  5364. # for act in self.ui.cmenu_gridmenu.actions():
  5365. # act.triggered.disconnect()
  5366. self.ui.cmenu_gridmenu.clear()
  5367. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5368. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5369. _("Grid On/Off"))
  5370. grid_toggle.setCheckable(True)
  5371. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5372. self.ui.cmenu_gridmenu.addSeparator()
  5373. for grid in sorted_list:
  5374. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5375. "%s" % str(grid))
  5376. action.triggered.connect(self.set_grid)
  5377. self.ui.cmenu_gridmenu.addSeparator()
  5378. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5379. _("Add"))
  5380. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5381. _("Delete"))
  5382. grid_add.triggered.connect(self.on_grid_add)
  5383. grid_delete.triggered.connect(self.on_grid_delete)
  5384. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5385. def set_grid(self):
  5386. menu_action = self.sender()
  5387. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5388. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5389. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5390. def on_grid_add(self):
  5391. # ## Current application units in lower Case
  5392. units = self.defaults['units'].lower()
  5393. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5394. text=_('Enter a Grid Value:'),
  5395. min=0.0000, max=99.9999, decimals=4)
  5396. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5397. val, ok = grid_add_popup.get_value()
  5398. if ok:
  5399. if float(val) == 0:
  5400. self.inform.emit('[WARNING_NOTCL] %s' %
  5401. _("Please enter a grid value with non-zero value, in Float format."))
  5402. return
  5403. else:
  5404. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5405. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5406. self.inform.emit('[success] %s...' %
  5407. _("New Grid added"))
  5408. else:
  5409. self.inform.emit('[WARNING_NOTCL] %s...' %
  5410. _("Grid already exists"))
  5411. else:
  5412. self.inform.emit('[WARNING_NOTCL] %s...' %
  5413. _("Adding New Grid cancelled"))
  5414. def on_grid_delete(self):
  5415. # ## Current application units in lower Case
  5416. units = self.defaults['units'].lower()
  5417. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5418. text='Enter a Grid Value:',
  5419. min=0.0000, max=99.9999, decimals=4)
  5420. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5421. val, ok = grid_del_popup.get_value()
  5422. if ok:
  5423. if float(val) == 0:
  5424. self.inform.emit('[WARNING_NOTCL] %s' %
  5425. _("Please enter a grid value with non-zero value, in Float format."))
  5426. return
  5427. else:
  5428. try:
  5429. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5430. except ValueError:
  5431. self.inform.emit('[ERROR_NOTCL]%s...' %
  5432. _(" Grid Value does not exist"))
  5433. return
  5434. self.inform.emit('[success] %s...' %
  5435. _("Grid Value deleted"))
  5436. else:
  5437. self.inform.emit('[WARNING_NOTCL] %s...' %
  5438. _("Delete Grid value cancelled"))
  5439. def on_shortcut_list(self):
  5440. self.defaults.report_usage("on_shortcut_list()")
  5441. # add the tab if it was closed
  5442. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5443. # delete the absolute and relative position and messages in the infobar
  5444. self.ui.position_label.setText("")
  5445. self.ui.rel_position_label.setText("")
  5446. # Switch plot_area to preferences page
  5447. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5448. # self.ui.show()
  5449. def on_select_tab(self, name):
  5450. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5451. if self.ui.splitter.sizes()[0] == 0:
  5452. self.ui.splitter.setSizes([1, 1])
  5453. else:
  5454. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5455. self.ui.splitter.setSizes([0, 1])
  5456. if name == 'project':
  5457. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5458. elif name == 'selected':
  5459. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5460. elif name == 'tool':
  5461. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5462. def on_copy_name(self):
  5463. self.defaults.report_usage("on_copy_name()")
  5464. obj = self.collection.get_active()
  5465. try:
  5466. name = obj.options["name"]
  5467. except AttributeError:
  5468. log.debug("on_copy_name() --> No object selected to copy it's name")
  5469. self.inform.emit('[WARNING_NOTCL]%s' %
  5470. _(" No object selected to copy it's name"))
  5471. return
  5472. self.clipboard.setText(name)
  5473. self.inform.emit(_("Name copied on clipboard ..."))
  5474. def on_mouse_click_over_plot(self, event):
  5475. """
  5476. Default actions are:
  5477. :param event: Contains information about the event, like which button
  5478. was clicked, the pixel coordinates and the axes coordinates.
  5479. :return: None
  5480. """
  5481. self.pos = []
  5482. if self.is_legacy is False:
  5483. event_pos = event.pos
  5484. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5485. # # Set the mouse button for panning
  5486. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5487. else:
  5488. event_pos = (event.xdata, event.ydata)
  5489. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5490. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5491. # So it can receive key presses
  5492. self.plotcanvas.native.setFocus()
  5493. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5494. if self.grid_status():
  5495. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5496. else:
  5497. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5498. try:
  5499. if event.button == 1:
  5500. # Reset here the relative coordinates so there is a new reference on the click position
  5501. if self.rel_point1 is None:
  5502. self.rel_point1 = self.pos
  5503. else:
  5504. self.rel_point2 = copy(self.rel_point1)
  5505. self.rel_point1 = self.pos
  5506. self.on_mouse_move_over_plot(event, origin_click=True)
  5507. except Exception as e:
  5508. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5509. def on_mouse_double_click_over_plot(self, event):
  5510. if event.button == 1:
  5511. self.doubleclick = True
  5512. def on_mouse_move_over_plot(self, event, origin_click=None):
  5513. """
  5514. Callback for the mouse motion event over the plot.
  5515. :param event: Contains information about the event.
  5516. :param origin_click
  5517. :return: None
  5518. """
  5519. if self.is_legacy is False:
  5520. event_pos = event.pos
  5521. if self.defaults["global_pan_button"] == '2':
  5522. pan_button = 2
  5523. else:
  5524. pan_button = 3
  5525. self.event_is_dragging = event.is_dragging
  5526. else:
  5527. event_pos = (event.xdata, event.ydata)
  5528. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5529. if self.defaults["global_pan_button"] == '2':
  5530. pan_button = 3
  5531. else:
  5532. pan_button = 2
  5533. self.event_is_dragging = self.plotcanvas.is_dragging
  5534. # So it can receive key presses but not when the Tcl Shell is active
  5535. if not self.ui.shell_dock.isVisible():
  5536. if not self.plotcanvas.native.hasFocus():
  5537. self.plotcanvas.native.setFocus()
  5538. self.pos_jump = event_pos
  5539. self.ui.popMenu.mouse_is_panning = False
  5540. if origin_click is None:
  5541. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5542. if event.button == pan_button and self.event_is_dragging == 1:
  5543. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5544. if self.ui.popMenu.popup_active:
  5545. self.ui.popMenu.popup_active = False
  5546. return
  5547. self.ui.popMenu.mouse_is_panning = True
  5548. return
  5549. if self.rel_point1 is not None:
  5550. try: # May fail in case mouse not within axes
  5551. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5552. if self.grid_status():
  5553. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5554. # Update cursor
  5555. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5556. symbol='++', edge_color=self.cursor_color_3D,
  5557. edge_width=self.defaults["global_cursor_width"],
  5558. size=self.defaults["global_cursor_size"])
  5559. else:
  5560. pos = (pos_canvas[0], pos_canvas[1])
  5561. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5562. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5563. self.dx = pos[0] - float(self.rel_point1[0])
  5564. self.dy = pos[1] - float(self.rel_point1[1])
  5565. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5566. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5567. self.mouse = [pos[0], pos[1]]
  5568. # if the mouse is moved and the LMB is clicked then the action is a selection
  5569. if self.event_is_dragging == 1 and event.button == 1:
  5570. self.delete_selection_shape()
  5571. if self.dx < 0:
  5572. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5573. face_color=self.defaults['global_alt_sel_fill'])
  5574. self.selection_type = False
  5575. elif self.dx >= 0:
  5576. self.draw_moving_selection_shape(self.pos, pos)
  5577. self.selection_type = True
  5578. else:
  5579. self.selection_type = None
  5580. else:
  5581. self.selection_type = None
  5582. # hover effect - enabled in Preferences -> General -> GUI Settings
  5583. if self.defaults['global_hover']:
  5584. for obj in self.collection.get_list():
  5585. try:
  5586. # select the object(s) only if it is enabled (plotted)
  5587. if obj.options['plot']:
  5588. if obj not in self.collection.get_selected():
  5589. poly_obj = Polygon(
  5590. [(obj.options['xmin'], obj.options['ymin']),
  5591. (obj.options['xmax'], obj.options['ymin']),
  5592. (obj.options['xmax'], obj.options['ymax']),
  5593. (obj.options['xmin'], obj.options['ymax'])]
  5594. )
  5595. if Point(pos).within(poly_obj):
  5596. if obj.isHovering is False:
  5597. obj.isHovering = True
  5598. obj.notHovering = True
  5599. # create the selection box around the selected object
  5600. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5601. else:
  5602. if obj.notHovering is True:
  5603. obj.notHovering = False
  5604. obj.isHovering = False
  5605. self.delete_hover_shape()
  5606. except Exception:
  5607. # the Exception here will happen if we try to select on screen and we have an
  5608. # newly (and empty) just created Geometry or Excellon object that do not have the
  5609. # xmin, xmax, ymin, ymax options.
  5610. # In this case poly_obj creation (see above) will fail
  5611. pass
  5612. except Exception:
  5613. self.ui.position_label.setText("")
  5614. self.ui.rel_position_label.setText("")
  5615. self.mouse = None
  5616. def on_mouse_click_release_over_plot(self, event):
  5617. """
  5618. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5619. and has been registered in ''self.__init__()''.
  5620. :param event: contains information about the event.
  5621. :return:
  5622. """
  5623. if self.is_legacy is False:
  5624. event_pos = event.pos
  5625. right_button = 2
  5626. else:
  5627. event_pos = (event.xdata, event.ydata)
  5628. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5629. right_button = 3
  5630. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5631. if self.grid_status():
  5632. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5633. else:
  5634. pos = (pos_canvas[0], pos_canvas[1])
  5635. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5636. # canvas menu
  5637. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5638. self.ui.popMenu.mouse_is_panning = False
  5639. self.cursor = QtGui.QCursor()
  5640. self.populate_cmenu_grids()
  5641. self.ui.popMenu.popup(self.cursor.pos())
  5642. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5643. # selection and then select a type of selection ("enclosing" or "touching")
  5644. if event.button == 1: # left click
  5645. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5646. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5647. if modifiers == QtCore.Qt.ShiftModifier:
  5648. # do not auto open the Project Tab
  5649. self.click_noproject = True
  5650. self.clipboard.setText(
  5651. self.defaults["global_point_clipboard_format"] %
  5652. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5653. )
  5654. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5655. return
  5656. if self.doubleclick is True:
  5657. self.doubleclick = False
  5658. if self.collection.get_selected():
  5659. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5660. if self.ui.splitter.sizes()[0] == 0:
  5661. self.ui.splitter.setSizes([1, 1])
  5662. try:
  5663. # delete the selection shape(S) as it may be in the way
  5664. self.delete_selection_shape()
  5665. self.delete_hover_shape()
  5666. except Exception as e:
  5667. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5668. return
  5669. else:
  5670. # WORKAROUND for LEGACY MODE
  5671. if self.is_legacy is True:
  5672. # if there is no move on canvas then we have no dragging selection
  5673. if self.dx == 0 or self.dy == 0:
  5674. self.selection_type = None
  5675. if self.selection_type is not None:
  5676. try:
  5677. self.selection_area_handler(self.pos, pos, self.selection_type)
  5678. self.selection_type = None
  5679. except Exception as e:
  5680. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5681. return
  5682. else:
  5683. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5684. if key_modifier == QtCore.Qt.ShiftModifier:
  5685. mod_key = 'Shift'
  5686. elif key_modifier == QtCore.Qt.ControlModifier:
  5687. mod_key = 'Control'
  5688. else:
  5689. mod_key = None
  5690. try:
  5691. if mod_key == self.defaults["global_mselect_key"]:
  5692. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5693. # deselect, and if it's not selected then it will be selected
  5694. # If there is no active command (self.command_active is None) then we check if we clicked
  5695. # on a object by checking the bounding limits against mouse click position
  5696. if self.command_active is None:
  5697. self.select_objects(key='multisel')
  5698. self.delete_hover_shape()
  5699. else:
  5700. # If there is no active command (self.command_active is None) then we check if we clicked
  5701. # on a object by checking the bounding limits against mouse click position
  5702. if self.command_active is None:
  5703. self.select_objects()
  5704. self.delete_hover_shape()
  5705. except Exception as e:
  5706. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5707. return
  5708. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5709. """
  5710. :param start_pos: mouse position when the selection LMB click was done
  5711. :param end_pos: mouse position when the left mouse button is released
  5712. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5713. :return:
  5714. """
  5715. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5716. # delete previous selection shape
  5717. self.delete_selection_shape()
  5718. # make all objects inactive
  5719. self.collection.set_all_inactive()
  5720. for obj in self.collection.get_list():
  5721. try:
  5722. # select the object(s) only if it is enabled (plotted)
  5723. if obj.options['plot']:
  5724. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5725. (obj.options['xmax'], obj.options['ymin']),
  5726. (obj.options['xmax'], obj.options['ymax']),
  5727. (obj.options['xmin'], obj.options['ymax'])])
  5728. if sel_type is True:
  5729. if poly_obj.within(poly_selection):
  5730. # create the selection box around the selected object
  5731. if self.defaults['global_selection_shape'] is True:
  5732. self.draw_selection_shape(obj)
  5733. self.collection.set_active(obj.options['name'])
  5734. else:
  5735. if poly_selection.intersects(poly_obj):
  5736. # create the selection box around the selected object
  5737. if self.defaults['global_selection_shape'] is True:
  5738. self.draw_selection_shape(obj)
  5739. self.collection.set_active(obj.options['name'])
  5740. obj.selection_shape_drawn = True
  5741. except Exception as e:
  5742. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5743. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5744. # In this case poly_obj creation (see above) will fail
  5745. log.debug("App.selection_area_handler() --> %s" % str(e))
  5746. def select_objects(self, key=None):
  5747. """
  5748. Will select objects clicked on canvas
  5749. :param key: for future use in cumulative selection
  5750. :return:
  5751. """
  5752. # list where we store the overlapped objects under our mouse left click position
  5753. if key is None:
  5754. self.objects_under_the_click_list = []
  5755. # Populate the list with the overlapped objects on the click position
  5756. curr_x, curr_y = self.pos
  5757. for obj in self.all_objects_list:
  5758. # ScriptObject and DocumentObject objects can't be selected
  5759. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5760. continue
  5761. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5762. continue
  5763. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5764. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5765. if obj.options['name'] not in self.objects_under_the_click_list:
  5766. if obj.options['plot']:
  5767. # add objects to the objects_under_the_click list only if the object is plotted
  5768. # (active and not disabled)
  5769. self.objects_under_the_click_list.append(obj.options['name'])
  5770. try:
  5771. if self.objects_under_the_click_list:
  5772. curr_sel_obj = self.collection.get_active()
  5773. # case when there is only an object under the click and we toggle it
  5774. if len(self.objects_under_the_click_list) == 1:
  5775. if curr_sel_obj is None:
  5776. self.collection.set_active(self.objects_under_the_click_list[0])
  5777. curr_sel_obj = self.collection.get_active()
  5778. # create the selection box around the selected object
  5779. if self.defaults['global_selection_shape'] is True:
  5780. self.draw_selection_shape(curr_sel_obj)
  5781. curr_sel_obj.selection_shape_drawn = True
  5782. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5783. self.on_objects_selection(False)
  5784. self.delete_selection_shape()
  5785. curr_sel_obj.selection_shape_drawn = False
  5786. self.collection.set_active(self.objects_under_the_click_list[0])
  5787. curr_sel_obj = self.collection.get_active()
  5788. # create the selection box around the selected object
  5789. if self.defaults['global_selection_shape'] is True:
  5790. self.draw_selection_shape(curr_sel_obj)
  5791. curr_sel_obj.selection_shape_drawn = True
  5792. self.selected_message(curr_sel_obj=curr_sel_obj)
  5793. elif curr_sel_obj.selection_shape_drawn is False:
  5794. if self.defaults['global_selection_shape'] is True:
  5795. self.draw_selection_shape(curr_sel_obj)
  5796. curr_sel_obj.selection_shape_drawn = True
  5797. else:
  5798. self.on_objects_selection(False)
  5799. self.delete_selection_shape()
  5800. if self.call_source != 'app':
  5801. self.call_source = 'app'
  5802. self.selected_message(curr_sel_obj=curr_sel_obj)
  5803. else:
  5804. # If there is no selected object
  5805. # make active the first element of the overlapped objects list
  5806. if self.collection.get_active() is None:
  5807. self.collection.set_active(self.objects_under_the_click_list[0])
  5808. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5809. name_sel_obj = self.collection.get_active().options['name']
  5810. # In case that there is a selected object but it is not in the overlapped object list
  5811. # make that object inactive and activate the first element in the overlapped object list
  5812. if name_sel_obj not in self.objects_under_the_click_list:
  5813. self.collection.set_inactive(name_sel_obj)
  5814. name_sel_obj = self.objects_under_the_click_list[0]
  5815. self.collection.set_active(name_sel_obj)
  5816. else:
  5817. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5818. self.collection.set_all_inactive()
  5819. self.collection.set_active(
  5820. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5821. curr_sel_obj = self.collection.get_active()
  5822. # delete the possible selection box around a possible selected object
  5823. self.delete_selection_shape()
  5824. curr_sel_obj.selection_shape_drawn = False
  5825. # create the selection box around the selected object
  5826. if self.defaults['global_selection_shape'] is True:
  5827. self.draw_selection_shape(curr_sel_obj)
  5828. curr_sel_obj.selection_shape_drawn = True
  5829. self.selected_message(curr_sel_obj=curr_sel_obj)
  5830. else:
  5831. # deselect everything
  5832. self.on_objects_selection(False)
  5833. # delete the possible selection box around a possible selected object
  5834. self.delete_selection_shape()
  5835. for o in self.collection.get_list():
  5836. o.selection_shape_drawn = False
  5837. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5838. # only when working on App
  5839. if self.call_source == 'app':
  5840. if self.click_noproject is False:
  5841. # if the Tool Tab is in focus don't change focus to Project Tab
  5842. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5843. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5844. else:
  5845. # restore auto open the Project Tab
  5846. self.click_noproject = False
  5847. # delete any text in the status bar, implicitly the last object name that was selected
  5848. # self.inform.emit("")
  5849. else:
  5850. self.call_source = 'app'
  5851. except Exception as e:
  5852. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5853. def selected_message(self, curr_sel_obj):
  5854. if curr_sel_obj:
  5855. if curr_sel_obj.kind == 'gerber':
  5856. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5857. color='green',
  5858. name=str(curr_sel_obj.options['name']),
  5859. tx=_("selected"))
  5860. )
  5861. elif curr_sel_obj.kind == 'excellon':
  5862. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5863. color='brown',
  5864. name=str(curr_sel_obj.options['name']),
  5865. tx=_("selected"))
  5866. )
  5867. elif curr_sel_obj.kind == 'cncjob':
  5868. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5869. color='blue',
  5870. name=str(curr_sel_obj.options['name']),
  5871. tx=_("selected"))
  5872. )
  5873. elif curr_sel_obj.kind == 'geometry':
  5874. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5875. color='red',
  5876. name=str(curr_sel_obj.options['name']),
  5877. tx=_("selected"))
  5878. )
  5879. def delete_hover_shape(self):
  5880. self.hover_shapes.clear()
  5881. self.hover_shapes.redraw()
  5882. def draw_hover_shape(self, sel_obj, color=None):
  5883. """
  5884. :param sel_obj: The object for which the hover shape must be drawn
  5885. :param color: The color of the hover shape
  5886. :return: None
  5887. """
  5888. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5889. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5890. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5891. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5892. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5893. if self.defaults['units'].upper() == 'MM':
  5894. hover_rect = hover_rect.buffer(-0.1)
  5895. hover_rect = hover_rect.buffer(0.2)
  5896. else:
  5897. hover_rect = hover_rect.buffer(-0.00393)
  5898. hover_rect = hover_rect.buffer(0.00787)
  5899. # if color:
  5900. # face = Color(color)
  5901. # face.alpha = 0.2
  5902. # outline = Color(color, alpha=0.8)
  5903. # else:
  5904. # face = Color(self.defaults['global_sel_fill'])
  5905. # face.alpha = 0.2
  5906. # outline = self.defaults['global_sel_line']
  5907. if color:
  5908. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5909. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5910. else:
  5911. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5912. outline = self.defaults['global_sel_line']
  5913. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5914. if self.is_legacy is True:
  5915. self.hover_shapes.redraw()
  5916. def delete_selection_shape(self):
  5917. self.move_tool.sel_shapes.clear()
  5918. self.move_tool.sel_shapes.redraw()
  5919. def draw_selection_shape(self, sel_obj, color=None):
  5920. """
  5921. Will draw a selection shape around the selected object.
  5922. :param sel_obj: The object for which the selection shape must be drawn
  5923. :param color: The color for the selection shape.
  5924. :return: None
  5925. """
  5926. if sel_obj is None:
  5927. return
  5928. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5929. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5930. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5931. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5932. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5933. if self.defaults['units'].upper() == 'MM':
  5934. sel_rect = sel_rect.buffer(-0.1)
  5935. sel_rect = sel_rect.buffer(0.2)
  5936. else:
  5937. sel_rect = sel_rect.buffer(-0.00393)
  5938. sel_rect = sel_rect.buffer(0.00787)
  5939. if color:
  5940. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5941. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5942. else:
  5943. if self.is_legacy is False:
  5944. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5945. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5946. else:
  5947. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5948. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5949. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5950. color=outline,
  5951. face_color=face,
  5952. update=True,
  5953. layer=0,
  5954. tolerance=None))
  5955. if self.is_legacy is True:
  5956. self.move_tool.sel_shapes.redraw()
  5957. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5958. """
  5959. Will draw a selection shape when dragging mouse on canvas.
  5960. :param old_coords: Old coordinates
  5961. :param coords: New coordinates
  5962. :param kwargs: Keyword arguments
  5963. :return:
  5964. """
  5965. if 'color' in kwargs:
  5966. color = kwargs['color']
  5967. else:
  5968. color = self.defaults['global_sel_line']
  5969. if 'face_color' in kwargs:
  5970. face_color = kwargs['face_color']
  5971. else:
  5972. face_color = self.defaults['global_sel_fill']
  5973. if 'face_alpha' in kwargs:
  5974. face_alpha = kwargs['face_alpha']
  5975. else:
  5976. face_alpha = 0.3
  5977. x0, y0 = old_coords
  5978. x1, y1 = coords
  5979. pt1 = (x0, y0)
  5980. pt2 = (x1, y0)
  5981. pt3 = (x1, y1)
  5982. pt4 = (x0, y1)
  5983. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5984. # color_t = Color(face_color)
  5985. # color_t.alpha = face_alpha
  5986. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5987. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5988. layer=0, tolerance=None)
  5989. if self.is_legacy is True:
  5990. self.move_tool.sel_shapes.redraw()
  5991. def on_file_new_click(self):
  5992. """
  5993. Callback for menu item File -> New.
  5994. Executed on clicking the Menu -> File -> New Project
  5995. :return:
  5996. """
  5997. if self.collection.get_list() and self.should_we_save:
  5998. msgbox = QtWidgets.QMessageBox()
  5999. # msgbox.setText("<B>Save changes ...</B>")
  6000. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6001. "Creating a New project will delete them.\n"
  6002. "Do you want to Save the project?"))
  6003. msgbox.setWindowTitle(_("Save changes"))
  6004. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6005. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6006. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6007. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6008. msgbox.setDefaultButton(bt_yes)
  6009. msgbox.exec_()
  6010. response = msgbox.clickedButton()
  6011. if response == bt_yes:
  6012. self.on_file_saveprojectas()
  6013. elif response == bt_cancel:
  6014. return
  6015. elif response == bt_no:
  6016. self.on_file_new()
  6017. else:
  6018. self.on_file_new()
  6019. self.inform.emit('[success] %s...' % _("New Project created"))
  6020. def on_file_new(self, cli=None):
  6021. """
  6022. Returns the application to its startup state. This method is thread-safe.
  6023. :param cli: Boolean. If True this method was run from command line
  6024. :return: None
  6025. """
  6026. self.defaults.report_usage("on_file_new")
  6027. # Remove everything from memory
  6028. App.log.debug("on_file_new()")
  6029. if self.call_source != 'app':
  6030. self.editor2object(cleanup=True)
  6031. # ## EDITOR section
  6032. self.geo_editor = FlatCAMGeoEditor(self)
  6033. self.exc_editor = FlatCAMExcEditor(self)
  6034. self.grb_editor = FlatCAMGrbEditor(self)
  6035. # Clear pool
  6036. self.clear_pool()
  6037. for obj in self.collection.get_list():
  6038. # delete shapes left drawn from mark shape_collections, if any
  6039. if isinstance(obj, GerberObject):
  6040. try:
  6041. for el in obj.mark_shapes:
  6042. obj.mark_shapes[el].clear(update=True)
  6043. obj.mark_shapes[el].enabled = False
  6044. del el
  6045. except AttributeError:
  6046. pass
  6047. # also delete annotation shapes, if any
  6048. elif isinstance(obj, CNCJobObject):
  6049. try:
  6050. obj.text_col.enabled = False
  6051. del obj.text_col
  6052. obj.annotation.clear(update=True)
  6053. del obj.annotation
  6054. except AttributeError:
  6055. pass
  6056. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6057. self.shell.init_tcl()
  6058. self.delete_selection_shape()
  6059. self.collection.delete_all()
  6060. self.setup_component_editor()
  6061. # Clear project filename
  6062. self.project_filename = None
  6063. # Load the application defaults
  6064. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6065. # Re-fresh project options
  6066. self.on_options_app2project()
  6067. # Init Tools
  6068. self.init_tools()
  6069. if cli is None:
  6070. # Close any Tabs opened in the Plot Tab Area section
  6071. for index in range(self.ui.plot_tab_area.count()):
  6072. self.ui.plot_tab_area.closeTab(index)
  6073. # for whatever reason previous command does not close the last tab so I do it manually
  6074. self.ui.plot_tab_area.closeTab(0)
  6075. # # And then add again the Plot Area
  6076. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6077. self.ui.plot_tab_area.protectTab(0)
  6078. # take the focus of the Notebook on Project Tab.
  6079. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6080. self.set_ui_title(name=_("New Project - Not saved"))
  6081. def obj_properties(self):
  6082. """
  6083. Will launch the object Properties Tool
  6084. :return:
  6085. """
  6086. self.defaults.report_usage("obj_properties()")
  6087. self.properties_tool.run(toggle=False)
  6088. def on_project_context_save(self):
  6089. """
  6090. Wrapper, will save the object function of it's type
  6091. :return:
  6092. """
  6093. obj = self.collection.get_active()
  6094. if type(obj) == GeometryObject:
  6095. self.on_file_exportdxf()
  6096. elif type(obj) == ExcellonObject:
  6097. self.on_file_saveexcellon()
  6098. elif type(obj) == CNCJobObject:
  6099. obj.on_exportgcode_button_click()
  6100. elif type(obj) == GerberObject:
  6101. self.on_file_savegerber()
  6102. elif type(obj) == ScriptObject:
  6103. self.on_file_savescript()
  6104. elif type(obj) == DocumentObject:
  6105. self.on_file_savedocument()
  6106. def obj_move(self):
  6107. """
  6108. Callback for the Move menu entry in various Context Menu's.
  6109. :return:
  6110. """
  6111. self.defaults.report_usage("obj_move()")
  6112. self.move_tool.run(toggle=False)
  6113. def on_fileopengerber(self, signal, name=None):
  6114. """
  6115. File menu callback for opening a Gerber.
  6116. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6117. :param name:
  6118. :return: None
  6119. """
  6120. self.defaults.report_usage("on_fileopengerber")
  6121. App.log.debug("on_fileopengerber()")
  6122. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6123. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6124. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6125. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6126. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6127. "*.mil);;" \
  6128. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6129. "Allegro Files (*.art);;" \
  6130. "Mentor Files (*.pho *.gdo);;" \
  6131. "All Files (*.*)"
  6132. if name is None:
  6133. try:
  6134. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6135. directory=self.get_last_folder(),
  6136. filter=_filter_)
  6137. except TypeError:
  6138. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6139. filenames = [str(filename) for filename in filenames]
  6140. else:
  6141. filenames = [name]
  6142. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6143. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6144. _("Opening Gerber file.")),
  6145. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6146. color=QtGui.QColor("gray"))
  6147. if len(filenames) == 0:
  6148. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6149. else:
  6150. for filename in filenames:
  6151. if filename != '':
  6152. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6153. def on_fileopenexcellon(self, signal, name=None):
  6154. """
  6155. File menu callback for opening an Excellon file.
  6156. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6157. :param name:
  6158. :return: None
  6159. """
  6160. self.defaults.report_usage("on_fileopenexcellon")
  6161. App.log.debug("on_fileopenexcellon()")
  6162. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6163. "All Files (*.*)"
  6164. if name is None:
  6165. try:
  6166. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6167. directory=self.get_last_folder(),
  6168. filter=_filter_)
  6169. except TypeError:
  6170. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6171. filenames = [str(filename) for filename in filenames]
  6172. else:
  6173. filenames = [str(name)]
  6174. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6175. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6176. _("Opening Excellon file.")),
  6177. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6178. color=QtGui.QColor("gray"))
  6179. if len(filenames) == 0:
  6180. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6181. else:
  6182. for filename in filenames:
  6183. if filename != '':
  6184. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6185. def on_fileopengcode(self, signal, name=None):
  6186. """
  6187. File menu call back for opening gcode.
  6188. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6189. :param name:
  6190. :return:
  6191. """
  6192. self.defaults.report_usage("on_fileopengcode")
  6193. App.log.debug("on_fileopengcode()")
  6194. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6195. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6196. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6197. "All Files (*.*)"
  6198. if name is None:
  6199. try:
  6200. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6201. directory=self.get_last_folder(),
  6202. filter=_filter_)
  6203. except TypeError:
  6204. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6205. filenames = [str(filename) for filename in filenames]
  6206. else:
  6207. filenames = [name]
  6208. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6209. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6210. _("Opening G-Code file.")),
  6211. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6212. color=QtGui.QColor("gray"))
  6213. if len(filenames) == 0:
  6214. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6215. else:
  6216. for filename in filenames:
  6217. if filename != '':
  6218. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6219. def on_file_openproject(self, signal):
  6220. """
  6221. File menu callback for opening a project.
  6222. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6223. :return: None
  6224. """
  6225. self.defaults.report_usage("on_file_openproject")
  6226. App.log.debug("on_file_openproject()")
  6227. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6228. try:
  6229. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6230. directory=self.get_last_folder(), filter=_filter_)
  6231. except TypeError:
  6232. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6233. # The Qt methods above will return a QString which can cause problems later.
  6234. # So far json.dump() will fail to serialize it.
  6235. # TODO: Improve the serialization methods and remove this fix.
  6236. filename = str(filename)
  6237. if filename == "":
  6238. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6239. else:
  6240. # self.worker_task.emit({'fcn': self.open_project,
  6241. # 'params': [filename]})
  6242. # The above was failing because open_project() is not
  6243. # thread safe. The new_project()
  6244. self.open_project(filename)
  6245. def on_fileopenhpgl2(self, signal, name=None):
  6246. """
  6247. File menu callback for opening a HPGL2.
  6248. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6249. :param name:
  6250. :return: None
  6251. """
  6252. self.defaults.report_usage("on_fileopenhpgl2")
  6253. App.log.debug("on_fileopenhpgl2()")
  6254. _filter_ = "HPGL2 Files (*.plt);;" \
  6255. "All Files (*.*)"
  6256. if name is None:
  6257. try:
  6258. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6259. directory=self.get_last_folder(),
  6260. filter=_filter_)
  6261. except TypeError:
  6262. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6263. filenames = [str(filename) for filename in filenames]
  6264. else:
  6265. filenames = [name]
  6266. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6267. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6268. _("Opening HPGL2 file.")),
  6269. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6270. color=QtGui.QColor("gray"))
  6271. if len(filenames) == 0:
  6272. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6273. else:
  6274. for filename in filenames:
  6275. if filename != '':
  6276. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6277. def on_file_openconfig(self, signal):
  6278. """
  6279. File menu callback for opening a config file.
  6280. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6281. :return: None
  6282. """
  6283. self.defaults.report_usage("on_file_openconfig")
  6284. App.log.debug("on_file_openconfig()")
  6285. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6286. try:
  6287. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6288. directory=self.data_path, filter=_filter_)
  6289. except TypeError:
  6290. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6291. filter=_filter_)
  6292. if filename == "":
  6293. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6294. else:
  6295. self.open_config_file(filename)
  6296. def on_file_exportsvg(self):
  6297. """
  6298. Callback for menu item File->Export SVG.
  6299. :return: None
  6300. """
  6301. self.defaults.report_usage("on_file_exportsvg")
  6302. App.log.debug("on_file_exportsvg()")
  6303. obj = self.collection.get_active()
  6304. if obj is None:
  6305. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6306. msg = _("Please Select a Geometry object to export")
  6307. msgbox = QtWidgets.QMessageBox()
  6308. msgbox.setInformativeText(msg)
  6309. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6310. msgbox.setDefaultButton(bt_ok)
  6311. msgbox.exec_()
  6312. return
  6313. # Check for more compatible types and add as required
  6314. if (not isinstance(obj, GeometryObject)
  6315. and not isinstance(obj, GerberObject)
  6316. and not isinstance(obj, CNCJobObject)
  6317. and not isinstance(obj, ExcellonObject)):
  6318. msg = '[ERROR_NOTCL] %s' % \
  6319. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6320. msgbox = QtWidgets.QMessageBox()
  6321. msgbox.setInformativeText(msg)
  6322. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6323. msgbox.setDefaultButton(bt_ok)
  6324. msgbox.exec_()
  6325. return
  6326. name = obj.options["name"]
  6327. _filter = "SVG File (*.svg);;All Files (*.*)"
  6328. try:
  6329. filename, _f = FCFileSaveDialog.get_saved_filename(
  6330. caption=_("Export SVG"),
  6331. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6332. filter=_filter)
  6333. except TypeError:
  6334. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6335. filename = str(filename)
  6336. if filename == "":
  6337. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6338. return
  6339. else:
  6340. self.export_svg(name, filename)
  6341. if self.defaults["global_open_style"] is False:
  6342. self.file_opened.emit("SVG", filename)
  6343. self.file_saved.emit("SVG", filename)
  6344. def on_file_exportpng(self):
  6345. self.defaults.report_usage("on_file_exportpng")
  6346. App.log.debug("on_file_exportpng()")
  6347. self.date = str(datetime.today()).rpartition('.')[0]
  6348. self.date = ''.join(c for c in self.date if c not in ':-')
  6349. self.date = self.date.replace(' ', '_')
  6350. if self.is_legacy is False:
  6351. image = _screenshot()
  6352. data = np.asarray(image)
  6353. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6354. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6355. return
  6356. filter_ = "PNG File (*.png);;All Files (*.*)"
  6357. try:
  6358. filename, _f = FCFileSaveDialog.get_saved_filename(
  6359. caption=_("Export PNG Image"),
  6360. directory=self.get_last_save_folder() + '/png_' + self.date,
  6361. filter=filter_)
  6362. except TypeError:
  6363. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6364. filename = str(filename)
  6365. if filename == "":
  6366. self.inform.emit(_("Cancelled."))
  6367. return
  6368. else:
  6369. if self.is_legacy is False:
  6370. write_png(filename, data)
  6371. else:
  6372. self.plotcanvas.figure.savefig(filename)
  6373. if self.defaults["global_open_style"] is False:
  6374. self.file_opened.emit("png", filename)
  6375. self.file_saved.emit("png", filename)
  6376. def on_file_savegerber(self):
  6377. """
  6378. Callback for menu item in Project context menu.
  6379. :return: None
  6380. """
  6381. self.defaults.report_usage("on_file_savegerber")
  6382. App.log.debug("on_file_savegerber()")
  6383. obj = self.collection.get_active()
  6384. if obj is None:
  6385. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6386. return
  6387. # Check for more compatible types and add as required
  6388. if not isinstance(obj, GerberObject):
  6389. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6390. return
  6391. name = self.collection.get_active().options["name"]
  6392. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6393. try:
  6394. filename, _f = FCFileSaveDialog.get_saved_filename(
  6395. caption="Save Gerber source file",
  6396. directory=self.get_last_save_folder() + '/' + name,
  6397. filter=_filter)
  6398. except TypeError:
  6399. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6400. filename = str(filename)
  6401. if filename == "":
  6402. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6403. return
  6404. else:
  6405. self.save_source_file(name, filename)
  6406. if self.defaults["global_open_style"] is False:
  6407. self.file_opened.emit("Gerber", filename)
  6408. self.file_saved.emit("Gerber", filename)
  6409. def on_file_savescript(self):
  6410. """
  6411. Callback for menu item in Project context menu.
  6412. :return: None
  6413. """
  6414. self.defaults.report_usage("on_file_savescript")
  6415. App.log.debug("on_file_savescript()")
  6416. obj = self.collection.get_active()
  6417. if obj is None:
  6418. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6419. return
  6420. # Check for more compatible types and add as required
  6421. if not isinstance(obj, ScriptObject):
  6422. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6423. return
  6424. name = self.collection.get_active().options["name"]
  6425. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6426. try:
  6427. filename, _f = FCFileSaveDialog.get_saved_filename(
  6428. caption="Save Script source file",
  6429. directory=self.get_last_save_folder() + '/' + name,
  6430. filter=_filter)
  6431. except TypeError:
  6432. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6433. filename = str(filename)
  6434. if filename == "":
  6435. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6436. return
  6437. else:
  6438. self.save_source_file(name, filename)
  6439. if self.defaults["global_open_style"] is False:
  6440. self.file_opened.emit("Script", filename)
  6441. self.file_saved.emit("Script", filename)
  6442. def on_file_savedocument(self):
  6443. """
  6444. Callback for menu item in Project context menu.
  6445. :return: None
  6446. """
  6447. self.defaults.report_usage("on_file_savedocument")
  6448. App.log.debug("on_file_savedocument()")
  6449. obj = self.collection.get_active()
  6450. if obj is None:
  6451. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6452. return
  6453. # Check for more compatible types and add as required
  6454. if not isinstance(obj, ScriptObject):
  6455. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6456. return
  6457. name = self.collection.get_active().options["name"]
  6458. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6459. try:
  6460. filename, _f = FCFileSaveDialog.get_saved_filename(
  6461. caption="Save Document source file",
  6462. directory=self.get_last_save_folder() + '/' + name,
  6463. filter=_filter)
  6464. except TypeError:
  6465. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6466. filename = str(filename)
  6467. if filename == "":
  6468. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6469. return
  6470. else:
  6471. self.save_source_file(name, filename)
  6472. if self.defaults["global_open_style"] is False:
  6473. self.file_opened.emit("Document", filename)
  6474. self.file_saved.emit("Document", filename)
  6475. def on_file_saveexcellon(self):
  6476. """
  6477. Callback for menu item in project context menu.
  6478. :return: None
  6479. """
  6480. self.defaults.report_usage("on_file_saveexcellon")
  6481. App.log.debug("on_file_saveexcellon()")
  6482. obj = self.collection.get_active()
  6483. if obj is None:
  6484. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6485. return
  6486. # Check for more compatible types and add as required
  6487. if not isinstance(obj, ExcellonObject):
  6488. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6489. return
  6490. name = self.collection.get_active().options["name"]
  6491. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6492. try:
  6493. filename, _f = FCFileSaveDialog.get_saved_filename(
  6494. caption=_("Save Excellon source file"),
  6495. directory=self.get_last_save_folder() + '/' + name,
  6496. filter=_filter)
  6497. except TypeError:
  6498. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6499. filename = str(filename)
  6500. if filename == "":
  6501. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6502. return
  6503. else:
  6504. self.save_source_file(name, filename)
  6505. if self.defaults["global_open_style"] is False:
  6506. self.file_opened.emit("Excellon", filename)
  6507. self.file_saved.emit("Excellon", filename)
  6508. def on_file_exportexcellon(self):
  6509. """
  6510. Callback for menu item File->Export->Excellon.
  6511. :return: None
  6512. """
  6513. self.defaults.report_usage("on_file_exportexcellon")
  6514. App.log.debug("on_file_exportexcellon()")
  6515. obj = self.collection.get_active()
  6516. if obj is None:
  6517. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6518. return
  6519. # Check for more compatible types and add as required
  6520. if not isinstance(obj, ExcellonObject):
  6521. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6522. return
  6523. name = self.collection.get_active().options["name"]
  6524. _filter = self.defaults["excellon_save_filters"]
  6525. try:
  6526. filename, _f = FCFileSaveDialog.get_saved_filename(
  6527. caption=_("Export Excellon"),
  6528. directory=self.get_last_save_folder() + '/' + name,
  6529. filter=_filter)
  6530. except TypeError:
  6531. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6532. filename = str(filename)
  6533. if filename == "":
  6534. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6535. return
  6536. else:
  6537. used_extension = filename.rpartition('.')[2]
  6538. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6539. self.export_excellon(name, filename)
  6540. if self.defaults["global_open_style"] is False:
  6541. self.file_opened.emit("Excellon", filename)
  6542. self.file_saved.emit("Excellon", filename)
  6543. def on_file_exportgerber(self):
  6544. """
  6545. Callback for menu item File->Export->Gerber.
  6546. :return: None
  6547. """
  6548. self.defaults.report_usage("on_file_exportgerber")
  6549. App.log.debug("on_file_exportgerber()")
  6550. obj = self.collection.get_active()
  6551. if obj is None:
  6552. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6553. return
  6554. # Check for more compatible types and add as required
  6555. if not isinstance(obj, GerberObject):
  6556. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6557. return
  6558. name = self.collection.get_active().options["name"]
  6559. _filter_ = self.defaults['gerber_save_filters']
  6560. try:
  6561. filename, _f = FCFileSaveDialog.get_saved_filename(
  6562. caption=_("Export Gerber"),
  6563. directory=self.get_last_save_folder() + '/' + name,
  6564. filter=_filter_)
  6565. except TypeError:
  6566. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6567. filename = str(filename)
  6568. if filename == "":
  6569. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6570. return
  6571. else:
  6572. used_extension = filename.rpartition('.')[2]
  6573. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6574. self.export_gerber(name, filename)
  6575. if self.defaults["global_open_style"] is False:
  6576. self.file_opened.emit("Gerber", filename)
  6577. self.file_saved.emit("Gerber", filename)
  6578. def on_file_exportdxf(self):
  6579. """
  6580. Callback for menu item File->Export DXF.
  6581. :return: None
  6582. """
  6583. self.defaults.report_usage("on_file_exportdxf")
  6584. App.log.debug("on_file_exportdxf()")
  6585. obj = self.collection.get_active()
  6586. if obj is None:
  6587. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6588. msg = _("Please Select a Geometry object to export")
  6589. msgbox = QtWidgets.QMessageBox()
  6590. msgbox.setInformativeText(msg)
  6591. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6592. msgbox.setDefaultButton(bt_ok)
  6593. msgbox.exec_()
  6594. return
  6595. # Check for more compatible types and add as required
  6596. if not isinstance(obj, GeometryObject):
  6597. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6598. msgbox = QtWidgets.QMessageBox()
  6599. msgbox.setInformativeText(msg)
  6600. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6601. msgbox.setDefaultButton(bt_ok)
  6602. msgbox.exec_()
  6603. return
  6604. name = self.collection.get_active().options["name"]
  6605. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6606. try:
  6607. filename, _f = FCFileSaveDialog.get_saved_filename(
  6608. caption=_("Export DXF"),
  6609. directory=self.get_last_save_folder() + '/' + name,
  6610. filter=_filter_)
  6611. except TypeError:
  6612. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6613. filename = str(filename)
  6614. if filename == "":
  6615. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6616. return
  6617. else:
  6618. self.export_dxf(name, filename)
  6619. if self.defaults["global_open_style"] is False:
  6620. self.file_opened.emit("DXF", filename)
  6621. self.file_saved.emit("DXF", filename)
  6622. def on_file_importsvg(self, type_of_obj):
  6623. """
  6624. Callback for menu item File->Import SVG.
  6625. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6626. :type type_of_obj: str
  6627. :return: None
  6628. """
  6629. self.defaults.report_usage("on_file_importsvg")
  6630. App.log.debug("on_file_importsvg()")
  6631. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6632. try:
  6633. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6634. directory=self.get_last_folder(), filter=_filter_)
  6635. except TypeError:
  6636. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6637. filter=_filter_)
  6638. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6639. type_of_obj = "geometry"
  6640. filenames = [str(filename) for filename in filenames]
  6641. if len(filenames) == 0:
  6642. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6643. else:
  6644. for filename in filenames:
  6645. if filename != '':
  6646. self.worker_task.emit({'fcn': self.import_svg,
  6647. 'params': [filename, type_of_obj]})
  6648. def on_file_importdxf(self, type_of_obj):
  6649. """
  6650. Callback for menu item File->Import DXF.
  6651. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6652. :type type_of_obj: str
  6653. :return: None
  6654. """
  6655. self.defaults.report_usage("on_file_importdxf")
  6656. App.log.debug("on_file_importdxf()")
  6657. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6658. try:
  6659. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6660. directory=self.get_last_folder(),
  6661. filter=_filter_)
  6662. except TypeError:
  6663. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6664. filter=_filter_)
  6665. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6666. type_of_obj = "geometry"
  6667. filenames = [str(filename) for filename in filenames]
  6668. if len(filenames) == 0:
  6669. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6670. else:
  6671. for filename in filenames:
  6672. if filename != '':
  6673. self.worker_task.emit({'fcn': self.import_dxf,
  6674. 'params': [filename, type_of_obj]})
  6675. # ###############################################################################################################
  6676. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6677. # ###############################################################################################################
  6678. def init_code_editor(self, name):
  6679. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6680. # add the tab if it was closed
  6681. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6682. self.text_editor_tab.setObjectName('text_editor_tab')
  6683. # delete the absolute and relative position and messages in the infobar
  6684. self.ui.position_label.setText("")
  6685. self.ui.rel_position_label.setText("")
  6686. # first clear previous text in text editor (if any)
  6687. self.text_editor_tab.code_editor.clear()
  6688. self.text_editor_tab.code_editor.setReadOnly(False)
  6689. self.toggle_codeeditor = True
  6690. self.text_editor_tab.code_editor.completer_enable = False
  6691. self.text_editor_tab.buttonRun.hide()
  6692. # make sure to keep a reference to the code editor
  6693. self.reference_code_editor = self.text_editor_tab.code_editor
  6694. # Switch plot_area to CNCJob tab
  6695. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6696. def on_view_source(self):
  6697. """
  6698. Called when the user wants to see the source file of the selected object
  6699. :return:
  6700. """
  6701. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6702. self.proc_container.view.set_busy(_("Loading..."))
  6703. try:
  6704. obj = self.collection.get_active()
  6705. except Exception as e:
  6706. log.debug("App.on_view_source() --> %s" % str(e))
  6707. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6708. return 'fail'
  6709. if obj is None:
  6710. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6711. return 'fail'
  6712. flt = "All Files (*.*)"
  6713. if obj.kind == 'gerber':
  6714. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6715. elif obj.kind == 'excellon':
  6716. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6717. elif obj.kind == 'cncjob':
  6718. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6719. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6720. # add the tab if it was closed
  6721. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6722. self.source_editor_tab.setObjectName('source_editor_tab')
  6723. # delete the absolute and relative position and messages in the infobar
  6724. self.ui.position_label.setText("")
  6725. self.ui.rel_position_label.setText("")
  6726. # first clear previous text in text editor (if any)
  6727. self.source_editor_tab.code_editor.clear()
  6728. self.source_editor_tab.code_editor.setReadOnly(False)
  6729. self.source_editor_tab.code_editor.completer_enable = False
  6730. self.source_editor_tab.buttonRun.hide()
  6731. # Switch plot_area to CNCJob tab
  6732. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6733. try:
  6734. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6735. except TypeError:
  6736. pass
  6737. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6738. try:
  6739. self.source_editor_tab.buttonSave.clicked.disconnect()
  6740. except TypeError:
  6741. pass
  6742. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6743. # then append the text from GCode to the text editor
  6744. if obj.kind == 'cncjob':
  6745. try:
  6746. file = obj.export_gcode(
  6747. preamble=self.defaults["cncjob_prepend"],
  6748. postamble=self.defaults["cncjob_append"],
  6749. to_file=True)
  6750. if file == 'fail':
  6751. return 'fail'
  6752. except AttributeError:
  6753. self.inform.emit('[WARNING_NOTCL] %s' %
  6754. _("There is no selected object for which to see it's source file code."))
  6755. return 'fail'
  6756. else:
  6757. try:
  6758. file = StringIO(obj.source_file)
  6759. except (AttributeError, TypeError):
  6760. self.inform.emit('[WARNING_NOTCL] %s' %
  6761. _("There is no selected object for which to see it's source file code."))
  6762. return 'fail'
  6763. self.source_editor_tab.t_frame.hide()
  6764. try:
  6765. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6766. # for line in file:
  6767. # QtWidgets.QApplication.processEvents()
  6768. # proc_line = str(line).strip('\n')
  6769. # self.source_editor_tab.code_editor.append(proc_line)
  6770. except Exception as e:
  6771. log.debug('App.on_view_source() -->%s' % str(e))
  6772. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6773. return
  6774. self.source_editor_tab.handleTextChanged()
  6775. self.source_editor_tab.t_frame.show()
  6776. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6777. self.proc_container.view.set_idle()
  6778. # self.ui.show()
  6779. def on_toggle_code_editor(self):
  6780. self.defaults.report_usage("on_toggle_code_editor()")
  6781. if self.toggle_codeeditor is False:
  6782. self.init_code_editor(name=_("Code Editor"))
  6783. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6784. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6785. self.text_editor_tab.buttonSave.clicked.disconnect()
  6786. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6787. else:
  6788. for idx in range(self.ui.plot_tab_area.count()):
  6789. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6790. self.ui.plot_tab_area.closeTab(idx)
  6791. break
  6792. self.toggle_codeeditor = False
  6793. def on_code_editor_close(self):
  6794. self.toggle_codeeditor = False
  6795. def goto_text_line(self):
  6796. """
  6797. Will scroll a text to the specified text line.
  6798. :return: None
  6799. """
  6800. dia_box = Dialog_box(title=_("Go to Line ..."),
  6801. label=_("Line:"),
  6802. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6803. initial_text='')
  6804. try:
  6805. line = int(dia_box.location) - 1
  6806. except (ValueError, TypeError):
  6807. line = 0
  6808. if dia_box.ok:
  6809. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6810. # at the top of the window
  6811. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6812. # get the document() of the TextEditor
  6813. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6814. # create a Text Cursor based on the searched line
  6815. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6816. # set cursor of the code editor with the cursor at the searcehd line
  6817. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6818. def on_filenewscript(self, silent=False, name=None, text=None):
  6819. """
  6820. Will create a new script file and open it in the Code Editor
  6821. :param silent: if True will not display status messages
  6822. :param name: if specified will be the name of the new script
  6823. :param text: pass a source file to the newly created script to be loaded in it
  6824. :return: None
  6825. """
  6826. if silent is False:
  6827. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6828. # delete the absolute and relative position and messages in the infobar
  6829. self.ui.position_label.setText("")
  6830. self.ui.rel_position_label.setText("")
  6831. if name is not None:
  6832. self.new_script_object(name=name, text=text)
  6833. else:
  6834. self.new_script_object(text=text)
  6835. # script_text = script_obj.source_file
  6836. #
  6837. # self.proc_container.view.set_busy(_("Loading..."))
  6838. # script_obj.script_editor_tab.t_frame.hide()
  6839. #
  6840. # script_obj.script_editor_tab.t_frame.show()
  6841. # self.proc_container.view.set_idle()
  6842. def on_fileopenscript(self, name=None, silent=False):
  6843. """
  6844. Will open a Tcl script file into the Code Editor
  6845. :param silent: if True will not display status messages
  6846. :param name: name of a Tcl script file to open
  6847. :return:
  6848. """
  6849. self.defaults.report_usage("on_fileopenscript")
  6850. App.log.debug("on_fileopenscript()")
  6851. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6852. "All Files (*.*)"
  6853. if name:
  6854. filenames = [name]
  6855. else:
  6856. try:
  6857. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6858. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6859. except TypeError:
  6860. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6861. if len(filenames) == 0:
  6862. if silent is False:
  6863. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6864. else:
  6865. for filename in filenames:
  6866. if filename != '':
  6867. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6868. def on_fileopenscript_example(self, name=None, silent=False):
  6869. """
  6870. Will open a Tcl script file into the Code Editor
  6871. :param silent: if True will not display status messages
  6872. :param name: name of a Tcl script file to open
  6873. :return:
  6874. """
  6875. self.report_usage("on_fileopenscript_example")
  6876. App.log.debug("on_fileopenscript_example()")
  6877. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6878. "All Files (*.*)"
  6879. # test if the app was frozen and choose the path for the configuration file
  6880. if getattr(sys, "frozen", False) is True:
  6881. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6882. else:
  6883. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6884. if name:
  6885. filenames = [name]
  6886. else:
  6887. try:
  6888. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6889. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6890. except TypeError:
  6891. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6892. if len(filenames) == 0:
  6893. if silent is False:
  6894. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6895. else:
  6896. for filename in filenames:
  6897. if filename != '':
  6898. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6899. def on_filerunscript(self, name=None, silent=False):
  6900. """
  6901. File menu callback for loading and running a TCL script.
  6902. :param silent: if True will not display status messages
  6903. :param name: name of a Tcl script file to be run by FlatCAM
  6904. :return: None
  6905. """
  6906. self.defaults.report_usage("on_filerunscript")
  6907. App.log.debug("on_file_runscript()")
  6908. if name:
  6909. filename = name
  6910. if self.cmd_line_headless != 1:
  6911. self.splash.showMessage('%s: %ssec\n%s' %
  6912. (_("Canvas initialization started.\n"
  6913. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6914. _("Executing ScriptObject file.")
  6915. ),
  6916. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6917. color=QtGui.QColor("gray"))
  6918. else:
  6919. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6920. "All Files (*.*)"
  6921. try:
  6922. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6923. directory=self.get_last_folder(), filter=_filter_)
  6924. except TypeError:
  6925. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6926. # The Qt methods above will return a QString which can cause problems later.
  6927. # So far json.dump() will fail to serialize it.
  6928. filename = str(filename)
  6929. if filename == "":
  6930. if silent is False:
  6931. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6932. else:
  6933. if self.cmd_line_headless != 1:
  6934. if self.ui.shell_dock.isHidden():
  6935. self.ui.shell_dock.show()
  6936. try:
  6937. with open(filename, "r") as tcl_script:
  6938. cmd_line_shellfile_content = tcl_script.read()
  6939. if self.cmd_line_headless != 1:
  6940. self.shell.exec_command(cmd_line_shellfile_content)
  6941. else:
  6942. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6943. if silent is False:
  6944. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6945. except Exception as e:
  6946. log.debug("App.on_filerunscript() -> %s" % str(e))
  6947. sys.exit(2)
  6948. def on_file_saveproject(self, silent=False):
  6949. """
  6950. Callback for menu item File->Save Project. Saves the project to
  6951. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6952. if set to None. The project is saved by calling ``self.save_project()``.
  6953. :param silent: if True will not display status messages
  6954. :return: None
  6955. """
  6956. self.defaults.report_usage("on_file_saveproject")
  6957. if self.project_filename is None:
  6958. self.on_file_saveprojectas()
  6959. else:
  6960. self.worker_task.emit({'fcn': self.save_project,
  6961. 'params': [self.project_filename, silent]})
  6962. if self.defaults["global_open_style"] is False:
  6963. self.file_opened.emit("project", self.project_filename)
  6964. self.file_saved.emit("project", self.project_filename)
  6965. self.set_ui_title(name=self.project_filename)
  6966. self.should_we_save = False
  6967. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6968. """
  6969. Callback for menu item File->Save Project As... Opens a file
  6970. chooser and saves the project to the given file via
  6971. ``self.save_project()``.
  6972. :param make_copy if to be create a copy of the project; boolean
  6973. :param use_thread: if to be run in a separate thread; boolean
  6974. :param quit_action: if to be followed by quiting the application; boolean
  6975. :return: None
  6976. """
  6977. self.defaults.report_usage("on_file_saveprojectas")
  6978. self.date = str(datetime.today()).rpartition('.')[0]
  6979. self.date = ''.join(c for c in self.date if c not in ':-')
  6980. self.date = self.date.replace(' ', '_')
  6981. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6982. try:
  6983. filename, _f = FCFileSaveDialog.get_saved_filename(
  6984. caption=_("Save Project As ..."),
  6985. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6986. proj=_("Project")),
  6987. filter=filter_
  6988. )
  6989. except TypeError:
  6990. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6991. filename = str(filename)
  6992. if filename == '':
  6993. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6994. return
  6995. if use_thread is True:
  6996. self.worker_task.emit({'fcn': self.save_project,
  6997. 'params': [filename, quit_action]})
  6998. else:
  6999. self.save_project(filename, quit_action)
  7000. # self.save_project(filename)
  7001. if self.defaults["global_open_style"] is False:
  7002. self.file_opened.emit("project", filename)
  7003. self.file_saved.emit("project", filename)
  7004. if not make_copy:
  7005. self.project_filename = filename
  7006. self.set_ui_title(name=self.project_filename)
  7007. self.should_we_save = False
  7008. def on_file_save_objects_pdf(self, use_thread=True):
  7009. self.date = str(datetime.today()).rpartition('.')[0]
  7010. self.date = ''.join(c for c in self.date if c not in ':-')
  7011. self.date = self.date.replace(' ', '_')
  7012. try:
  7013. obj_selection = self.collection.get_selected()
  7014. if len(obj_selection) == 1:
  7015. obj_name = str(obj_selection[0].options['name'])
  7016. else:
  7017. obj_name = _("FlatCAM objects print")
  7018. except AttributeError as err:
  7019. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7020. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7021. return
  7022. if not obj_selection:
  7023. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7024. return
  7025. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7026. try:
  7027. filename, _f = FCFileSaveDialog.get_saved_filename(
  7028. caption=_("Save Object as PDF ..."),
  7029. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7030. obj_name=obj_name,
  7031. date=self.date),
  7032. filter=filter_
  7033. )
  7034. except TypeError:
  7035. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7036. filename = str(filename)
  7037. if filename == '':
  7038. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7039. return
  7040. if use_thread is True:
  7041. proc = self.proc_container.new(_("Printing PDF ... Please wait."))
  7042. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7043. else:
  7044. self.save_pdf(filename, obj_selection)
  7045. # self.save_project(filename)
  7046. if self.defaults["global_open_style"] is False:
  7047. self.file_opened.emit("pdf", filename)
  7048. self.file_saved.emit("pdf", filename)
  7049. def save_pdf(self, file_name, obj_selection):
  7050. p_size = self.defaults['global_workspaceT']
  7051. orientation = self.defaults['global_workspace_orientation']
  7052. color = 'black'
  7053. transparency_level = 1.0
  7054. self.pagesize = {}
  7055. self.pagesize.update(
  7056. {
  7057. 'Bounds': None,
  7058. 'A0': (841 * mm, 1189 * mm),
  7059. 'A1': (594 * mm, 841 * mm),
  7060. 'A2': (420 * mm, 594 * mm),
  7061. 'A3': (297 * mm, 420 * mm),
  7062. 'A4': (210 * mm, 297 * mm),
  7063. 'A5': (148 * mm, 210 * mm),
  7064. 'A6': (105 * mm, 148 * mm),
  7065. 'A7': (74 * mm, 105 * mm),
  7066. 'A8': (52 * mm, 74 * mm),
  7067. 'A9': (37 * mm, 52 * mm),
  7068. 'A10': (26 * mm, 37 * mm),
  7069. 'B0': (1000 * mm, 1414 * mm),
  7070. 'B1': (707 * mm, 1000 * mm),
  7071. 'B2': (500 * mm, 707 * mm),
  7072. 'B3': (353 * mm, 500 * mm),
  7073. 'B4': (250 * mm, 353 * mm),
  7074. 'B5': (176 * mm, 250 * mm),
  7075. 'B6': (125 * mm, 176 * mm),
  7076. 'B7': (88 * mm, 125 * mm),
  7077. 'B8': (62 * mm, 88 * mm),
  7078. 'B9': (44 * mm, 62 * mm),
  7079. 'B10': (31 * mm, 44 * mm),
  7080. 'C0': (917 * mm, 1297 * mm),
  7081. 'C1': (648 * mm, 917 * mm),
  7082. 'C2': (458 * mm, 648 * mm),
  7083. 'C3': (324 * mm, 458 * mm),
  7084. 'C4': (229 * mm, 324 * mm),
  7085. 'C5': (162 * mm, 229 * mm),
  7086. 'C6': (114 * mm, 162 * mm),
  7087. 'C7': (81 * mm, 114 * mm),
  7088. 'C8': (57 * mm, 81 * mm),
  7089. 'C9': (40 * mm, 57 * mm),
  7090. 'C10': (28 * mm, 40 * mm),
  7091. # American paper sizes
  7092. 'LETTER': (8.5 * inch, 11 * inch),
  7093. 'LEGAL': (8.5 * inch, 14 * inch),
  7094. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7095. # From https://en.wikipedia.org/wiki/Paper_size
  7096. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7097. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7098. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7099. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7100. 'LEDGER': (17 * inch, 11 * inch),
  7101. }
  7102. )
  7103. exported_svg = []
  7104. for obj in obj_selection:
  7105. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7106. scale_factor_x=None, scale_factor_y=None,
  7107. skew_factor_x=None, skew_factor_y=None,
  7108. mirror=None)
  7109. if obj.kind.lower() == 'gerber':
  7110. # color = self.defaults["gerber_plot_fill"][:-2]
  7111. color = obj.fill_color[:-2]
  7112. elif obj.kind.lower() == 'excellon':
  7113. color = '#C40000'
  7114. elif obj.kind.lower() == 'geometry':
  7115. color = self.defaults["global_draw_color"]
  7116. # Change the attributes of the exported SVG
  7117. # We don't need stroke-width
  7118. # We set opacity to maximum
  7119. # We set the colour to WHITE
  7120. root = ET.fromstring(svg_obj)
  7121. for child in root:
  7122. child.set('fill', str(color))
  7123. child.set('opacity', str(transparency_level))
  7124. child.set('stroke', str(color))
  7125. exported_svg.append(ET.tostring(root))
  7126. xmin = Inf
  7127. ymin = Inf
  7128. xmax = -Inf
  7129. ymax = -Inf
  7130. for obj in obj_selection:
  7131. try:
  7132. gxmin, gymin, gxmax, gymax = obj.bounds()
  7133. xmin = min([xmin, gxmin])
  7134. ymin = min([ymin, gymin])
  7135. xmax = max([xmax, gxmax])
  7136. ymax = max([ymax, gymax])
  7137. except Exception as e:
  7138. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7139. # Determine bounding area for svg export
  7140. bounds = [xmin, ymin, xmax, ymax]
  7141. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7142. # This contain the measure units
  7143. uom = obj_selection[0].units.lower()
  7144. # Define a boundary around SVG of about 1.0mm (~39mils)
  7145. if uom in "mm":
  7146. boundary = 1.0
  7147. else:
  7148. boundary = 0.0393701
  7149. # Convert everything to strings for use in the xml doc
  7150. svgwidth = str(size[0] + (2 * boundary))
  7151. svgheight = str(size[1] + (2 * boundary))
  7152. minx = str(bounds[0] - boundary)
  7153. miny = str(bounds[1] + boundary + size[1])
  7154. # Add a SVG Header and footer to the svg output from shapely
  7155. # The transform flips the Y Axis so that everything renders
  7156. # properly within svg apps such as inkscape
  7157. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7158. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7159. svg_header += 'width="' + svgwidth + uom + '" '
  7160. svg_header += 'height="' + svgheight + uom + '" '
  7161. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7162. svg_header += '>'
  7163. svg_header += '<g transform="scale(1,-1)">'
  7164. svg_footer = '</g> </svg>'
  7165. svg_elem = str(svg_header)
  7166. for svg_item in exported_svg:
  7167. svg_elem += str(svg_item)
  7168. svg_elem += str(svg_footer)
  7169. # Parse the xml through a xml parser just to add line feeds
  7170. # and to make it look more pretty for the output
  7171. doc = parse_xml_string(svg_elem)
  7172. doc_final = doc.toprettyxml()
  7173. try:
  7174. if self.defaults['units'].upper() == 'IN':
  7175. unit = inch
  7176. else:
  7177. unit = mm
  7178. doc_final = StringIO(doc_final)
  7179. drawing = svg2rlg(doc_final)
  7180. if p_size == 'Bounds':
  7181. renderPDF.drawToFile(drawing, file_name)
  7182. else:
  7183. if orientation == 'p':
  7184. page_size = portrait(self.pagesize[p_size])
  7185. else:
  7186. page_size = landscape(self.pagesize[p_size])
  7187. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7188. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7189. renderPDF.draw(drawing, my_canvas, 0, 0)
  7190. my_canvas.save()
  7191. except Exception as e:
  7192. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7193. return 'fail'
  7194. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7195. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7196. """
  7197. Exports a Geometry Object to an SVG file.
  7198. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7199. :param filename: Path to the SVG file to save to.
  7200. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7201. :return:
  7202. """
  7203. self.defaults.report_usage("export_svg()")
  7204. if filename is None:
  7205. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7206. is not None else self.defaults["global_last_folder"]
  7207. self.log.debug("export_svg()")
  7208. try:
  7209. obj = self.collection.get_by_name(str(obj_name))
  7210. except Exception:
  7211. # TODO: The return behavior has not been established... should raise exception?
  7212. return "Could not retrieve object: %s" % obj_name
  7213. with self.proc_container.new(_("Exporting SVG")) as proc:
  7214. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7215. # Determine bounding area for svg export
  7216. bounds = obj.bounds()
  7217. size = obj.size()
  7218. # Convert everything to strings for use in the xml doc
  7219. svgwidth = str(size[0])
  7220. svgheight = str(size[1])
  7221. minx = str(bounds[0])
  7222. miny = str(bounds[1] - size[1])
  7223. uom = obj.units.lower()
  7224. # Add a SVG Header and footer to the svg output from shapely
  7225. # The transform flips the Y Axis so that everything renders
  7226. # properly within svg apps such as inkscape
  7227. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7228. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7229. svg_header += 'width="' + svgwidth + uom + '" '
  7230. svg_header += 'height="' + svgheight + uom + '" '
  7231. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7232. svg_header += '<g transform="scale(1,-1)">'
  7233. svg_footer = '</g> </svg>'
  7234. svg_elem = svg_header + exported_svg + svg_footer
  7235. # Parse the xml through a xml parser just to add line feeds
  7236. # and to make it look more pretty for the output
  7237. svgcode = parse_xml_string(svg_elem)
  7238. svgcode = svgcode.toprettyxml()
  7239. try:
  7240. with open(filename, 'w') as fp:
  7241. fp.write(svgcode)
  7242. except PermissionError:
  7243. self.inform.emit('[WARNING] %s' %
  7244. _("Permission denied, saving not possible.\n"
  7245. "Most likely another app is holding the file open and not accessible."))
  7246. return 'fail'
  7247. if self.defaults["global_open_style"] is False:
  7248. self.file_opened.emit("SVG", filename)
  7249. self.file_saved.emit("SVG", filename)
  7250. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7251. def save_source_file(self, obj_name, filename, use_thread=True):
  7252. """
  7253. Exports a FlatCAM Object to an Gerber/Excellon file.
  7254. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7255. :param filename: Path to the Gerber file to save to.
  7256. :param use_thread: if to be run in a separate thread
  7257. :return:
  7258. """
  7259. self.defaults.report_usage("save source file()")
  7260. if filename is None:
  7261. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7262. is not None else self.defaults["global_last_folder"]
  7263. self.log.debug("save source file()")
  7264. obj = self.collection.get_by_name(obj_name)
  7265. file_string = StringIO(obj.source_file)
  7266. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7267. if file_string.getvalue() == '':
  7268. self.inform.emit('[ERROR_NOTCL] %s' %
  7269. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7270. return 'fail'
  7271. try:
  7272. with open(filename, 'w') as file:
  7273. file.writelines('G04*\n')
  7274. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7275. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7276. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7277. file.writelines('G04 Created on : %s*\n' % time_string)
  7278. for line in file_string:
  7279. file.writelines(line)
  7280. except PermissionError:
  7281. self.inform.emit('[WARNING] %s' %
  7282. _("Permission denied, saving not possible.\n"
  7283. "Most likely another app is holding the file open and not accessible."))
  7284. return 'fail'
  7285. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7286. """
  7287. Exports a Excellon Object to an Excellon file.
  7288. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7289. :param filename: Path to the Excellon file to save to.
  7290. :param local_use:
  7291. :param use_thread: if to be run in a separate thread
  7292. :return:
  7293. """
  7294. self.defaults.report_usage("export_excellon()")
  7295. if filename is None:
  7296. if self.defaults["global_last_save_folder"]:
  7297. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7298. else:
  7299. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7300. self.log.debug("export_excellon()")
  7301. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7302. self.defaults["excellon_exp_decimals"]
  7303. )
  7304. if local_use is None:
  7305. try:
  7306. obj = self.collection.get_by_name(str(obj_name))
  7307. except Exception:
  7308. return "Could not retrieve object: %s" % obj_name
  7309. else:
  7310. obj = local_use
  7311. if not isinstance(obj, ExcellonObject):
  7312. self.inform.emit('[ERROR_NOTCL] %s' %
  7313. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7314. return
  7315. # updated units
  7316. eunits = self.defaults["excellon_exp_units"]
  7317. ewhole = self.defaults["excellon_exp_integer"]
  7318. efract = self.defaults["excellon_exp_decimals"]
  7319. ezeros = self.defaults["excellon_exp_zeros"]
  7320. eformat = self.defaults["excellon_exp_format"]
  7321. slot_type = self.defaults["excellon_exp_slot_type"]
  7322. fc_units = self.defaults['units'].upper()
  7323. if fc_units == 'MM':
  7324. factor = 1 if eunits == 'METRIC' else 0.03937
  7325. else:
  7326. factor = 25.4 if eunits == 'METRIC' else 1
  7327. def make_excellon():
  7328. try:
  7329. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7330. header = 'M48\n'
  7331. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7332. (str(self.version), str(self.version_date))
  7333. header += ';Filename: %s' % str(obj_name) + '\n'
  7334. header += ';Created on : %s' % time_str + '\n'
  7335. if eformat == 'dec':
  7336. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7337. header += eunits + '\n'
  7338. for tool in obj.tools:
  7339. if eunits == 'METRIC':
  7340. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7341. tool=str(tool),
  7342. dec=2)
  7343. else:
  7344. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7345. tool=str(tool),
  7346. dec=4)
  7347. else:
  7348. if ezeros == 'LZ':
  7349. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7350. form='ndec', e_zeros='LZ', factor=factor,
  7351. slot_type=slot_type)
  7352. header += '%s,%s\n' % (eunits, 'LZ')
  7353. header += format_exc
  7354. for tool in obj.tools:
  7355. if eunits == 'METRIC':
  7356. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7357. tool=str(tool),
  7358. dec=2)
  7359. else:
  7360. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7361. tool=str(tool),
  7362. dec=4)
  7363. else:
  7364. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7365. form='ndec', e_zeros='TZ', factor=factor,
  7366. slot_type=slot_type)
  7367. header += '%s,%s\n' % (eunits, 'TZ')
  7368. header += format_exc
  7369. for tool in obj.tools:
  7370. if eunits == 'METRIC':
  7371. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7372. tool=str(tool),
  7373. dec=2)
  7374. else:
  7375. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7376. tool=str(tool),
  7377. dec=4)
  7378. header += '%\n'
  7379. footer = 'M30\n'
  7380. exported_excellon = header
  7381. exported_excellon += excellon_code
  7382. exported_excellon += footer
  7383. if local_use is None:
  7384. try:
  7385. with open(filename, 'w') as fp:
  7386. fp.write(exported_excellon)
  7387. except PermissionError:
  7388. self.inform.emit('[WARNING] %s' %
  7389. _("Permission denied, saving not possible.\n"
  7390. "Most likely another app is holding the file open and not accessible."))
  7391. return 'fail'
  7392. if self.defaults["global_open_style"] is False:
  7393. self.file_opened.emit("Excellon", filename)
  7394. self.file_saved.emit("Excellon", filename)
  7395. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7396. else:
  7397. return exported_excellon
  7398. except Exception as e:
  7399. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7400. return 'fail'
  7401. if use_thread is True:
  7402. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7403. def job_thread_exc(app_obj):
  7404. ret = make_excellon()
  7405. if ret == 'fail':
  7406. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7407. return
  7408. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7409. else:
  7410. eret = make_excellon()
  7411. if eret == 'fail':
  7412. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7413. return 'fail'
  7414. if local_use is not None:
  7415. return eret
  7416. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7417. """
  7418. Exports a Gerber Object to an Gerber file.
  7419. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7420. :param filename: Path to the Gerber file to save to.
  7421. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7422. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7423. :param use_thread: if to be run in a separate thread
  7424. :return:
  7425. """
  7426. self.defaults.report_usage("export_gerber()")
  7427. if filename is None:
  7428. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7429. is not None else self.defaults["global_last_folder"]
  7430. self.log.debug("export_gerber()")
  7431. if local_use is None:
  7432. try:
  7433. obj = self.collection.get_by_name(str(obj_name))
  7434. except Exception:
  7435. return "Could not retrieve object: %s" % obj_name
  7436. else:
  7437. obj = local_use
  7438. # updated units
  7439. gunits = self.defaults["gerber_exp_units"]
  7440. gwhole = self.defaults["gerber_exp_integer"]
  7441. gfract = self.defaults["gerber_exp_decimals"]
  7442. gzeros = self.defaults["gerber_exp_zeros"]
  7443. fc_units = self.defaults['units'].upper()
  7444. if fc_units == 'MM':
  7445. factor = 1 if gunits == 'MM' else 0.03937
  7446. else:
  7447. factor = 25.4 if gunits == 'MM' else 1
  7448. def make_gerber():
  7449. try:
  7450. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7451. header = 'G04*\n'
  7452. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7453. (str(self.version), str(self.version_date))
  7454. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7455. header += 'G04 Created on : %s*' % time_str + '\n'
  7456. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7457. header += "%MO{units}*%\n".format(units=gunits)
  7458. for apid in obj.apertures:
  7459. if obj.apertures[apid]['type'] == 'C':
  7460. header += "%ADD{apid}{type},{size}*%\n".format(
  7461. apid=str(apid),
  7462. type='C',
  7463. size=(factor * obj.apertures[apid]['size'])
  7464. )
  7465. elif obj.apertures[apid]['type'] == 'R':
  7466. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7467. apid=str(apid),
  7468. type='R',
  7469. width=(factor * obj.apertures[apid]['width']),
  7470. height=(factor * obj.apertures[apid]['height'])
  7471. )
  7472. elif obj.apertures[apid]['type'] == 'O':
  7473. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7474. apid=str(apid),
  7475. type='O',
  7476. width=(factor * obj.apertures[apid]['width']),
  7477. height=(factor * obj.apertures[apid]['height'])
  7478. )
  7479. header += '\n'
  7480. # obsolete units but some software may need it
  7481. if gunits == 'IN':
  7482. header += 'G70*\n'
  7483. else:
  7484. header += 'G71*\n'
  7485. # Absolute Mode
  7486. header += 'G90*\n'
  7487. header += 'G01*\n'
  7488. # positive polarity
  7489. header += '%LPD*%\n'
  7490. footer = 'M02*\n'
  7491. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7492. exported_gerber = header
  7493. exported_gerber += gerber_code
  7494. exported_gerber += footer
  7495. if local_use is None:
  7496. try:
  7497. with open(filename, 'w') as fp:
  7498. fp.write(exported_gerber)
  7499. except PermissionError:
  7500. self.inform.emit('[WARNING] %s' %
  7501. _("Permission denied, saving not possible.\n"
  7502. "Most likely another app is holding the file open and not accessible."))
  7503. return 'fail'
  7504. if self.defaults["global_open_style"] is False:
  7505. self.file_opened.emit("Gerber", filename)
  7506. self.file_saved.emit("Gerber", filename)
  7507. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7508. else:
  7509. return exported_gerber
  7510. except Exception as e:
  7511. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7512. return 'fail'
  7513. if use_thread is True:
  7514. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7515. def job_thread_grb(app_obj):
  7516. ret = make_gerber()
  7517. if ret == 'fail':
  7518. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7519. return
  7520. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7521. else:
  7522. gret = make_gerber()
  7523. if gret == 'fail':
  7524. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7525. return 'fail'
  7526. if local_use is not None:
  7527. return gret
  7528. def export_dxf(self, obj_name, filename, use_thread=True):
  7529. """
  7530. Exports a Geometry Object to an DXF file.
  7531. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7532. :param filename: Path to the DXF file to save to.
  7533. :param use_thread: if to be run in a separate thread
  7534. :return:
  7535. """
  7536. self.defaults.report_usage("export_dxf()")
  7537. if filename is None:
  7538. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7539. is not None else self.defaults["global_last_folder"]
  7540. self.log.debug("export_dxf()")
  7541. try:
  7542. obj = self.collection.get_by_name(str(obj_name))
  7543. except Exception:
  7544. # TODO: The return behavior has not been established... should raise exception?
  7545. return "Could not retrieve object: %s" % obj_name
  7546. def make_dxf():
  7547. try:
  7548. dxf_code = obj.export_dxf()
  7549. dxf_code.saveas(filename)
  7550. if self.defaults["global_open_style"] is False:
  7551. self.file_opened.emit("DXF", filename)
  7552. self.file_saved.emit("DXF", filename)
  7553. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7554. except Exception:
  7555. return 'fail'
  7556. if use_thread is True:
  7557. with self.proc_container.new(_("Exporting DXF")) as proc:
  7558. def job_thread_exc(app_obj):
  7559. ret_dxf_val = make_dxf()
  7560. if ret_dxf_val == 'fail':
  7561. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7562. return
  7563. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7564. else:
  7565. ret = make_dxf()
  7566. if ret == 'fail':
  7567. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7568. return
  7569. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7570. """
  7571. Adds a new Geometry Object to the projects and populates
  7572. it with shapes extracted from the SVG file.
  7573. :param filename: Path to the SVG file.
  7574. :param geo_type: Type of FlatCAM object that will be created from SVG
  7575. :param outname:
  7576. :return:
  7577. """
  7578. self.defaults.report_usage("import_svg()")
  7579. log.debug("App.import_svg()")
  7580. obj_type = ""
  7581. if geo_type is None or geo_type == "geometry":
  7582. obj_type = "geometry"
  7583. elif geo_type == "gerber":
  7584. obj_type = "gerber"
  7585. else:
  7586. self.inform.emit('[ERROR_NOTCL] %s' %
  7587. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7588. return
  7589. units = self.defaults['units'].upper()
  7590. def obj_init(geo_obj, app_obj):
  7591. geo_obj.import_svg(filename, obj_type, units=units)
  7592. geo_obj.multigeo = False
  7593. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7594. with self.proc_container.new(_("Importing SVG")) as proc:
  7595. # Object name
  7596. name = outname or filename.split('/')[-1].split('\\')[-1]
  7597. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7598. if ret == 'fail':
  7599. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7600. return 'fail'
  7601. # Register recent file
  7602. self.file_opened.emit("svg", filename)
  7603. # GUI feedback
  7604. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7605. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7606. """
  7607. Adds a new Geometry Object to the projects and populates
  7608. it with shapes extracted from the DXF file.
  7609. :param filename: Path to the DXF file.
  7610. :param geo_type: Type of FlatCAM object that will be created from DXF
  7611. :param outname: Name for the imported Geometry
  7612. :return:
  7613. """
  7614. self.defaults.report_usage("import_dxf()")
  7615. obj_type = ""
  7616. if geo_type is None or geo_type == "geometry":
  7617. obj_type = "geometry"
  7618. elif geo_type == "gerber":
  7619. obj_type = geo_type
  7620. else:
  7621. self.inform.emit('[ERROR_NOTCL] %s' %
  7622. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7623. return
  7624. units = self.defaults['units'].upper()
  7625. def obj_init(geo_obj, app_obj):
  7626. geo_obj.import_dxf(filename, obj_type, units=units)
  7627. geo_obj.multigeo = False
  7628. with self.proc_container.new(_("Importing DXF")):
  7629. # Object name
  7630. name = outname or filename.split('/')[-1].split('\\')[-1]
  7631. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7632. if ret == 'fail':
  7633. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7634. return 'fail'
  7635. # Register recent file
  7636. self.file_opened.emit("dxf", filename)
  7637. # GUI feedback
  7638. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7639. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7640. """
  7641. Opens a Gerber file, parses it and creates a new object for
  7642. it in the program. Thread-safe.
  7643. :param outname: Name of the resulting object. None causes the
  7644. name to be that of the file. Str.
  7645. :param filename: Gerber file filename
  7646. :type filename: str
  7647. :param plot: boolean, to plot or not the resulting object
  7648. :param from_tcl: True if run from Tcl Shell
  7649. :return: None
  7650. """
  7651. # How the object should be initialized
  7652. def obj_init(gerber_obj, app_obj):
  7653. assert isinstance(gerber_obj, GerberObject), \
  7654. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7655. # Opening the file happens here
  7656. try:
  7657. gerber_obj.parse_file(filename)
  7658. except IOError:
  7659. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7660. return "fail"
  7661. except ParseError as err:
  7662. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7663. app_obj.log.error(str(err))
  7664. return "fail"
  7665. except Exception as e:
  7666. log.debug("App.open_gerber() --> %s" % str(e))
  7667. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7668. msg += traceback.format_exc()
  7669. app_obj.inform.emit(msg)
  7670. return "fail"
  7671. if gerber_obj.is_empty():
  7672. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7673. _("Object is not Gerber file or empty. Aborting object creation."))
  7674. return "fail"
  7675. App.log.debug("open_gerber()")
  7676. with self.proc_container.new(_("Opening Gerber")):
  7677. # Object name
  7678. name = outname or filename.split('/')[-1].split('\\')[-1]
  7679. # # ## Object creation # ##
  7680. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7681. if ret_val == 'fail':
  7682. if from_tcl:
  7683. filename = self.defaults['global_tcl_path'] + '/' + name
  7684. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7685. if ret_val == 'fail':
  7686. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7687. return 'fail'
  7688. # Register recent file
  7689. self.file_opened.emit("gerber", filename)
  7690. # GUI feedback
  7691. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7692. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7693. """
  7694. Opens an Excellon file, parses it and creates a new object for
  7695. it in the program. Thread-safe.
  7696. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7697. :param filename: Excellon file filename
  7698. :type filename: str
  7699. :param plot: boolean, to plot or not the resulting object
  7700. :param from_tcl: True if run from Tcl Shell
  7701. :return: None
  7702. """
  7703. App.log.debug("open_excellon()")
  7704. # How the object should be initialized
  7705. def obj_init(excellon_obj, app_obj):
  7706. try:
  7707. ret = excellon_obj.parse_file(filename=filename)
  7708. if ret == "fail":
  7709. log.debug("Excellon parsing failed.")
  7710. self.inform.emit('[ERROR_NOTCL] %s' %
  7711. _("This is not Excellon file."))
  7712. return "fail"
  7713. except IOError:
  7714. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7715. (_("Cannot open file"), filename))
  7716. log.debug("Could not open Excellon object.")
  7717. return "fail"
  7718. except Exception:
  7719. msg = '[ERROR_NOTCL] %s' % \
  7720. _("An internal error has occurred. See shell.\n")
  7721. msg += traceback.format_exc()
  7722. app_obj.inform.emit(msg)
  7723. return "fail"
  7724. ret = excellon_obj.create_geometry()
  7725. if ret == 'fail':
  7726. log.debug("Could not create geometry for Excellon object.")
  7727. return "fail"
  7728. for tool in excellon_obj.tools:
  7729. if excellon_obj.tools[tool]['solid_geometry']:
  7730. return
  7731. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7732. return "fail"
  7733. with self.proc_container.new(_("Opening Excellon.")):
  7734. # Object name
  7735. name = outname or filename.split('/')[-1].split('\\')[-1]
  7736. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7737. if ret_val == 'fail':
  7738. if from_tcl:
  7739. filename = self.defaults['global_tcl_path'] + '/' + name
  7740. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7741. if ret_val == 'fail':
  7742. self.inform.emit('[ERROR_NOTCL] %s' %
  7743. _('Open Excellon file failed. Probable not an Excellon file.'))
  7744. return
  7745. # Register recent file
  7746. self.file_opened.emit("excellon", filename)
  7747. # GUI feedback
  7748. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7749. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7750. """
  7751. Opens a G-gcode file, parses it and creates a new object for
  7752. it in the program. Thread-safe.
  7753. :param filename: G-code file filename
  7754. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7755. :param force_parsing:
  7756. :param plot: If True plot the object on canvas
  7757. :param from_tcl: True if run from Tcl Shell
  7758. :return: None
  7759. """
  7760. App.log.debug("open_gcode()")
  7761. # How the object should be initialized
  7762. def obj_init(job_obj, app_obj_):
  7763. """
  7764. :param job_obj: the resulting object
  7765. :type app_obj_: App
  7766. """
  7767. assert isinstance(app_obj_, App), \
  7768. "Initializer expected App, got %s" % type(app_obj_)
  7769. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7770. try:
  7771. f = open(filename)
  7772. gcode = f.read()
  7773. f.close()
  7774. except IOError:
  7775. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7776. return "fail"
  7777. job_obj.gcode = gcode
  7778. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7779. if gcode_ret == "fail":
  7780. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7781. return "fail"
  7782. job_obj.create_geometry()
  7783. with self.proc_container.new(_("Opening G-Code.")):
  7784. # Object name
  7785. name = outname or filename.split('/')[-1].split('\\')[-1]
  7786. # New object creation and file processing
  7787. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7788. if ret_val == 'fail':
  7789. if from_tcl:
  7790. filename = self.defaults['global_tcl_path'] + '/' + name
  7791. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7792. if ret_val == 'fail':
  7793. self.inform.emit('[ERROR_NOTCL] %s' %
  7794. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7795. "Try to load it from File menu.\n "
  7796. "Attempting to create a FlatCAM CNCJob Object from "
  7797. "G-Code file failed during processing"))
  7798. return "fail"
  7799. # Register recent file
  7800. self.file_opened.emit("cncjob", filename)
  7801. # GUI feedback
  7802. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7803. def open_hpgl2(self, filename, outname=None):
  7804. """
  7805. Opens a HPGL2 file, parses it and creates a new object for
  7806. it in the program. Thread-safe.
  7807. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7808. :param filename: HPGL2 file filename
  7809. :return: None
  7810. """
  7811. filename = filename
  7812. # How the object should be initialized
  7813. def obj_init(geo_obj, app_obj):
  7814. assert isinstance(geo_obj, GeometryObject), \
  7815. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7816. # Opening the file happens here
  7817. obj = HPGL2(self)
  7818. try:
  7819. HPGL2.parse_file(obj, filename)
  7820. except IOError:
  7821. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7822. return "fail"
  7823. except ParseError as err:
  7824. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7825. app_obj.log.error(str(err))
  7826. return "fail"
  7827. except Exception as e:
  7828. log.debug("App.open_hpgl2() --> %s" % str(e))
  7829. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7830. msg += traceback.format_exc()
  7831. app_obj.inform.emit(msg)
  7832. return "fail"
  7833. geo_obj.multigeo = True
  7834. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7835. geo_obj.tools = deepcopy(obj.tools)
  7836. geo_obj.source_file = deepcopy(obj.source_file)
  7837. del obj
  7838. if not geo_obj.solid_geometry:
  7839. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7840. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7841. return "fail"
  7842. App.log.debug("open_hpgl2()")
  7843. with self.proc_container.new(_("Opening HPGL2")) as proc:
  7844. # Object name
  7845. name = outname or filename.split('/')[-1].split('\\')[-1]
  7846. # # ## Object creation # ##
  7847. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7848. if ret == 'fail':
  7849. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7850. return 'fail'
  7851. # Register recent file
  7852. self.file_opened.emit("geometry", filename)
  7853. # GUI feedback
  7854. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7855. def open_script(self, filename, outname=None, silent=False):
  7856. """
  7857. Opens a Script file, parses it and creates a new object for
  7858. it in the program. Thread-safe.
  7859. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7860. :param filename: Script file filename
  7861. :return: None
  7862. """
  7863. App.log.debug("open_script()")
  7864. with self.proc_container.new(_("Opening TCL Script...")):
  7865. try:
  7866. with open(filename, "r") as opened_script:
  7867. script_content = opened_script.readlines()
  7868. script_content = ''.join(script_content)
  7869. if silent is False:
  7870. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7871. except Exception as e:
  7872. log.debug("App.open_script() -> %s" % str(e))
  7873. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  7874. return
  7875. # Object name
  7876. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7877. # New object creation and file processing
  7878. self.on_filenewscript(name=script_name, text=script_content)
  7879. # Register recent file
  7880. self.file_opened.emit("script", filename)
  7881. # GUI feedback
  7882. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7883. def open_config_file(self, filename, run_from_arg=None):
  7884. """
  7885. Loads a config file from the specified file.
  7886. :param filename: Name of the file from which to load.
  7887. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7888. :return: None
  7889. """
  7890. App.log.debug("Opening config file: " + filename)
  7891. if run_from_arg:
  7892. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7893. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7894. _("Opening FlatCAM Config file.")),
  7895. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7896. color=QtGui.QColor("gray"))
  7897. # # add the tab if it was closed
  7898. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7899. # # first clear previous text in text editor (if any)
  7900. # self.ui.text_editor_tab.code_editor.clear()
  7901. #
  7902. # # Switch plot_area to CNCJob tab
  7903. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7904. # close the Code editor if already open
  7905. if self.toggle_codeeditor:
  7906. self.on_toggle_code_editor()
  7907. self.on_toggle_code_editor()
  7908. try:
  7909. if filename:
  7910. f = QtCore.QFile(filename)
  7911. if f.open(QtCore.QIODevice.ReadOnly):
  7912. stream = QtCore.QTextStream(f)
  7913. code_edited = stream.readAll()
  7914. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7915. f.close()
  7916. except IOError:
  7917. App.log.error("Failed to open config file: %s" % filename)
  7918. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7919. (_("Failed to open config file"), filename))
  7920. return
  7921. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7922. """
  7923. Loads a project from the specified file.
  7924. 1) Loads and parses file
  7925. 2) Registers the file as recently opened.
  7926. 3) Calls on_file_new()
  7927. 4) Updates options
  7928. 5) Calls new_object() with the object's from_dict() as init method.
  7929. 6) Calls plot_all() if plot=True
  7930. :param filename: Name of the file from which to load.
  7931. :param run_from_arg: True if run for arguments
  7932. :param plot: If True plot all objects in the project
  7933. :param cli: Run from command line
  7934. :param from_tcl: True if run from Tcl Sehll
  7935. :return: None
  7936. """
  7937. App.log.debug("Opening project: " + filename)
  7938. # block autosaving while a project is loaded
  7939. self.block_autosave = True
  7940. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7941. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7942. if cli is None:
  7943. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7944. if run_from_arg:
  7945. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7946. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7947. _("Opening FlatCAM Project file.")),
  7948. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7949. color=QtGui.QColor("gray"))
  7950. # Open and parse an uncompressed Project file
  7951. try:
  7952. f = open(filename, 'r')
  7953. except IOError:
  7954. if from_tcl:
  7955. name = filename.split('/')[-1].split('\\')[-1]
  7956. filename = self.defaults['global_tcl_path'] + '/' + name
  7957. try:
  7958. f = open(filename, 'r')
  7959. except IOError:
  7960. log.error("Failed to open project file: %s" % filename)
  7961. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7962. return
  7963. else:
  7964. log.error("Failed to open project file: %s" % filename)
  7965. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7966. return
  7967. try:
  7968. d = json.load(f, object_hook=dict2obj)
  7969. except Exception as e:
  7970. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7971. (filename, str(e)))
  7972. f.close()
  7973. # Open and parse a compressed Project file
  7974. try:
  7975. with lzma.open(filename) as f:
  7976. file_content = f.read().decode('utf-8')
  7977. d = json.loads(file_content, object_hook=dict2obj)
  7978. except Exception as e:
  7979. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7980. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7981. (_("Failed to open project file"), filename))
  7982. return
  7983. # Clear the current project
  7984. # # NOT THREAD SAFE # ##
  7985. if run_from_arg is True:
  7986. pass
  7987. elif cli is True:
  7988. self.delete_selection_shape()
  7989. else:
  7990. self.on_file_new()
  7991. # Project options
  7992. self.options.update(d['options'])
  7993. self.project_filename = filename
  7994. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7995. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7996. if cli is None:
  7997. self.set_screen_units(self.options["units"])
  7998. # Re create objects
  7999. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8000. for obj in d['objs']:
  8001. try:
  8002. def obj_init(obj_inst, app_inst):
  8003. obj_inst.from_dict(obj)
  8004. App.log.debug("Recreating from opened project an %s object: %s" %
  8005. (obj['kind'].capitalize(), obj['options']['name']))
  8006. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8007. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8008. if cli is None:
  8009. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8010. obj['kind'].upper(),
  8011. obj['options']['name']
  8012. )
  8013. )
  8014. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8015. except Exception as e:
  8016. print('App.open_project() --> ' + str(e))
  8017. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8018. self.should_we_save = False
  8019. self.file_opened.emit("project", filename)
  8020. # restore autosaving after a project was loaded
  8021. self.block_autosave = False
  8022. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8023. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8024. if cli is None:
  8025. self.set_ui_title(name=self.project_filename)
  8026. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8027. def plot_all(self, fit_view=True, use_thread=True):
  8028. """
  8029. Re-generates all plots from all objects.
  8030. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8031. :param use_thread: if True will use threading for plotting the objects
  8032. :return: None
  8033. """
  8034. self.log.debug("Plot_all()")
  8035. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8036. for plot_obj in self.collection.get_list():
  8037. def worker_task(obj):
  8038. with self.proc_container.new("Plotting"):
  8039. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8040. if fit_view is True:
  8041. self.object_plotted.emit(obj)
  8042. if use_thread is True:
  8043. # Send to worker
  8044. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8045. else:
  8046. worker_task(plot_obj)
  8047. def register_folder(self, filename):
  8048. """
  8049. Register the last folder used by the app to open something
  8050. :param filename: the last folder is extracted from the filename
  8051. :return: None
  8052. """
  8053. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8054. def register_save_folder(self, filename):
  8055. """
  8056. Register the last folder used by the app to save something
  8057. :param filename: the last folder is extracted from the filename
  8058. :return: None
  8059. """
  8060. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8061. # def set_progress_bar(self, percentage, text=""):
  8062. # """
  8063. # Set a progress bar to a value (percentage)
  8064. #
  8065. # :param percentage: Value set to the progressbar
  8066. # :param text: Not used
  8067. # :return: None
  8068. # """
  8069. # self.ui.progress_bar.setValue(int(percentage))
  8070. def setup_recent_items(self):
  8071. """
  8072. Setup a dictionary with the recent files accessed, organized by type
  8073. :return:
  8074. """
  8075. icons = {
  8076. "gerber": self.resource_location + "/flatcam_icon16.png",
  8077. "excellon": self.resource_location + "/drill16.png",
  8078. 'geometry': self.resource_location + "/geometry16.png",
  8079. "cncjob": self.resource_location + "/cnc16.png",
  8080. "script": self.resource_location + "/script_new24.png",
  8081. "document": self.resource_location + "/notes16_1.png",
  8082. "project": self.resource_location + "/project16.png",
  8083. "svg": self.resource_location + "/geometry16.png",
  8084. "dxf": self.resource_location + "/dxf16.png",
  8085. "pdf": self.resource_location + "/pdf32.png",
  8086. "image": self.resource_location + "/image16.png"
  8087. }
  8088. try:
  8089. image_opener = self.image_tool.import_image
  8090. except AttributeError:
  8091. image_opener = None
  8092. openers = {
  8093. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8094. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8095. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8096. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8097. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8098. "document": None,
  8099. 'project': self.open_project,
  8100. 'svg': self.import_svg,
  8101. 'dxf': self.import_dxf,
  8102. 'image': image_opener,
  8103. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8104. }
  8105. # Open recent file for files
  8106. try:
  8107. f = open(self.data_path + '/recent.json')
  8108. except IOError:
  8109. App.log.error("Failed to load recent item list.")
  8110. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8111. return
  8112. try:
  8113. self.recent = json.load(f)
  8114. except json.errors.JSONDecodeError:
  8115. App.log.error("Failed to parse recent item list.")
  8116. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8117. f.close()
  8118. return
  8119. f.close()
  8120. # Open recent file for projects
  8121. try:
  8122. fp = open(self.data_path + '/recent_projects.json')
  8123. except IOError:
  8124. App.log.error("Failed to load recent project item list.")
  8125. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8126. return
  8127. try:
  8128. self.recent_projects = json.load(fp)
  8129. except json.errors.JSONDecodeError:
  8130. App.log.error("Failed to parse recent project item list.")
  8131. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8132. fp.close()
  8133. return
  8134. fp.close()
  8135. # Closure needed to create callbacks in a loop.
  8136. # Otherwise late binding occurs.
  8137. def make_callback(func, fname):
  8138. def opener():
  8139. func(fname)
  8140. return opener
  8141. def reset_recent_files():
  8142. # Reset menu
  8143. self.ui.recent.clear()
  8144. self.recent = []
  8145. try:
  8146. ff = open(self.data_path + '/recent.json', 'w')
  8147. except IOError:
  8148. App.log.error("Failed to open recent items file for writing.")
  8149. return
  8150. json.dump(self.recent, ff)
  8151. def reset_recent_projects():
  8152. # Reset menu
  8153. self.ui.recent_projects.clear()
  8154. self.recent_projects = []
  8155. try:
  8156. frp = open(self.data_path + '/recent_projects.json', 'w')
  8157. except IOError:
  8158. App.log.error("Failed to open recent projects items file for writing.")
  8159. return
  8160. json.dump(self.recent, frp)
  8161. # Reset menu
  8162. self.ui.recent.clear()
  8163. self.ui.recent_projects.clear()
  8164. # Create menu items for projects
  8165. for recent in self.recent_projects:
  8166. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8167. if recent['kind'] == 'project':
  8168. try:
  8169. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8170. # Attach callback
  8171. o = make_callback(openers[recent["kind"]], recent['filename'])
  8172. action.triggered.connect(o)
  8173. self.ui.recent_projects.addAction(action)
  8174. except KeyError:
  8175. App.log.error("Unsupported file type: %s" % recent["kind"])
  8176. # Last action in Recent Files menu is one that Clear the content
  8177. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8178. (_("Clear Recent projects")), self)
  8179. clear_action_proj.triggered.connect(reset_recent_projects)
  8180. self.ui.recent_projects.addSeparator()
  8181. self.ui.recent_projects.addAction(clear_action_proj)
  8182. # Create menu items for files
  8183. for recent in self.recent:
  8184. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8185. if recent['kind'] != 'project':
  8186. try:
  8187. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8188. # Attach callback
  8189. o = make_callback(openers[recent["kind"]], recent['filename'])
  8190. action.triggered.connect(o)
  8191. self.ui.recent.addAction(action)
  8192. except KeyError:
  8193. App.log.error("Unsupported file type: %s" % recent["kind"])
  8194. # Last action in Recent Files menu is one that Clear the content
  8195. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8196. (_("Clear Recent files")), self)
  8197. clear_action.triggered.connect(reset_recent_files)
  8198. self.ui.recent.addSeparator()
  8199. self.ui.recent.addAction(clear_action)
  8200. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8201. # self.ui.menufilerecent.set_submenu(recent_menu)
  8202. # recent_menu.show_all()
  8203. # self.ui.recent.show()
  8204. self.log.debug("Recent items list has been populated.")
  8205. def setup_component_editor(self):
  8206. """
  8207. Default text for the Selected tab when is not taken by the Object UI.
  8208. :return:
  8209. """
  8210. # label = QtWidgets.QLabel("Choose an item from Project")
  8211. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8212. sel_title = QtWidgets.QTextEdit(
  8213. _('<b>Shortcut Key List</b>'))
  8214. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8215. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8216. f_settings = QSettings("Open Source", "FlatCAM")
  8217. if f_settings.contains("notebook_font_size"):
  8218. fsize = f_settings.value('notebook_font_size', type=int)
  8219. else:
  8220. fsize = 12
  8221. tsize = fsize + int(fsize / 2)
  8222. # selected_text = (_('''
  8223. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8224. # </p>
  8225. #
  8226. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8227. # The normal flow when working in FlatCAM is the following:</span></p>
  8228. #
  8229. # <ol>
  8230. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8231. # file into
  8232. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8233. # even dragging and dropping the files on the GUI.<br />
  8234. # <br />
  8235. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8236. # drop of the
  8237. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8238. # &nbsp;</li>
  8239. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8240. # and then
  8241. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8242. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8243. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8244. # <br />
  8245. # If the selection of the object is done on the canvas by single click instead, and the
  8246. # <strong>SELECTED TAB</strong>
  8247. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8248. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8249. # it even if it was out of focus.<br />
  8250. # <br />
  8251. # You can change the parameters in this screen and the flow direction is like this:<br />
  8252. # <br />
  8253. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8254. # <strong> Geometry Object
  8255. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8256. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8257. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8258. # </ol>
  8259. #
  8260. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8261. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8262. # <strong>F3</strong>.</span></p>
  8263. #
  8264. # ''').format(fsize=fsize, tsize=tsize))
  8265. selected_text = '''
  8266. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8267. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8268. {s1}</span></p>
  8269. <ol>
  8270. <li><span style="font-size:{fsize}px">{s2}<br />
  8271. <br />
  8272. {s3}</span><br />
  8273. &nbsp;</li>
  8274. <li><span style="font-size:{fsize}px">{s4}<br />
  8275. &nbsp;</li>
  8276. <br />
  8277. <li><span style="font-size:{fsize}px">{s5}<br />
  8278. &nbsp;</li>
  8279. <br />
  8280. <li><span style="font-size:{fsize}px">{s6}<br />
  8281. <br />
  8282. {s7}</span></li>
  8283. </ol>
  8284. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8285. '''.format(
  8286. title=_("Selected Tab - Choose an Item from Project Tab"),
  8287. subtitle=_("Details"),
  8288. s1=_("The normal flow when working in FlatCAM is the following:"),
  8289. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8290. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8291. "files on the GUI."),
  8292. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8293. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8294. "actions offered within the app."),
  8295. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8296. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8297. "SELECTED TAB will be updated with the object properties according to its kind: "
  8298. "Gerber, Excellon, Geometry or CNCJob object."),
  8299. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8300. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8301. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8302. "the SELECTED TAB and populate it even if it was out of focus."),
  8303. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8304. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8305. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8306. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8307. "(again, done in SELECTED TAB) --> Save GCode."),
  8308. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8309. "or through its own key shortcut: <b>F3</b>."),
  8310. tsize=tsize,
  8311. fsize=fsize
  8312. )
  8313. sel_title.setText(selected_text)
  8314. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8315. self.ui.selected_scroll_area.setWidget(sel_title)
  8316. def setup_obj_classes(self):
  8317. """
  8318. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8319. class.
  8320. :return: None
  8321. """
  8322. FlatCAMObj.app = self
  8323. ObjectCollection.app = self
  8324. Gerber.app = self
  8325. Excellon.app = self
  8326. Geometry.app = self
  8327. CNCjob.app = self
  8328. FCProcess.app = self
  8329. FCProcessContainer.app = self
  8330. OptionsGroupUI.app = self
  8331. def version_check(self):
  8332. """
  8333. Checks for the latest version of the program. Alerts the
  8334. user if theirs is outdated. This method is meant to be run
  8335. in a separate thread.
  8336. :return: None
  8337. """
  8338. self.log.debug("version_check()")
  8339. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8340. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8341. App.version_url,
  8342. str(self.defaults['global_serial']),
  8343. str(self.version),
  8344. str(self.os),
  8345. urllib.parse.urlencode(self.defaults["global_stats"])
  8346. )
  8347. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8348. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8349. # urllib.parse.urlencode(self.defaults["global_stats"])
  8350. else:
  8351. # no_stats dict; just so it won't break things on website
  8352. no_ststs_dict = {}
  8353. no_ststs_dict["global_ststs"] = {}
  8354. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) +\
  8355. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8356. App.log.debug("Checking for updates @ %s" % full_url)
  8357. # ## Get the data
  8358. try:
  8359. f = urllib.request.urlopen(full_url)
  8360. except Exception:
  8361. # App.log.warning("Failed checking for latest version. Could not connect.")
  8362. self.log.warning("Failed checking for latest version. Could not connect.")
  8363. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8364. return
  8365. try:
  8366. data = json.load(f)
  8367. except Exception as e:
  8368. App.log.error("Could not parse information about latest version.")
  8369. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8370. App.log.debug("json.load(): %s" % str(e))
  8371. f.close()
  8372. return
  8373. f.close()
  8374. # ## Latest version?
  8375. if self.version >= data["version"]:
  8376. App.log.debug("FlatCAM is up to date!")
  8377. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8378. return
  8379. App.log.debug("Newer version available.")
  8380. self.message.emit(
  8381. _("Newer Version Available"),
  8382. '%s<br><br>><b>%s</b><br>%s' % (
  8383. _("There is a newer version of FlatCAM available for download:"),
  8384. str(data["name"]),
  8385. str(data["message"])
  8386. ),
  8387. _("info")
  8388. )
  8389. def on_plotcanvas_setup(self, container=None):
  8390. """
  8391. This is doing the setup for the plot area (canvas).
  8392. :param container: QT Widget where to install the canvas
  8393. :return: None
  8394. """
  8395. if container:
  8396. plot_container = container
  8397. else:
  8398. plot_container = self.ui.right_layout
  8399. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8400. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8401. self.is_legacy = True
  8402. self.defaults["global_graphic_engine"] = "2D"
  8403. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8404. else:
  8405. try:
  8406. self.plotcanvas = PlotCanvas(plot_container, self)
  8407. except Exception as er:
  8408. msg_txt = traceback.format_exc()
  8409. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8410. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8411. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8412. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8413. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8414. msg += msg_txt
  8415. self.inform.emit(msg)
  8416. return 'fail'
  8417. # So it can receive key presses
  8418. self.plotcanvas.native.setFocus()
  8419. if self.is_legacy is False:
  8420. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8421. # Set the mouse button for panning
  8422. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8423. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8424. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8425. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8426. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8427. # Keys over plot enabled
  8428. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8429. if self.defaults['global_cursor_type'] == 'small':
  8430. self.app_cursor = self.plotcanvas.new_cursor()
  8431. else:
  8432. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8433. if self.ui.grid_snap_btn.isChecked():
  8434. self.app_cursor.enabled = True
  8435. else:
  8436. self.app_cursor.enabled = False
  8437. if self.is_legacy is False:
  8438. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8439. else:
  8440. # will use the default Matplotlib axes
  8441. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8442. def on_zoom_fit(self, event):
  8443. """
  8444. Callback for zoom-fit request. This can be either from the corresponding
  8445. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8446. with axes limits from the geometry bounds of all objects.
  8447. :param event: Ignored.
  8448. :return: None
  8449. """
  8450. if self.is_legacy is False:
  8451. self.plotcanvas.fit_view()
  8452. else:
  8453. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8454. width = xmax - xmin
  8455. height = ymax - ymin
  8456. xmin -= 0.05 * width
  8457. xmax += 0.05 * width
  8458. ymin -= 0.05 * height
  8459. ymax += 0.05 * height
  8460. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8461. def on_zoom_in(self):
  8462. """
  8463. Callback for zoom-in request.
  8464. :return:
  8465. """
  8466. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8467. def on_zoom_out(self):
  8468. """
  8469. Callback for zoom-out request.
  8470. :return:
  8471. """
  8472. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8473. def disable_all_plots(self):
  8474. self.defaults.report_usage("disable_all_plots()")
  8475. self.disable_plots(self.collection.get_list())
  8476. self.inform.emit('[success] %s' %
  8477. _("All plots disabled."))
  8478. def disable_other_plots(self):
  8479. self.defaults.report_usage("disable_other_plots()")
  8480. self.disable_plots(self.collection.get_non_selected())
  8481. self.inform.emit('[success] %s' %
  8482. _("All non selected plots disabled."))
  8483. def enable_all_plots(self):
  8484. self.defaults.report_usage("enable_all_plots()")
  8485. self.enable_plots(self.collection.get_list())
  8486. self.inform.emit('[success] %s' %
  8487. _("All plots enabled."))
  8488. def on_enable_sel_plots(self):
  8489. log.debug("App.on_enable_sel_plot()")
  8490. object_list = self.collection.get_selected()
  8491. self.enable_plots(objects=object_list)
  8492. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8493. def on_disable_sel_plots(self):
  8494. log.debug("App.on_disable_sel_plot()")
  8495. # self.inform.emit(_("Disabling plots ..."))
  8496. object_list = self.collection.get_selected()
  8497. self.disable_plots(objects=object_list)
  8498. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8499. def enable_plots(self, objects):
  8500. """
  8501. Enable plots
  8502. :param objects: list of Objects to be enabled
  8503. :return:
  8504. """
  8505. log.debug("Enabling plots ...")
  8506. # self.inform.emit(_("Working ..."))
  8507. for obj in objects:
  8508. if obj.options['plot'] is False:
  8509. obj.options.set_change_callback(lambda x: None)
  8510. obj.options['plot'] = True
  8511. try:
  8512. # only the Gerber obj has on_plot_cb_click() method
  8513. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8514. # disable this cb while disconnected,
  8515. # in case the operation takes time the user is not allowed to change it
  8516. obj.ui.plot_cb.setDisabled(True)
  8517. except AttributeError:
  8518. pass
  8519. obj.set_form_item("plot")
  8520. try:
  8521. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8522. obj.ui.plot_cb.setDisabled(False)
  8523. except AttributeError:
  8524. pass
  8525. obj.options.set_change_callback(obj.on_options_change)
  8526. def worker_task(objs):
  8527. with self.proc_container.new(_("Enabling plots ...")):
  8528. for plot_obj in objs:
  8529. # obj.options['plot'] = True
  8530. if isinstance(plot_obj, CNCJobObject):
  8531. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8532. else:
  8533. plot_obj.plot(visible=True)
  8534. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8535. # self.plots_updated.emit()
  8536. def disable_plots(self, objects):
  8537. """
  8538. Disables plots
  8539. :param objects: list of Objects to be disabled
  8540. :return:
  8541. """
  8542. # if no objects selected then do nothing
  8543. if not self.collection.get_selected():
  8544. return
  8545. log.debug("Disabling plots ...")
  8546. # self.inform.emit(_("Working ..."))
  8547. for obj in objects:
  8548. if obj.options['plot'] is True:
  8549. obj.options.set_change_callback(lambda x: None)
  8550. obj.options['plot'] = False
  8551. try:
  8552. # only the Gerber obj has on_plot_cb_click() method
  8553. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8554. obj.ui.plot_cb.setDisabled(True)
  8555. except AttributeError:
  8556. pass
  8557. obj.set_form_item("plot")
  8558. try:
  8559. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8560. obj.ui.plot_cb.setDisabled(False)
  8561. except AttributeError:
  8562. pass
  8563. obj.options.set_change_callback(obj.on_options_change)
  8564. try:
  8565. self.delete_selection_shape()
  8566. except Exception as e:
  8567. log.debug("App.disable_plots() --> %s" % str(e))
  8568. # self.plots_updated.emit()
  8569. def worker_task(objs):
  8570. with self.proc_container.new(_("Disabling plots ...")):
  8571. for plot_obj in objs:
  8572. # obj.options['plot'] = True
  8573. if isinstance(plot_obj, CNCJobObject):
  8574. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8575. else:
  8576. plot_obj.plot(visible=False)
  8577. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8578. def toggle_plots(self, objects):
  8579. """
  8580. Toggle plots visibility
  8581. :param objects: list of Objects for which to be toggled the visibility
  8582. :return: None
  8583. """
  8584. # if no objects selected then do nothing
  8585. if not self.collection.get_selected():
  8586. return
  8587. log.debug("Toggling plots ...")
  8588. self.inform.emit(_("Working ..."))
  8589. for obj in objects:
  8590. if obj.options['plot'] is False:
  8591. obj.options['plot'] = True
  8592. else:
  8593. obj.options['plot'] = False
  8594. self.plots_updated.emit()
  8595. def clear_plots(self):
  8596. """
  8597. Clear the plots
  8598. :return: None
  8599. """
  8600. objects = self.collection.get_list()
  8601. for obj in objects:
  8602. obj.clear(obj == objects[-1])
  8603. # Clear pool to free memory
  8604. self.clear_pool()
  8605. def on_set_color_action_triggered(self):
  8606. """
  8607. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8608. :return:
  8609. """
  8610. new_color = self.defaults['gerber_plot_fill']
  8611. clicked_action = self.sender()
  8612. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8613. act_name = clicked_action.text()
  8614. sel_obj_list = self.collection.get_selected()
  8615. if not sel_obj_list:
  8616. return
  8617. # a default value, I just chose this one
  8618. alpha_level = 'BF'
  8619. for sel_obj in sel_obj_list:
  8620. if sel_obj.kind == 'excellon':
  8621. alpha_level = str(hex(
  8622. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8623. elif sel_obj.kind == 'gerber':
  8624. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8625. elif sel_obj.kind == 'geometry':
  8626. alpha_level = 'FF'
  8627. else:
  8628. log.debug(
  8629. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8630. continue
  8631. sel_obj.alpha_level = alpha_level
  8632. if act_name == _('Red'):
  8633. new_color = '#FF0000' + alpha_level
  8634. if act_name == _('Blue'):
  8635. new_color = '#0000FF' + alpha_level
  8636. if act_name == _('Yellow'):
  8637. new_color = '#FFDF00' + alpha_level
  8638. if act_name == _('Green'):
  8639. new_color = '#00FF00' + alpha_level
  8640. if act_name == _('Purple'):
  8641. new_color = '#FF00FF' + alpha_level
  8642. if act_name == _('Brown'):
  8643. new_color = '#A52A2A' + alpha_level
  8644. if act_name == _('White'):
  8645. new_color = '#FFFFFF' + alpha_level
  8646. if act_name == _('Black'):
  8647. new_color = '#000000' + alpha_level
  8648. if act_name == _('Custom'):
  8649. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8650. c_dialog = QtWidgets.QColorDialog()
  8651. plot_fill_color = c_dialog.getColor(initial=new_color)
  8652. if plot_fill_color.isValid() is False:
  8653. return
  8654. new_color = str(plot_fill_color.name()) + alpha_level
  8655. if act_name == _("Default"):
  8656. for sel_obj in sel_obj_list:
  8657. if sel_obj.kind == 'excellon':
  8658. new_color = self.defaults['excellon_plot_fill']
  8659. new_line_color = self.defaults['excellon_plot_line']
  8660. elif sel_obj.kind == 'gerber':
  8661. new_color = self.defaults['gerber_plot_fill']
  8662. new_line_color = self.defaults['gerber_plot_line']
  8663. elif sel_obj.kind == 'geometry':
  8664. new_color = self.defaults['geometry_plot_line']
  8665. new_line_color = self.defaults['geometry_plot_line']
  8666. else:
  8667. log.debug(
  8668. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8669. continue
  8670. sel_obj.fill_color = new_color
  8671. sel_obj.outline_color = new_line_color
  8672. sel_obj.shapes.redraw(
  8673. update_colors=(new_color, new_line_color)
  8674. )
  8675. return
  8676. if act_name == _("Opacity"):
  8677. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8678. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8679. if ok_button:
  8680. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8681. for sel_obj in sel_obj_list:
  8682. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8683. sel_obj.shapes.redraw(
  8684. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8685. )
  8686. return
  8687. new_line_color = color_variant(new_color[:7], 0.7)
  8688. if act_name == _("White"):
  8689. new_line_color = color_variant("#dedede", 0.7)
  8690. for sel_obj in sel_obj_list:
  8691. sel_obj.fill_color = new_color
  8692. sel_obj.outline_color = new_line_color
  8693. sel_obj.shapes.redraw(
  8694. update_colors=(new_color, new_line_color)
  8695. )
  8696. def on_grid_snap_triggered(self, state):
  8697. """
  8698. :param state: A parameter with the state of the grid, boolean
  8699. :return:
  8700. """
  8701. if state:
  8702. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  8703. else:
  8704. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  8705. self.ui.snap_infobar_label.clicked_state = state
  8706. def on_grid_icon_snap_clicked(self):
  8707. """
  8708. Slot called by clicking a GUI element, in this case a FCLabel
  8709. :return:
  8710. """
  8711. if isinstance(self.sender(), FCLabel):
  8712. self.ui.grid_snap_btn.trigger()
  8713. def generate_cnc_job(self, objects):
  8714. """
  8715. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8716. :param objects: Selected objects in the Project Tab
  8717. :return:
  8718. """
  8719. self.defaults.report_usage("generate_cnc_job()")
  8720. # for obj in objects:
  8721. # obj.generatecncjob()
  8722. for obj in objects:
  8723. obj.on_generatecnc_button_click()
  8724. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8725. """
  8726. Saves the current project to the specified file.
  8727. :param filename: Name of the file in which to save.
  8728. :type filename: str
  8729. :param quit_action: if the project saving will be followed by an app quit; boolean
  8730. :param silent: if True will not display status messages
  8731. :param from_tcl True is run from Tcl Shell
  8732. :return: None
  8733. """
  8734. self.log.debug("save_project()")
  8735. self.save_in_progress = True
  8736. with self.proc_container.new(_("Saving FlatCAM Project")):
  8737. # Capture the latest changes
  8738. # Current object
  8739. try:
  8740. current_object = self.collection.get_active()
  8741. if current_object:
  8742. current_object.read_form()
  8743. except Exception as e:
  8744. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8745. pass
  8746. # Serialize the whole project
  8747. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8748. "options": self.options,
  8749. "version": self.version}
  8750. if self.defaults["global_save_compressed"] is True:
  8751. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8752. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8753. # # Write
  8754. f.write(g)
  8755. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8756. else:
  8757. # Open file
  8758. try:
  8759. f = open(filename, 'w')
  8760. except IOError:
  8761. App.log.error("Failed to open file for saving: %s", filename)
  8762. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8763. return
  8764. # Write
  8765. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8766. f.close()
  8767. # verification of the saved project
  8768. # Open and parse
  8769. try:
  8770. saved_f = open(filename, 'r')
  8771. except IOError:
  8772. if silent is False:
  8773. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8774. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8775. return
  8776. try:
  8777. saved_d = json.load(saved_f, object_hook=dict2obj)
  8778. except Exception:
  8779. if silent is False:
  8780. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8781. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8782. f.close()
  8783. return
  8784. saved_f.close()
  8785. if silent is False:
  8786. if 'version' in saved_d:
  8787. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8788. else:
  8789. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8790. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8791. tb_settings = QSettings("Open Source", "FlatCAM")
  8792. lock_state = self.ui.lock_action.isChecked()
  8793. tb_settings.setValue('toolbar_lock', lock_state)
  8794. # This will write the setting to the platform specific storage.
  8795. del tb_settings
  8796. # if quit:
  8797. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8798. # t.start()
  8799. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8800. def start_delayed_quit(self, delay, filename, should_quit=None):
  8801. """
  8802. :param delay: period of checking if project file size is more than zero; in seconds
  8803. :param filename: the name of the project file to be checked periodically for size more than zero
  8804. :param should_quit: if the task finished will be followed by an app quit; boolean
  8805. :return:
  8806. """
  8807. to_quit = should_quit
  8808. self.save_timer = QtCore.QTimer()
  8809. self.save_timer.setInterval(delay)
  8810. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8811. self.save_timer.start()
  8812. def check_project_file_size(self, filename, should_quit=None):
  8813. """
  8814. :param filename: the name of the project file to be checked periodically for size more than zero
  8815. :param should_quit: will quit the app if True; boolean
  8816. :return:
  8817. """
  8818. try:
  8819. if os.stat(filename).st_size > 0:
  8820. self.save_in_progress = False
  8821. self.save_timer.stop()
  8822. if should_quit:
  8823. self.app_quit.emit()
  8824. except Exception:
  8825. traceback.print_exc()
  8826. def save_project_auto(self):
  8827. """
  8828. Called periodically to save the project.
  8829. 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
  8830. # progress.
  8831. :return:
  8832. """
  8833. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8834. self.on_file_saveproject()
  8835. def save_project_auto_update(self):
  8836. """
  8837. Update the auto save time interval value.
  8838. :return:
  8839. """
  8840. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8841. try:
  8842. if self.autosave_timer.isActive():
  8843. self.autosave_timer.stop()
  8844. except Exception:
  8845. pass
  8846. if self.defaults['global_autosave'] is True:
  8847. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8848. self.autosave_timer.start()
  8849. def on_options_app2project(self):
  8850. """
  8851. Callback for Options->Transfer Options->App=>Project. Copies options
  8852. from application defaults to project defaults.
  8853. :return: None
  8854. """
  8855. self.defaults.report_usage("on_options_app2project")
  8856. self.preferencesUiManager.defaults_read_form()
  8857. self.options.update(self.defaults)
  8858. def toggle_shell(self):
  8859. """
  8860. Toggle shell: if is visible close it, if it is closed then open it
  8861. :return: None
  8862. """
  8863. self.defaults.report_usage("toggle_shell()")
  8864. if self.ui.shell_dock.isVisible():
  8865. self.ui.shell_dock.hide()
  8866. self.plotcanvas.native.setFocus()
  8867. else:
  8868. self.ui.shell_dock.show()
  8869. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8870. # self.shell._edit.setFocus()
  8871. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8872. # HACK - simulate a mouse click - alternative
  8873. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8874. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8875. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8876. # no_km)
  8877. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8878. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8879. # no_km)
  8880. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8881. def on_toggle_shell_from_settings(self, state):
  8882. """
  8883. Toggle shell: if is visible close it, if it is closed then open it
  8884. :return: None
  8885. """
  8886. self.defaults.report_usage("on_toggle_shell_from_settings()")
  8887. if state is True:
  8888. if not self.ui.shell_dock.isVisible():
  8889. self.ui.shell_dock.show()
  8890. else:
  8891. if self.ui.shell_dock.isVisible():
  8892. self.ui.shell_dock.hide()
  8893. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8894. """
  8895. Shows a message on the FlatCAM Shell
  8896. :param msg: Message to display.
  8897. :param show: Opens the shell.
  8898. :param error: Shows the message as an error.
  8899. :param warning: Shows the message as an warning.
  8900. :param success: Shows the message as an success.
  8901. :param selected: Indicate that something was selected on canvas
  8902. :return: None
  8903. """
  8904. if show:
  8905. self.ui.shell_dock.show()
  8906. try:
  8907. if error:
  8908. self.shell.append_error(msg + "\n")
  8909. elif warning:
  8910. self.shell.append_warning(msg + "\n")
  8911. elif success:
  8912. self.shell.append_success(msg + "\n")
  8913. elif selected:
  8914. self.shell.append_selected(msg + "\n")
  8915. else:
  8916. self.shell.append_output(msg + "\n")
  8917. except AttributeError:
  8918. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8919. class ArgsThread(QtCore.QObject):
  8920. open_signal = pyqtSignal(list)
  8921. start = pyqtSignal()
  8922. if sys.platform == 'win32':
  8923. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8924. else:
  8925. address = ('/tmp/testipc', 'AF_UNIX')
  8926. def __init__(self):
  8927. super(ArgsThread, self).__init__()
  8928. self.listener = None
  8929. self.thread_exit = False
  8930. self.start.connect(self.run)
  8931. def my_loop(self, address):
  8932. try:
  8933. self.listener = Listener(*address)
  8934. while self.thread_exit is False:
  8935. conn = self.listener.accept()
  8936. self.serve(conn)
  8937. except socket.error:
  8938. try:
  8939. conn = Client(*address)
  8940. conn.send(sys.argv)
  8941. conn.send('close')
  8942. # close the current instance only if there are args
  8943. if len(sys.argv) > 1:
  8944. try:
  8945. self.listener.close()
  8946. except Exception:
  8947. pass
  8948. sys.exit()
  8949. except ConnectionRefusedError:
  8950. if sys.platform == 'win32':
  8951. pass
  8952. else:
  8953. os.system('rm /tmp/testipc')
  8954. self.listener = Listener(*address)
  8955. while True:
  8956. conn = self.listener.accept()
  8957. self.serve(conn)
  8958. def serve(self, conn):
  8959. while self.thread_exit is False:
  8960. msg = conn.recv()
  8961. if msg == 'close':
  8962. break
  8963. self.open_signal.emit(msg)
  8964. conn.close()
  8965. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8966. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8967. @pyqtSlot()
  8968. def run(self):
  8969. self.my_loop(self.address)
  8970. # end of file