App_Main.py 448 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Various
  37. from Common import LoudDict
  38. from Common import color_variant
  39. from Common import ExclusionAreas
  40. from Bookmark import BookmarkManager
  41. from AppDatabase import ToolsDB2
  42. from vispy.gloo.util import _screenshot
  43. from vispy.io import write_png
  44. # FlatCAM defaults (preferences)
  45. from defaults import FlatCAMDefaults
  46. # FlatCAM Objects
  47. from AppGUI.preferences.OptionsGroupUI import OptionsGroupUI
  48. from AppGUI.preferences.PreferencesUIManager import PreferencesUIManager
  49. from AppObjects.ObjectCollection import *
  50. from AppObjects.FlatCAMObj import FlatCAMObj
  51. from AppObjects.AppObject import AppObject
  52. # FlatCAM Parsing files
  53. from AppParsers.ParseExcellon import Excellon
  54. from AppParsers.ParseGerber import Gerber
  55. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  56. # FlatCAM AppGUI
  57. from AppGUI.PlotCanvas import *
  58. from AppGUI.PlotCanvasLegacy import *
  59. from AppGUI.MainGUI import *
  60. from AppGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  61. # FlatCAM Pre-processors
  62. from AppPreProcessor import load_preprocessors
  63. # FlatCAM AppEditors
  64. from AppEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  65. from AppEditors.FlatCAMExcEditor import FlatCAMExcEditor
  66. from AppEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  67. from AppEditors.FlatCAMTextEditor import TextEditor
  68. from AppParsers.ParseHPGL2 import HPGL2
  69. # FlatCAM Workers
  70. from AppProcess import *
  71. from AppWorkerStack import WorkerStack
  72. # FlatCAM Tools
  73. from AppTools import *
  74. # FlatCAM Translation
  75. import gettext
  76. import AppTranslation as fcTranslate
  77. import builtins
  78. if sys.platform == 'win32':
  79. import winreg
  80. from win32comext.shell import shell, shellcon
  81. fcTranslate.apply_language('strings')
  82. if '_' not in builtins.__dict__:
  83. _ = gettext.gettext
  84. class App(QtCore.QObject):
  85. """
  86. The main application class. The constructor starts the GUI and all other classes used by the program.
  87. """
  88. # ###############################################################################################################
  89. # ########################################## App ################################################################
  90. # ###############################################################################################################
  91. # ###############################################################################################################
  92. # ######################################### LOGGING #############################################################
  93. # ###############################################################################################################
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ###############################################################################################################
  102. # #################################### Get Cmd Line Options #####################################################
  103. # ###############################################################################################################
  104. cmd_line_shellfile = ''
  105. cmd_line_shellvar = ''
  106. cmd_line_headless = None
  107. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  108. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  109. "FlatCam.py --headless=1"
  110. try:
  111. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  112. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  113. "shellvar=",
  114. "headless=",
  115. "multiprocessing-fork="])
  116. except getopt.GetoptError:
  117. print(cmd_line_help)
  118. sys.exit(2)
  119. for opt, arg in cmd_line_options:
  120. if opt == '-h':
  121. print(cmd_line_help)
  122. sys.exit()
  123. elif opt == '--shellfile':
  124. cmd_line_shellfile = arg
  125. elif opt == '--shellvar':
  126. cmd_line_shellvar = arg
  127. elif opt == '--headless':
  128. try:
  129. cmd_line_headless = eval(arg)
  130. except NameError:
  131. pass
  132. # ###############################################################################################################
  133. # ################################### Version and VERSION DATE ##################################################
  134. # ###############################################################################################################
  135. version = 8.993
  136. version_date = "2020/08/01"
  137. beta = True
  138. engine = '3D'
  139. # current date now
  140. date = str(datetime.today()).rpartition('.')[0]
  141. date = ''.join(c for c in date if c not in ':-')
  142. date = date.replace(' ', '_')
  143. # ###############################################################################################################
  144. # ############################################ URLS's ###########################################################
  145. # ###############################################################################################################
  146. # URL for update checks and statistics
  147. version_url = "http://flatcam.org/version"
  148. # App URL
  149. app_url = "http://flatcam.org"
  150. # Manual URL
  151. manual_url = "http://flatcam.org/manual/index.html"
  152. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  153. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  154. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  155. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  156. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  157. # this variable will hold the project status
  158. # if True it will mean that the project was modified and not saved
  159. should_we_save = False
  160. # flag is True if saving action has been triggered
  161. save_in_progress = False
  162. # ###############################################################################################################
  163. # ####################################### APP Signals ######################################################
  164. # ###############################################################################################################
  165. # Inform the user
  166. # Handled by:
  167. # * App.info() --> Print on the status bar
  168. inform = QtCore.pyqtSignal([str], [str, bool])
  169. app_quit = QtCore.pyqtSignal()
  170. # General purpose background task
  171. worker_task = QtCore.pyqtSignal(dict)
  172. # File opened
  173. # Handled by:
  174. # * register_folder()
  175. # * register_recent()
  176. # Note: Setting the parameters to unicode does not seem
  177. # to have an effect. Then are received as Qstring
  178. # anyway.
  179. # File type and filename
  180. file_opened = QtCore.pyqtSignal(str, str)
  181. # File type and filename
  182. file_saved = QtCore.pyqtSignal(str, str)
  183. # Percentage of progress
  184. progress = QtCore.pyqtSignal(int)
  185. # Emitted when a new object has been added or deleted from/to the collection
  186. object_status_changed = QtCore.pyqtSignal(object, str, str)
  187. message = QtCore.pyqtSignal(str, str, str)
  188. # Emmited when shell command is finished(one command only)
  189. shell_command_finished = QtCore.pyqtSignal(object)
  190. # Emitted when multiprocess pool has been recreated
  191. pool_recreated = QtCore.pyqtSignal(object)
  192. # Emitted when an unhandled exception happens
  193. # in the worker task.
  194. thread_exception = QtCore.pyqtSignal(object)
  195. # used to signal that there are arguments for the app
  196. args_at_startup = QtCore.pyqtSignal(list)
  197. # a reusable signal to replot a list of objects
  198. # should be disconnected after use so it can be reused
  199. replot_signal = pyqtSignal(list)
  200. # signal emitted when jumping
  201. jump_signal = pyqtSignal(tuple)
  202. # signal emitted when jumping
  203. locate_signal = pyqtSignal(tuple, str)
  204. # close app signal
  205. close_app_signal = pyqtSignal()
  206. # will perform the cleanup operation after a Graceful Exit
  207. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  208. # graphic residues behind
  209. cleanup = pyqtSignal()
  210. def __init__(self, user_defaults=True):
  211. """
  212. Starts the application.
  213. :return: app
  214. :rtype: App
  215. """
  216. super().__init__()
  217. App.log.info("FlatCAM Starting...")
  218. self.main_thread = QtWidgets.QApplication.instance().thread()
  219. # ############################################################################################################
  220. # ################# Setup the listening thread for another instance launching with args ######################
  221. # ############################################################################################################
  222. if sys.platform == 'win32' or sys.platform == 'linux':
  223. # make sure the thread is stored by using a self. otherwise it's garbage collected
  224. self.th = QtCore.QThread()
  225. self.th.start(priority=QtCore.QThread.LowestPriority)
  226. self.new_launch = ArgsThread()
  227. self.new_launch.open_signal[list].connect(self.on_startup_args)
  228. self.new_launch.moveToThread(self.th)
  229. self.new_launch.start.emit()
  230. # ############################################################################################################
  231. # ########################################## OS-specific #####################################################
  232. # ############################################################################################################
  233. portable = False
  234. # Folder for user settings.
  235. if sys.platform == 'win32':
  236. if platform.architecture()[0] == '32bit':
  237. App.log.debug("Win32!")
  238. else:
  239. App.log.debug("Win64!")
  240. # #######################################################################################################
  241. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  242. # #######################################################################################################
  243. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  244. try:
  245. with open(config_file, 'r'):
  246. pass
  247. except FileNotFoundError:
  248. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  249. try:
  250. with open(config_file, 'r') as f:
  251. try:
  252. for line in f:
  253. param = str(line).replace('\n', '').rpartition('=')
  254. if param[0] == 'portable':
  255. try:
  256. portable = eval(param[2])
  257. except NameError:
  258. portable = False
  259. if param[0] == 'headless':
  260. if param[2].lower() == 'true':
  261. self.cmd_line_headless = 1
  262. else:
  263. self.cmd_line_headless = None
  264. except Exception as e:
  265. log.debug('App.__init__() -->%s' % str(e))
  266. return
  267. except FileNotFoundError as e:
  268. log.debug(str(e))
  269. pass
  270. if portable is False:
  271. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  272. else:
  273. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  274. self.os = 'windows'
  275. else: # Linux/Unix/MacOS
  276. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  277. self.os = 'unix'
  278. # ############################################################################################################
  279. # ################################# Setup folders and files ##################################################
  280. # ############################################################################################################
  281. if not os.path.exists(self.data_path):
  282. os.makedirs(self.data_path)
  283. App.log.debug('Created data folder: ' + self.data_path)
  284. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  285. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  286. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  287. if not os.path.exists(self.preprocessorpaths):
  288. os.makedirs(self.preprocessorpaths)
  289. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  290. # create geo_tools_db.FlatDB file if there is none
  291. try:
  292. f = open(self.data_path + '/geo_tools_db.FlatDB')
  293. f.close()
  294. except IOError:
  295. App.log.debug('Creating empty geo_tool_db.FlatDB')
  296. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  297. json.dump({}, f)
  298. f.close()
  299. # create current_defaults.FlatConfig file if there is none
  300. try:
  301. f = open(self.data_path + '/current_defaults.FlatConfig')
  302. f.close()
  303. except IOError:
  304. App.log.debug('Creating empty current_defaults.FlatConfig')
  305. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  306. json.dump({}, f)
  307. f.close()
  308. # Write factory_defaults.FlatConfig file to disk
  309. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  310. # create a recent files json file if there is none
  311. try:
  312. f = open(self.data_path + '/recent.json')
  313. f.close()
  314. except IOError:
  315. App.log.debug('Creating empty recent.json')
  316. f = open(self.data_path + '/recent.json', 'w')
  317. json.dump([], f)
  318. f.close()
  319. # create a recent projects json file if there is none
  320. try:
  321. fp = open(self.data_path + '/recent_projects.json')
  322. fp.close()
  323. except IOError:
  324. App.log.debug('Creating empty recent_projects.json')
  325. fp = open(self.data_path + '/recent_projects.json', 'w')
  326. json.dump([], fp)
  327. fp.close()
  328. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  329. # This will fail under cx_freeze ...
  330. self.app_home = os.path.dirname(os.path.realpath(__file__))
  331. log.debug("Application path is " + self.app_home)
  332. log.debug("Started in " + os.getcwd())
  333. # cx_freeze workaround
  334. if os.path.isfile(self.app_home):
  335. self.app_home = os.path.dirname(self.app_home)
  336. os.chdir(self.app_home)
  337. # ############################################################################################################
  338. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  339. # ############################################################################################################
  340. self.defaults = FlatCAMDefaults()
  341. self.defaults["root_folder_path"] = self.app_home
  342. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  343. if user_defaults:
  344. self.defaults.load(filename=current_defaults_path)
  345. if self.defaults['units'] == 'MM':
  346. self.decimals = int(self.defaults['decimals_metric'])
  347. else:
  348. self.decimals = int(self.defaults['decimals_inch'])
  349. if self.defaults["global_gray_icons"] is False:
  350. self.resource_location = 'assets/resources'
  351. else:
  352. self.resource_location = 'assets/resources/dark_resources'
  353. self.current_units = self.defaults['units']
  354. # ###########################################################################################################
  355. # #################################### SETUP OBJECT CLASSES #################################################
  356. # ###########################################################################################################
  357. self.setup_obj_classes()
  358. # ###########################################################################################################
  359. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  360. # ###########################################################################################################
  361. self.pool = Pool()
  362. # ###########################################################################################################
  363. # ###################################### Setting the Splash Screen ##########################################
  364. # ###########################################################################################################
  365. splash_settings = QSettings("Open Source", "FlatCAM")
  366. if splash_settings.contains("splash_screen"):
  367. show_splash = splash_settings.value("splash_screen")
  368. else:
  369. splash_settings.setValue('splash_screen', 1)
  370. # This will write the setting to the platform specific storage.
  371. del splash_settings
  372. show_splash = 1
  373. if show_splash and self.cmd_line_headless != 1:
  374. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  375. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  376. # self.splash.setMask(splash_pix.mask())
  377. # move splashscreen to the current monitor
  378. desktop = QtWidgets.QApplication.desktop()
  379. screen = desktop.screenNumber(QtGui.QCursor.pos())
  380. current_screen_center = desktop.availableGeometry(screen).center()
  381. self.splash.move(current_screen_center - self.splash.rect().center())
  382. self.splash.show()
  383. self.splash.showMessage(_("FlatCAM is initializing ..."),
  384. alignment=Qt.AlignBottom | Qt.AlignLeft,
  385. color=QtGui.QColor("gray"))
  386. else:
  387. show_splash = 0
  388. # ###########################################################################################################
  389. # ######################################### Initialize GUI ##################################################
  390. # ###########################################################################################################
  391. # FlatCAM colors used in plotting
  392. self.FC_light_green = '#BBF268BF'
  393. self.FC_dark_green = '#006E20BF'
  394. self.FC_light_blue = '#a5a5ffbf'
  395. self.FC_dark_blue = '#0000ffbf'
  396. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  397. if theme_settings.contains("theme"):
  398. theme = theme_settings.value('theme', type=str)
  399. else:
  400. theme = 'white'
  401. if self.defaults["global_cursor_color_enabled"]:
  402. self.cursor_color_3D = self.defaults["global_cursor_color"]
  403. else:
  404. if theme == 'white':
  405. self.cursor_color_3D = 'black'
  406. else:
  407. self.cursor_color_3D = 'gray'
  408. # update the defaults dict with the setting in QSetting
  409. self.defaults['global_theme'] = theme
  410. self.ui = MainGUI(self)
  411. # set FlatCAM units in the Status bar
  412. self.set_screen_units(self.defaults['units'])
  413. # ###########################################################################################################
  414. # ########################################### AUTOSAVE SETUP ################################################
  415. # ###########################################################################################################
  416. self.block_autosave = False
  417. self.autosave_timer = QtCore.QTimer(self)
  418. self.save_project_auto_update()
  419. self.autosave_timer.timeout.connect(self.save_project_auto)
  420. # ###########################################################################################################
  421. # #################################### LOAD PREPROCESSORS ###################################################
  422. # ###########################################################################################################
  423. # ----------------------------------------- WARNING --------------------------------------------------------
  424. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  425. # That's because the number of preprocessors can vary and here the comboboxes are populated
  426. # -----------------------------------------------------------------------------------------------------------
  427. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  428. # the preprocessor file
  429. self.preprocessors = load_preprocessors(self)
  430. # make sure that always the 'default' preprocessor is the first item in the dictionary
  431. if 'default' in self.preprocessors.keys():
  432. new_ppp_dict = {}
  433. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  434. default_pp = self.preprocessors.pop('default')
  435. new_ppp_dict['default'] = default_pp
  436. # then add the rest of the keys
  437. for name, val_class in self.preprocessors.items():
  438. new_ppp_dict[name] = val_class
  439. # and now put back the ordered dict with 'default' key first
  440. self.preprocessors = new_ppp_dict
  441. for name in list(self.preprocessors.keys()):
  442. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  443. if name.partition('_')[0] == 'Paste':
  444. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  445. continue
  446. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  447. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  448. if name == 'hpgl':
  449. continue
  450. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  451. # ###########################################################################################################
  452. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  453. # ###########################################################################################################
  454. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  455. inform=self.inform)
  456. self.preferencesUiManager.defaults_write_form()
  457. # When the self.defaults dictionary changes will update the Preferences GUI forms
  458. self.defaults.set_change_callback(self.on_defaults_dict_change)
  459. # ###########################################################################################################
  460. # ##################################### FIRST RUN SECTION ###################################################
  461. # ################################ It's done only once after install #####################################
  462. # ###########################################################################################################
  463. if self.defaults["first_run"] is True:
  464. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  465. initial_lay = 'minimal'
  466. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  467. # Set the combobox in Preferences to the current layout
  468. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  469. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  470. # after the first run, this object should be False
  471. self.defaults["first_run"] = False
  472. self.preferencesUiManager.save_defaults(silent=True)
  473. # ###########################################################################################################
  474. # ############################################ Data #########################################################
  475. # ###########################################################################################################
  476. self.recent = []
  477. self.recent_projects = []
  478. self.clipboard = QtWidgets.QApplication.clipboard()
  479. self.project_filename = None
  480. self.toggle_units_ignore = False
  481. # ###########################################################################################################
  482. # ########################################## LOAD LANGUAGES ################################################
  483. # ###########################################################################################################
  484. self.languages = fcTranslate.load_languages()
  485. for name in sorted(self.languages.values()):
  486. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  487. # ###########################################################################################################
  488. # ####################################### APPLY APP LANGUAGE ################################################
  489. # ###########################################################################################################
  490. ret_val = fcTranslate.apply_language('strings')
  491. if ret_val == "no language":
  492. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  493. log.debug("Could not find the Language files. The App strings are missing.")
  494. else:
  495. # make the current language the current selection on the language combobox
  496. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  497. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  498. # ###########################################################################################################
  499. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  500. # ###########################################################################################################
  501. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  502. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  503. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  504. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  505. self.defaults.propagate_defaults()
  506. # ###########################################################################################################
  507. # ######################################## UPDATE THE OPTIONS ###############################################
  508. # ###########################################################################################################
  509. self.options = LoudDict()
  510. # -----------------------------------------------------------------------------------------------------------
  511. # Update the self.options from the self.defaults
  512. # The self.defaults holds the application defaults while the self.options holds the object defaults
  513. # -----------------------------------------------------------------------------------------------------------
  514. # Copy app defaults to project options
  515. for def_key, def_val in self.defaults.items():
  516. self.options[def_key] = deepcopy(def_val)
  517. self.preferencesUiManager.show_preferences_gui()
  518. # ### End of Data ####
  519. # ###########################################################################################################
  520. # #################################### SETUP OBJECT COLLECTION ##############################################
  521. # ###########################################################################################################
  522. self.collection = ObjectCollection(app=self)
  523. self.ui.project_tab_layout.addWidget(self.collection.view)
  524. self.app_obj = AppObject(app=self)
  525. # ### Adjust tabs width ## ##
  526. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  527. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  528. self.collection.view.setMinimumWidth(290)
  529. self.log.debug("Finished creating Object Collection.")
  530. # ###########################################################################################################
  531. # ######################################## SETUP Plot Area ##################################################
  532. # ###########################################################################################################
  533. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  534. if self.defaults["global_graphic_engine"] == '3D':
  535. self.is_legacy = False
  536. else:
  537. self.is_legacy = True
  538. # Event signals disconnect id holders
  539. self.mp = None
  540. self.mm = None
  541. self.mr = None
  542. self.mdc = None
  543. self.mp_zc = None
  544. self.kp = None
  545. # Matplotlib axis
  546. self.axes = None
  547. if show_splash:
  548. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  549. "Canvas initialization started."),
  550. alignment=Qt.AlignBottom | Qt.AlignLeft,
  551. color=QtGui.QColor("gray"))
  552. start_plot_time = time.time() # debug
  553. self.plotcanvas = None
  554. self.app_cursor = None
  555. self.hover_shapes = None
  556. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  557. # setup the PlotCanvas
  558. self.on_plotcanvas_setup()
  559. end_plot_time = time.time()
  560. self.used_time = end_plot_time - start_plot_time
  561. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  562. if show_splash:
  563. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  564. "Canvas initialization started.\n"
  565. "Canvas initialization finished in"), '%.2f' % self.used_time),
  566. alignment=Qt.AlignBottom | Qt.AlignLeft,
  567. color=QtGui.QColor("gray"))
  568. self.ui.splitter.setStretchFactor(1, 2)
  569. # ###########################################################################################################
  570. # ############################################### SYS TRAY ##################################################
  571. # ###########################################################################################################
  572. if self.defaults["global_systray_icon"]:
  573. self.parent_w = QtWidgets.QWidget()
  574. if self.cmd_line_headless == 1:
  575. self.trayIcon = FlatCAMSystemTray(app=self,
  576. icon=QtGui.QIcon(self.resource_location +
  577. '/flatcam_icon32_green.png'),
  578. headless=True,
  579. parent=self.parent_w)
  580. else:
  581. self.trayIcon = FlatCAMSystemTray(app=self,
  582. icon=QtGui.QIcon(self.resource_location +
  583. '/flatcam_icon32_green.png'),
  584. parent=self.parent_w)
  585. # ###########################################################################################################
  586. # ############################################### Worker SETUP ##############################################
  587. # ###########################################################################################################
  588. if self.defaults["global_worker_number"]:
  589. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  590. else:
  591. self.workers = WorkerStack(workers_number=2)
  592. self.worker_task.connect(self.workers.add_task)
  593. self.log.debug("Finished creating Workers crew.")
  594. # ###########################################################################################################
  595. # ############################################# Activity Monitor ###########################################
  596. # ###########################################################################################################
  597. self.activity_view = FlatCAMActivityView(app=self)
  598. self.ui.infobar.addWidget(self.activity_view)
  599. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  600. # ###########################################################################################################
  601. # ############################################# Signal handling #############################################
  602. # ###########################################################################################################
  603. # ########################################## Custom signals ################################################
  604. # signal for displaying messages in status bar
  605. self.inform[str].connect(self.info)
  606. self.inform[str, bool].connect(self.info)
  607. # signal to be called when the app is quiting
  608. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  609. self.message.connect(lambda: message_dialog(parent=self.ui))
  610. # self.progress.connect(self.set_progress_bar)
  611. # signals emitted when file state change
  612. self.file_opened.connect(self.register_recent)
  613. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  614. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  615. # ########################################## Standard signals ###############################################
  616. # ### Menu
  617. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  618. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  619. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  620. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  621. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  622. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  623. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  624. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  625. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  626. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  627. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  628. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  629. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  630. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  631. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  632. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  633. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  634. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  635. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  636. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  637. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  638. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  639. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  640. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  641. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  642. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  643. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  644. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  645. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  646. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  647. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  648. self.ui.menufile_exit.triggered.connect(self.final_save)
  649. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  650. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  651. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  652. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  653. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  654. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  655. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  656. self.ui.menueditdelete.triggered.connect(self.on_delete)
  657. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  658. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  659. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  660. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  661. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  662. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  663. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  664. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  665. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  666. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  667. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  668. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  669. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  670. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  671. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  672. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  673. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  674. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  675. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  676. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  677. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  678. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  679. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  680. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  681. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  682. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  683. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  684. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  685. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  686. self.ui.menuview_replot.triggered.connect(self.plot_all)
  687. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  688. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  689. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  690. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  691. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  692. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  693. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  694. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  695. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  696. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  697. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  698. self.ui.menuhelp_about.triggered.connect(self.on_about)
  699. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  700. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  701. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  702. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  703. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  704. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  705. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  706. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  707. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  708. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  709. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  710. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  711. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  712. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  713. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  714. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  715. # ToolBar signals
  716. self.connect_toolbar_signals()
  717. # Notebook and Plot Tab Area signals
  718. # make the right click on the notebook tab and plot tab area tab raise a menu
  719. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  720. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  721. self.on_tab_setup_context_menu()
  722. # activate initial state
  723. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  724. # Context Menu
  725. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  726. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  727. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  728. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  729. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  730. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  731. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  732. self.ui.clearplot.triggered.connect(self.clear_plots)
  733. self.ui.replot.triggered.connect(self.plot_all)
  734. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  735. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  736. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  737. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  738. self.ui.popmenu_move.triggered.connect(self.obj_move)
  739. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  740. # Project Context Menu -> Color Setting
  741. for act in self.ui.menuprojectcolor.actions():
  742. act.triggered.connect(self.on_set_color_action_triggered)
  743. # ###########################################################################################################
  744. # #################################### GUI PREFERENCES SIGNALS ##############################################
  745. # ###########################################################################################################
  746. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  747. lambda: self.on_toggle_units(no_pref=False))
  748. # ##################################### Workspace Setting Signals ###########################################
  749. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  750. self.on_workspace_modified)
  751. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  752. self.on_workspace_modified
  753. )
  754. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  755. # ###########################################################################################################
  756. # ######################################## GUI SETTINGS SIGNALS #############################################
  757. # ###########################################################################################################
  758. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  759. # ######################################## Tools related signals ############################################
  760. # portability changed signal
  761. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  762. # Object list
  763. self.object_status_changed.connect(self.collection.on_collection_updated)
  764. # when there are arguments at application startup this get launched
  765. self.args_at_startup[list].connect(self.on_startup_args)
  766. # ###########################################################################################################
  767. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  768. # ###########################################################################################################
  769. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  770. lambda: self.restore_extensions(ext_type='excellon'))
  771. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  772. lambda: self.restore_extensions(ext_type='gcode'))
  773. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  774. lambda: self.restore_extensions(ext_type='gerber'))
  775. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  776. lambda: self.delete_all_extensions(ext_type='excellon'))
  777. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  778. lambda: self.delete_all_extensions(ext_type='gcode'))
  779. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  780. lambda: self.delete_all_extensions(ext_type='gerber'))
  781. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  782. lambda: self.add_extension(ext_type='excellon'))
  783. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  784. lambda: self.add_extension(ext_type='gcode'))
  785. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  786. lambda: self.add_extension(ext_type='gerber'))
  787. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  788. lambda: self.del_extension(ext_type='excellon'))
  789. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  790. lambda: self.del_extension(ext_type='gcode'))
  791. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  792. lambda: self.del_extension(ext_type='gerber'))
  793. # connect the 'Apply' buttons from the Preferences/File Associations
  794. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  795. lambda: self.on_register_files(obj_type='excellon'))
  796. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  797. lambda: self.on_register_files(obj_type='gcode'))
  798. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  799. lambda: self.on_register_files(obj_type='gerber'))
  800. # ###########################################################################################################
  801. # ########################################### KEYWORDS SIGNALS ##############################################
  802. # ###########################################################################################################
  803. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  804. lambda: self.restore_extensions(ext_type='keyword'))
  805. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  806. lambda: self.delete_all_extensions(ext_type='keyword'))
  807. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  808. lambda: self.add_extension(ext_type='keyword'))
  809. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  810. lambda: self.del_extension(ext_type='keyword'))
  811. # ###########################################################################################################
  812. # ########################################### GUI SIGNALS ###################################################
  813. # ###########################################################################################################
  814. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  815. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  816. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  817. # ###########################################################################################################
  818. # ####################################### VARIOUS SIGNALS ###################################################
  819. # ###########################################################################################################
  820. # connect the abort_all_tasks related slots to the related signals
  821. self.proc_container.idle_flag.connect(self.app_is_idle)
  822. # signal emitted when a tab is closed in the Plot Area
  823. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  824. # signal to close the application
  825. self.close_app_signal.connect(self.kill_app)
  826. # ################################# FINISHED CONNECTING SIGNALS #############################################
  827. # ###########################################################################################################
  828. # ###########################################################################################################
  829. # ###########################################################################################################
  830. self.log.debug("Finished connecting Signals.")
  831. # ###########################################################################################################
  832. # ########################################## Other setups ###################################################
  833. # ###########################################################################################################
  834. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  835. # depending on from where those tools are called different actions can be done
  836. self.call_source = 'app'
  837. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  838. self.tool_tab_locked = False
  839. # decide if to show or hide the Notebook side of the screen at startup
  840. if self.defaults["global_project_at_startup"] is True:
  841. self.ui.splitter.setSizes([1, 1])
  842. else:
  843. self.ui.splitter.setSizes([0, 1])
  844. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  845. self.setup_component_editor()
  846. # ###########################################################################################################
  847. # ####################################### Auto-complete KEYWORDS ############################################
  848. # ###########################################################################################################
  849. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  850. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  851. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  852. 'export_exc',
  853. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  854. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  855. 'interiors', 'isolate', 'join_excellon',
  856. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  857. 'mirror', 'ncc',
  858. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  859. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  860. 'options', 'origin',
  861. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  862. 'save', 'save_project',
  863. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  864. 'skew', 'subtract_poly', 'subtract_rectangle',
  865. 'version', 'write_gcode'
  866. ]
  867. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  868. 'Paste_1',
  869. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  870. 'Toolchange_manual', 'True', 'Users',
  871. 'all', 'auto', 'axis',
  872. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  873. 'contour', 'default',
  874. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  875. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  876. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  877. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  878. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  879. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  880. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  881. 'spacing_columns',
  882. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  883. 'toolchange_xy', 'toolchangez', 'travelz',
  884. 'tooldia', 'use_threads', 'value',
  885. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  886. ]
  887. self.tcl_keywords = [
  888. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  889. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  890. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  891. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  892. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  893. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  894. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  895. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  896. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  897. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  898. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  899. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  900. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  901. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  902. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  903. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  904. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  905. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  906. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  907. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  908. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  909. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  910. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  911. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  912. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  913. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  914. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  915. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  916. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  917. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  918. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  919. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  920. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  921. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  922. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  923. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  924. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  925. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  926. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  927. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  928. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  929. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  930. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  931. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  932. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  933. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  934. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  935. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  936. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  937. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  938. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  939. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  940. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  941. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  942. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  943. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  944. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  945. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  946. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  947. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  948. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  949. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  950. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  951. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  952. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  953. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  954. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  955. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  956. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  957. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  958. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  959. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  960. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  961. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  962. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  963. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  964. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  965. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  966. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  967. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  968. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  969. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  970. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  971. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  972. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  973. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  974. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  975. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  976. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  977. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  978. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  979. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  980. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  981. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  982. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  983. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  984. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  985. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  986. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  987. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  988. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  989. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  990. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  991. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  992. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  993. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  994. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  995. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  996. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  997. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  998. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  999. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1000. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1001. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1002. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1003. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1004. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1005. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1006. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1007. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1008. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1009. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1010. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1011. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1012. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1013. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1014. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1015. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1016. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1017. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1018. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1019. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1020. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1021. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1022. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1023. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1024. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1025. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1026. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1027. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1028. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1029. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1030. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1031. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1032. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1033. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1034. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1035. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1036. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1037. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1038. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1039. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1040. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1041. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1042. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1043. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1044. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1045. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1046. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1047. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1048. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1049. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1050. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1051. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1052. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1053. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1054. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1055. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1056. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1057. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1058. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1059. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1060. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1061. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1062. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1063. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1064. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1065. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1066. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1067. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1068. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1069. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1070. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1071. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1072. ]
  1073. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1074. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1075. # ###########################################################################################################
  1076. # ############################################## Shell SETUP ################################################
  1077. # ###########################################################################################################
  1078. self.shell = FCShell(app=self, version=self.version)
  1079. self.ui.shell_dock.setWidget(self.shell)
  1080. self.log.debug("TCL Shell has been initialized.")
  1081. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1082. if self.defaults["global_shell_at_startup"]:
  1083. self.ui.shell_dock.show()
  1084. else:
  1085. self.ui.shell_dock.hide()
  1086. # ###########################################################################################################
  1087. # ########################################## Tools and Plugins ##############################################
  1088. # ###########################################################################################################
  1089. self.dblsidedtool = None
  1090. self.distance_tool = None
  1091. self.distance_min_tool = None
  1092. self.panelize_tool = None
  1093. self.film_tool = None
  1094. self.paste_tool = None
  1095. self.calculator_tool = None
  1096. self.rules_tool = None
  1097. self.sub_tool = None
  1098. self.move_tool = None
  1099. self.cutout_tool = None
  1100. self.ncclear_tool = None
  1101. self.paint_tool = None
  1102. self.isolation_tool = None
  1103. self.optimal_tool = None
  1104. self.transform_tool = None
  1105. self.properties_tool = None
  1106. self.pdf_tool = None
  1107. self.image_tool = None
  1108. self.pcb_wizard_tool = None
  1109. self.cal_exc_tool = None
  1110. self.qrcode_tool = None
  1111. self.copper_thieving_tool = None
  1112. self.fiducial_tool = None
  1113. self.edrills_tool = None
  1114. self.align_objects_tool = None
  1115. self.punch_tool = None
  1116. self.invert_tool = None
  1117. self.corners_tool = None
  1118. self.etch_tool = None
  1119. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1120. try:
  1121. self.install_tools()
  1122. except AttributeError as e:
  1123. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1124. # ###########################################################################################################
  1125. # ############################################ SETUP RECENT ITEMS ###########################################
  1126. # ###########################################################################################################
  1127. self.setup_recent_items()
  1128. # ###########################################################################################################
  1129. # ######################################### BookMarks Manager ###############################################
  1130. # ###########################################################################################################
  1131. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1132. self.install_bookmarks()
  1133. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1134. # ###########################################################################################################
  1135. # ########################################### Tools Database ################################################
  1136. # ###########################################################################################################
  1137. self.tools_db_tab = None
  1138. # ### System Font Parsing ###
  1139. # self.f_parse = ParseFont(self)
  1140. # self.parse_system_fonts()
  1141. # ###########################################################################################################
  1142. # ######################################### Check for updates ###############################################
  1143. # ###########################################################################################################
  1144. # Separate thread (Not worker)
  1145. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1146. if (self.beta is False or self.beta is None) and \
  1147. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1148. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1149. # self.thr2 = QtCore.QThread()
  1150. self.worker_task.emit({'fcn': self.version_check,
  1151. 'params': []})
  1152. # self.thr2.start(QtCore.QThread.LowPriority)
  1153. # ###########################################################################################################
  1154. # ##################################### Register files with FlatCAM; #######################################
  1155. # ################################### It works only for Windows for now ####################################
  1156. # ###########################################################################################################
  1157. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1158. self.on_register_files()
  1159. # ###########################################################################################################
  1160. # ######################################## Variables for global usage #######################################
  1161. # ###########################################################################################################
  1162. # hold the App units
  1163. self.units = 'MM'
  1164. # coordinates for relative position display
  1165. self.rel_point1 = (0, 0)
  1166. self.rel_point2 = (0, 0)
  1167. # variable to store coordinates
  1168. self.pos = (0, 0)
  1169. self.pos_canvas = (0, 0)
  1170. self.pos_jump = (0, 0)
  1171. # variable to store mouse coordinates
  1172. self.mouse = [0, 0]
  1173. # variable to store the delta positions on cavnas
  1174. self.dx = 0
  1175. self.dy = 0
  1176. # decide if we have a double click or single click
  1177. self.doubleclick = False
  1178. # store here the is_dragging value
  1179. self.event_is_dragging = False
  1180. # variable to store if a command is active (then the var is not None) and which one it is
  1181. self.command_active = None
  1182. # variable to store the status of moving selection action
  1183. # None value means that it's not an selection action
  1184. # True value = a selection from left to right
  1185. # False value = a selection from right to left
  1186. self.selection_type = None
  1187. # List to store the objects that are currently loaded in FlatCAM
  1188. # This list is updated on each object creation or object delete
  1189. self.all_objects_list = []
  1190. self.objects_under_the_click_list = []
  1191. # List to store the objects that are selected
  1192. self.sel_objects_list = []
  1193. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1194. self.key_modifiers = None
  1195. # Variable to store the status of the code editor
  1196. self.toggle_codeeditor = False
  1197. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1198. self.click_noproject = False
  1199. self.cursor = None
  1200. # Variable to store the GCODE that was edited
  1201. self.gcode_edited = ""
  1202. self.text_editor_tab = None
  1203. # reference for the self.ui.code_editor
  1204. self.reference_code_editor = None
  1205. self.script_code = ''
  1206. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1207. self.tools_db_changed_flag = False
  1208. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1209. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1210. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1211. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1212. 'tsm']
  1213. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1214. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1215. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1216. 'sbp', 'tap', 'xpi']
  1217. self.svg_list = ['svg']
  1218. self.dxf_list = ['dxf']
  1219. self.pdf_list = ['pdf']
  1220. self.prj_list = ['flatprj']
  1221. self.conf_list = ['flatconfig']
  1222. # last used filters
  1223. self.last_op_gerber_filter = None
  1224. self.last_op_excellon_filter = None
  1225. self.last_op_gcode_filter = None
  1226. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1227. # flag for polygons not cleared
  1228. self.poly_not_cleared = False
  1229. # VisPy visuals
  1230. self.isHovering = False
  1231. self.notHovering = True
  1232. # Window geometry
  1233. self.x_pos = None
  1234. self.y_pos = None
  1235. self.width = None
  1236. self.height = None
  1237. # when True, the app has to return from any thread
  1238. self.abort_flag = False
  1239. # set the value used in the Windows Title
  1240. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1241. # this holds a widget that is installed in the Plot Area when View Source option is used
  1242. self.source_editor_tab = None
  1243. self.pagesize = {}
  1244. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1245. # VisPy visuals
  1246. if self.is_legacy is False:
  1247. try:
  1248. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1249. except AttributeError:
  1250. self.tool_shapes = None
  1251. else:
  1252. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1253. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1254. # used in the delayed shutdown self.start_delayed_quit() method
  1255. self.save_timer = None
  1256. # ###########################################################################################################
  1257. # ################################## ADDING FlatCAM EDITORS section #########################################
  1258. # ###########################################################################################################
  1259. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1260. # at the first launch of the App , the editors will not be functional.
  1261. try:
  1262. self.geo_editor = FlatCAMGeoEditor(self)
  1263. except AttributeError:
  1264. pass
  1265. try:
  1266. self.exc_editor = FlatCAMExcEditor(self)
  1267. except AttributeError:
  1268. pass
  1269. try:
  1270. self.grb_editor = FlatCAMGrbEditor(self)
  1271. except AttributeError:
  1272. pass
  1273. self.log.debug("Finished adding FlatCAM Editor's.")
  1274. self.set_ui_title(name=_("New Project - Not saved"))
  1275. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1276. current_platform = platform.architecture()[0]
  1277. if current_platform != '64bit':
  1278. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1279. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1280. # ###########################################################################################################
  1281. # ########################################### EXCLUSION AREAS ###############################################
  1282. # ###########################################################################################################
  1283. self.exc_areas = ExclusionAreas(app=self)
  1284. # ###########################################################################################################
  1285. # ##################################### Finished the CONSTRUCTOR ############################################
  1286. # ###########################################################################################################
  1287. App.log.debug("END of constructor. Releasing control.")
  1288. # ###########################################################################################################
  1289. # ########################################## SHOW GUI #######################################################
  1290. # ###########################################################################################################
  1291. # if the app is not started as headless, show it
  1292. if self.cmd_line_headless != 1:
  1293. if show_splash:
  1294. # finish the splash
  1295. self.splash.finish(self.ui)
  1296. mgui_settings = QSettings("Open Source", "FlatCAM")
  1297. if mgui_settings.contains("maximized_gui"):
  1298. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1299. if maximized_ui is True:
  1300. self.ui.showMaximized()
  1301. else:
  1302. self.ui.show()
  1303. else:
  1304. self.ui.show()
  1305. if self.defaults["global_systray_icon"]:
  1306. self.trayIcon.show()
  1307. else:
  1308. log.warning("******************* RUNNING HEADLESS *******************")
  1309. # ###########################################################################################################
  1310. # ######################################## START-UP ARGUMENTS ###############################################
  1311. # ###########################################################################################################
  1312. # test if the program was started with a script as parameter
  1313. if self.cmd_line_shellvar:
  1314. try:
  1315. cnt = 0
  1316. command_tcl = 0
  1317. for i in self.cmd_line_shellvar.split(','):
  1318. if i is not None:
  1319. # noinspection PyBroadException
  1320. try:
  1321. command_tcl = eval(i)
  1322. except Exception:
  1323. command_tcl = i
  1324. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1325. cnt += 1
  1326. # if there are Windows paths then replace the path separator with a Unix like one
  1327. if sys.platform == 'win32':
  1328. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1329. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1330. except Exception as ext:
  1331. print("ERROR: ", ext)
  1332. sys.exit(2)
  1333. if self.cmd_line_shellfile:
  1334. if self.cmd_line_headless != 1:
  1335. if self.ui.shell_dock.isHidden():
  1336. self.ui.shell_dock.show()
  1337. try:
  1338. with open(self.cmd_line_shellfile, "r") as myfile:
  1339. # if show_splash:
  1340. # self.splash.showMessage('%s: %ssec\n%s' % (
  1341. # _("Canvas initialization started.\n"
  1342. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1343. # _("Executing Tcl Script ...")),
  1344. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1345. # color=QtGui.QColor("gray"))
  1346. cmd_line_shellfile_text = myfile.read()
  1347. if self.cmd_line_headless != 1:
  1348. self.shell.exec_command(cmd_line_shellfile_text)
  1349. else:
  1350. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1351. except Exception as ext:
  1352. print("ERROR: ", ext)
  1353. sys.exit(2)
  1354. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1355. # the path/file_name must be enclosed in quotes if it contain spaces
  1356. if App.args:
  1357. self.args_at_startup.emit(App.args)
  1358. if self.defaults.old_defaults_found is True:
  1359. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1360. "Please reboot the application to update."))
  1361. self.defaults.old_defaults_found = False
  1362. # ######################################### INIT FINISHED #######################################################
  1363. # #################################################################################################################
  1364. # #################################################################################################################
  1365. # #################################################################################################################
  1366. # #################################################################################################################
  1367. # #################################################################################################################
  1368. @staticmethod
  1369. def copy_and_overwrite(from_path, to_path):
  1370. """
  1371. From here:
  1372. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1373. :param from_path: source path
  1374. :param to_path: destination path
  1375. :return: None
  1376. """
  1377. if os.path.exists(to_path):
  1378. shutil.rmtree(to_path)
  1379. try:
  1380. shutil.copytree(from_path, to_path)
  1381. except FileNotFoundError:
  1382. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1383. shutil.copytree(from_new_path, to_path)
  1384. def on_startup_args(self, args, silent=False):
  1385. """
  1386. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1387. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1388. :param args: a list containing the application args at startup
  1389. :return: None
  1390. """
  1391. if args is not None:
  1392. args_to_process = args
  1393. else:
  1394. args_to_process = App.args
  1395. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1396. for argument in args_to_process:
  1397. if '.FlatPrj'.lower() in argument.lower():
  1398. try:
  1399. project_name = str(argument)
  1400. if project_name == "":
  1401. if silent is False:
  1402. self.inform.emit(_("Cancelled."))
  1403. else:
  1404. # self.open_project(project_name)
  1405. run_from_arg = True
  1406. # self.worker_task.emit({'fcn': self.open_project,
  1407. # 'params': [project_name, run_from_arg]})
  1408. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1409. except Exception as e:
  1410. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1411. elif '.FlatConfig'.lower() in argument.lower():
  1412. try:
  1413. file_name = str(argument)
  1414. if file_name == "":
  1415. if silent is False:
  1416. self.inform.emit(_("Open Config file failed."))
  1417. else:
  1418. run_from_arg = True
  1419. # self.worker_task.emit({'fcn': self.open_config_file,
  1420. # 'params': [file_name, run_from_arg]})
  1421. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1422. except Exception as e:
  1423. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1424. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1425. try:
  1426. file_name = str(argument)
  1427. if file_name == "":
  1428. if silent is False:
  1429. self.inform.emit(_("Open Script file failed."))
  1430. else:
  1431. if silent is False:
  1432. self.on_fileopenscript(name=file_name)
  1433. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1434. self.on_filerunscript(name=file_name)
  1435. except Exception as e:
  1436. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1437. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1438. log.debug("App.on_startup_args() --> Quit event.")
  1439. sys.exit()
  1440. elif 'save'.lower() in argument.lower():
  1441. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1442. self.preferencesUiManager.save_defaults()
  1443. else:
  1444. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1445. proc_arg = argument.lower()
  1446. for ext in exc_list:
  1447. proc_ext = ext.replace(' ', '')
  1448. proc_ext = '.%s' % proc_ext
  1449. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1450. file_name = str(argument)
  1451. if file_name == "":
  1452. if silent is False:
  1453. self.inform.emit(_("Open Excellon file failed."))
  1454. else:
  1455. self.on_fileopenexcellon(name=file_name, signal=None)
  1456. return
  1457. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1458. for ext in gco_list:
  1459. proc_ext = ext.replace(' ', '')
  1460. proc_ext = '.%s' % proc_ext
  1461. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1462. file_name = str(argument)
  1463. if file_name == "":
  1464. if silent is False:
  1465. self.inform.emit(_("Open GCode file failed."))
  1466. else:
  1467. self.on_fileopengcode(name=file_name, signal=None)
  1468. return
  1469. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1470. for ext in grb_list:
  1471. proc_ext = ext.replace(' ', '')
  1472. proc_ext = '.%s' % proc_ext
  1473. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1474. file_name = str(argument)
  1475. if file_name == "":
  1476. if silent is False:
  1477. self.inform.emit(_("Open Gerber file failed."))
  1478. else:
  1479. self.on_fileopengerber(name=file_name, signal=None)
  1480. return
  1481. # if it reached here without already returning then the app was registered with a file that it does not
  1482. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1483. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1484. # for arg in args_to_process:
  1485. # if 'FlatCAM.exe' in arg:
  1486. # continue
  1487. # else:
  1488. # sys.exit(2)
  1489. def set_ui_title(self, name):
  1490. """
  1491. Sets the title of the main window.
  1492. :param name: String that store the project path and project name
  1493. :return: None
  1494. """
  1495. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1496. (self.version,
  1497. ('BETA' if self.beta else ''),
  1498. platform.architecture()[0],
  1499. self.engine,
  1500. name)
  1501. )
  1502. def on_app_restart(self):
  1503. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1504. # be left in the SySTray
  1505. try:
  1506. self.trayIcon.hide()
  1507. except Exception:
  1508. pass
  1509. fcTranslate.restart_program(app=self)
  1510. def clear_pool(self):
  1511. """
  1512. Clear the multiprocessing pool and calls garbage collector.
  1513. :return: None
  1514. """
  1515. self.pool.close()
  1516. self.pool = Pool()
  1517. self.pool_recreated.emit(self.pool)
  1518. gc.collect()
  1519. def install_tools(self):
  1520. """
  1521. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1522. Instantiation of the Tools classes.
  1523. The order that the tools are installed is important as they can depend on each other install position.
  1524. :return: None
  1525. """
  1526. self.distance_tool = Distance(self)
  1527. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1528. before=self.ui.menueditorigin,
  1529. separator=False)
  1530. self.distance_min_tool = DistanceMin(self)
  1531. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1532. pos=self.ui.menuedit,
  1533. before=self.ui.menueditorigin,
  1534. separator=True)
  1535. self.dblsidedtool = DblSidedTool(self)
  1536. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1537. self.cal_exc_tool = ToolCalibration(self)
  1538. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1539. before=self.dblsidedtool.menuAction,
  1540. separator=False)
  1541. self.align_objects_tool = AlignObjects(self)
  1542. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1543. self.edrills_tool = ToolExtractDrills(self)
  1544. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1545. self.panelize_tool = Panelize(self)
  1546. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1547. self.film_tool = Film(self)
  1548. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1549. self.paste_tool = SolderPaste(self)
  1550. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1551. self.calculator_tool = ToolCalculator(self)
  1552. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1553. self.sub_tool = ToolSub(self)
  1554. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1555. pos=self.ui.menutool, separator=True)
  1556. self.rules_tool = RulesCheck(self)
  1557. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1558. pos=self.ui.menutool, separator=False)
  1559. self.optimal_tool = ToolOptimal(self)
  1560. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1561. pos=self.ui.menutool, separator=True)
  1562. self.move_tool = ToolMove(self)
  1563. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1564. before=self.ui.menueditorigin, separator=True)
  1565. self.cutout_tool = CutOut(self)
  1566. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1567. before=self.sub_tool.menuAction)
  1568. self.ncclear_tool = NonCopperClear(self)
  1569. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1570. before=self.sub_tool.menuAction, separator=True)
  1571. self.paint_tool = ToolPaint(self)
  1572. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1573. before=self.sub_tool.menuAction, separator=True)
  1574. self.isolation_tool = ToolIsolation(self)
  1575. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1576. before=self.sub_tool.menuAction, separator=True)
  1577. self.copper_thieving_tool = ToolCopperThieving(self)
  1578. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1579. pos=self.ui.menutool)
  1580. self.fiducial_tool = ToolFiducials(self)
  1581. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1582. pos=self.ui.menutool)
  1583. self.qrcode_tool = QRCode(self)
  1584. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1585. pos=self.ui.menutool)
  1586. self.punch_tool = ToolPunchGerber(self)
  1587. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1588. self.invert_tool = ToolInvertGerber(self)
  1589. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1590. self.corners_tool = ToolCorners(self)
  1591. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1592. self.etch_tool = ToolEtchCompensation(self)
  1593. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1594. self.transform_tool = ToolTransform(self)
  1595. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1596. pos=self.ui.menuoptions, separator=True)
  1597. self.properties_tool = Properties(self)
  1598. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1599. pos=self.ui.menuoptions)
  1600. self.pdf_tool = ToolPDF(self)
  1601. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1602. pos=self.ui.menufileimport,
  1603. separator=True)
  1604. self.image_tool = ToolImage(self)
  1605. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1606. pos=self.ui.menufileimport,
  1607. separator=True)
  1608. self.pcb_wizard_tool = PcbWizard(self)
  1609. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1610. pos=self.ui.menufileimport)
  1611. self.log.debug("Tools are installed.")
  1612. def remove_tools(self):
  1613. """
  1614. Will remove all the actions in the Tool menu.
  1615. :return: None
  1616. """
  1617. for act in self.ui.menutool.actions():
  1618. self.ui.menutool.removeAction(act)
  1619. def init_tools(self):
  1620. """
  1621. Initialize the Tool tab in the notebook side of the central widget.
  1622. Remove the actions in the Tools menu.
  1623. Instantiate again the FlatCAM tools (plugins).
  1624. All this is required when changing the layout: standard, compact etc.
  1625. :return: None
  1626. """
  1627. log.debug("init_tools()")
  1628. # delete the data currently in the Tools Tab and the Tab itself
  1629. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1630. if widget is not None:
  1631. widget.deleteLater()
  1632. self.ui.notebook.removeTab(2)
  1633. # rebuild the Tools Tab
  1634. self.ui.tool_tab = QtWidgets.QWidget()
  1635. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1636. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1637. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1638. self.ui.tool_scroll_area = VerticalScrollArea()
  1639. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1640. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1641. # first remove all of them
  1642. self.remove_tools()
  1643. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1644. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1645. '&Command Line\tS')
  1646. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1647. # third install all of them
  1648. try:
  1649. self.install_tools()
  1650. except AttributeError:
  1651. pass
  1652. self.log.debug("Tools are initialized.")
  1653. # def parse_system_fonts(self):
  1654. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1655. # 'params': []})
  1656. def connect_toolbar_signals(self):
  1657. """
  1658. Reconnect the signals to the actions in the toolbar.
  1659. This has to be done each time after the FlatCAM tools are removed/installed.
  1660. :return: None
  1661. """
  1662. # Toolbar
  1663. # File Toolbar Signals
  1664. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1665. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1666. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1667. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1668. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1669. # View Toolbar Signals
  1670. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1671. self.ui.replot_btn.triggered.connect(self.plot_all)
  1672. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1673. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1674. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1675. # Edit Toolbar Signals
  1676. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1677. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1678. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1679. self.ui.delete_btn.triggered.connect(self.on_delete)
  1680. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1681. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1682. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1683. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1684. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1685. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1686. # Scripting Toolbar Signals
  1687. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1688. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1689. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1690. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1691. # Tools Toolbar Signals
  1692. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1693. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1694. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1695. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1696. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1697. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1698. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1699. self.ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1700. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1701. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1702. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1703. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1704. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1705. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1706. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1707. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1708. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1709. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1710. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1711. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1712. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1713. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1714. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1715. def object2editor(self):
  1716. """
  1717. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1718. :return: None
  1719. """
  1720. self.defaults.report_usage("object2editor()")
  1721. # disable the objects menu as it may interfere with the AppEditors
  1722. self.ui.menuobjects.setDisabled(True)
  1723. edited_object = self.collection.get_active()
  1724. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1725. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1726. pass
  1727. else:
  1728. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1729. return
  1730. if isinstance(edited_object, GeometryObject):
  1731. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1732. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1733. # we set the notebook to hidden
  1734. # self.ui.splitter.setSizes([0, 1])
  1735. if edited_object.multigeo is True:
  1736. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1737. if len(sel_rows) > 1:
  1738. self.inform.emit('[WARNING_NOTCL] %s' %
  1739. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1740. "is not possible.\n"
  1741. "Edit only one geometry at a time."))
  1742. # determine the tool dia of the selected tool
  1743. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1744. # now find the key in the edited_object.tools that has this tooldia
  1745. multi_tool = 1
  1746. for tool in edited_object.tools:
  1747. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1748. multi_tool = tool
  1749. break
  1750. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1751. else:
  1752. self.geo_editor.edit_fcgeometry(edited_object)
  1753. # set call source to the Editor we go into
  1754. self.call_source = 'geo_editor'
  1755. elif isinstance(edited_object, ExcellonObject):
  1756. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1757. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1758. if self.ui.splitter.sizes()[0] == 0:
  1759. self.ui.splitter.setSizes([1, 1])
  1760. self.exc_editor.edit_fcexcellon(edited_object)
  1761. # set call source to the Editor we go into
  1762. self.call_source = 'exc_editor'
  1763. elif isinstance(edited_object, GerberObject):
  1764. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1765. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1766. if self.ui.splitter.sizes()[0] == 0:
  1767. self.ui.splitter.setSizes([1, 1])
  1768. self.grb_editor.edit_fcgerber(edited_object)
  1769. # set call source to the Editor we go into
  1770. self.call_source = 'grb_editor'
  1771. # reset the following variables so the UI is built again after edit
  1772. edited_object.ui_build = False
  1773. edited_object.build_aperture_storage = False
  1774. elif isinstance(edited_object, CNCJobObject):
  1775. if self.ui.splitter.sizes()[0] == 0:
  1776. self.ui.splitter.setSizes([1, 1])
  1777. edited_object.on_edit_code_click()
  1778. return
  1779. # make sure that we can't select another object while in Editor Mode:
  1780. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1781. self.ui.project_frame.setDisabled(True)
  1782. # delete any selection shape that might be active as they are not relevant in Editor
  1783. self.delete_selection_shape()
  1784. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1785. self.ui.plot_tab_area.protectTab(0)
  1786. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1787. self.should_we_save = True
  1788. def editor2object(self, cleanup=None):
  1789. """
  1790. Transfers the Geometry or Excellon from it's editor to the current object.
  1791. :return: None
  1792. """
  1793. self.defaults.report_usage("editor2object()")
  1794. # re-enable the objects menu that was disabled on entry in Editor mode
  1795. self.ui.menuobjects.setDisabled(False)
  1796. # do not update a geometry or excellon object unless it comes out of an editor
  1797. if self.call_source != 'app':
  1798. edited_obj = self.collection.get_active()
  1799. if cleanup is None:
  1800. msgbox = QtWidgets.QMessageBox()
  1801. msgbox.setText(_("Do you want to save the edited object?"))
  1802. msgbox.setWindowTitle(_("Close Editor"))
  1803. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1804. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1805. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1806. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1807. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1808. msgbox.setDefaultButton(bt_yes)
  1809. msgbox.exec_()
  1810. response = msgbox.clickedButton()
  1811. if response == bt_yes:
  1812. # clean the Tools Tab
  1813. self.ui.tool_scroll_area.takeWidget()
  1814. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1815. self.ui.notebook.setTabText(2, "Tool")
  1816. if isinstance(edited_obj, GeometryObject):
  1817. obj_type = "Geometry"
  1818. self.geo_editor.update_fcgeometry(edited_obj)
  1819. # self.geo_editor.update_options(edited_obj)
  1820. # restore GUI to the Selected TAB
  1821. # Remove anything else in the AppGUI
  1822. self.ui.tool_scroll_area.takeWidget()
  1823. # update the geo object options so it is including the bounding box values
  1824. try:
  1825. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1826. edited_obj.options['xmin'] = xmin
  1827. edited_obj.options['ymin'] = ymin
  1828. edited_obj.options['xmax'] = xmax
  1829. edited_obj.options['ymax'] = ymax
  1830. except AttributeError as e:
  1831. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1832. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1833. edited_obj.build_ui()
  1834. edited_obj.plot()
  1835. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1836. elif isinstance(edited_obj, GerberObject):
  1837. obj_type = "Gerber"
  1838. self.grb_editor.update_fcgerber()
  1839. # self.grb_editor.update_options(edited_obj)
  1840. # delete the old object (the source object) if it was an empty one
  1841. try:
  1842. if len(edited_obj.solid_geometry) == 0:
  1843. old_name = edited_obj.options['name']
  1844. self.collection.delete_by_name(old_name)
  1845. except TypeError:
  1846. # if the solid_geometry is a single Polygon the len() will not work
  1847. # in any case, falling here means that we have something in the solid_geometry, even if only
  1848. # a single Polygon, therefore we pass this
  1849. pass
  1850. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1851. # restore GUI to the Selected TAB
  1852. # Remove anything else in the AppGUI
  1853. self.ui.selected_scroll_area.takeWidget()
  1854. elif isinstance(edited_obj, ExcellonObject):
  1855. obj_type = "Excellon"
  1856. self.exc_editor.update_fcexcellon(edited_obj)
  1857. # self.exc_editor.update_options(edited_obj)
  1858. # restore GUI to the Selected TAB
  1859. # Remove anything else in the AppGUI
  1860. self.ui.tool_scroll_area.takeWidget()
  1861. # delete the old object (the source object) if it was an empty one
  1862. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1863. old_name = edited_obj.options['name']
  1864. self.collection.delete_by_name(name=old_name)
  1865. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1866. else:
  1867. self.inform.emit('[WARNING_NOTCL] %s' %
  1868. _("Select a Gerber, Geometry or Excellon Object to update."))
  1869. return
  1870. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1871. elif response == bt_no:
  1872. # clean the Tools Tab
  1873. self.ui.tool_scroll_area.takeWidget()
  1874. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1875. self.ui.notebook.setTabText(2, "Tool")
  1876. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1877. if isinstance(edited_obj, GeometryObject):
  1878. self.geo_editor.deactivate()
  1879. edited_obj.build_ui()
  1880. edited_obj.plot()
  1881. elif isinstance(edited_obj, GerberObject):
  1882. self.grb_editor.deactivate_grb_editor()
  1883. edited_obj.build_ui()
  1884. elif isinstance(edited_obj, ExcellonObject):
  1885. self.exc_editor.deactivate()
  1886. edited_obj.build_ui()
  1887. else:
  1888. self.inform.emit('[WARNING_NOTCL] %s' %
  1889. _("Select a Gerber, Geometry or Excellon Object to update."))
  1890. return
  1891. elif response == bt_cancel:
  1892. return
  1893. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1894. # edited_obj.build_ui()
  1895. # Switch notebook to Selected page
  1896. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1897. else:
  1898. if isinstance(edited_obj, GeometryObject):
  1899. self.geo_editor.deactivate()
  1900. elif isinstance(edited_obj, GerberObject):
  1901. self.grb_editor.deactivate_grb_editor()
  1902. elif isinstance(edited_obj, ExcellonObject):
  1903. self.exc_editor.deactivate()
  1904. else:
  1905. self.inform.emit('[WARNING_NOTCL] %s' %
  1906. _("Select a Gerber, Geometry or Excellon Object to update."))
  1907. return
  1908. # if notebook is hidden we show it
  1909. if self.ui.splitter.sizes()[0] == 0:
  1910. self.ui.splitter.setSizes([1, 1])
  1911. # restore the call_source to app
  1912. self.call_source = 'app'
  1913. # edited_obj.plot()
  1914. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1915. self.ui.plot_tab_area.protectTab(0)
  1916. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1917. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1918. self.ui.project_frame.setDisabled(False)
  1919. def get_last_folder(self):
  1920. """
  1921. Get the folder path from where the last file was opened.
  1922. :return: String, last opened folder path
  1923. """
  1924. return self.defaults["global_last_folder"]
  1925. def get_last_save_folder(self):
  1926. """
  1927. Get the folder path from where the last file was saved.
  1928. :return: String, last saved folder path
  1929. """
  1930. loc = self.defaults["global_last_save_folder"]
  1931. if loc is None:
  1932. loc = self.defaults["global_last_folder"]
  1933. if loc is None:
  1934. loc = os.path.dirname(__file__)
  1935. return loc
  1936. @QtCore.pyqtSlot(str)
  1937. @QtCore.pyqtSlot(str, bool)
  1938. def info(self, msg, shell_echo=True):
  1939. """
  1940. Informs the user. Normally on the status bar, optionally
  1941. also on the shell.
  1942. :param msg: Text to write.
  1943. :type msg: str
  1944. :param shell_echo: Control if to display the message msg in the Shell
  1945. :type shell_echo: bool
  1946. :return: None
  1947. """
  1948. # Type of message in brackets at the beginning of the message.
  1949. match = re.search(r"\[(.*)\](.*)", msg)
  1950. if match:
  1951. level = match.group(1)
  1952. msg_ = match.group(2)
  1953. self.ui.fcinfo.set_status(str(msg_), level=level)
  1954. if shell_echo is True:
  1955. if level.lower() == "error":
  1956. self.shell_message(msg, error=True, show=True)
  1957. elif level.lower() == "warning":
  1958. self.shell_message(msg, warning=True, show=True)
  1959. elif level.lower() == "error_notcl":
  1960. self.shell_message(msg, error=True, show=False)
  1961. elif level.lower() == "warning_notcl":
  1962. self.shell_message(msg, warning=True, show=False)
  1963. elif level.lower() == "success":
  1964. self.shell_message(msg, success=True, show=False)
  1965. elif level.lower() == "selected":
  1966. self.shell_message(msg, selected=True, show=False)
  1967. else:
  1968. self.shell_message(msg, show=False)
  1969. else:
  1970. self.ui.fcinfo.set_status(str(msg), level="info")
  1971. # make sure that if the message is to clear the infobar with a space
  1972. # is not printed over and over on the shell
  1973. if msg != '' and shell_echo is True:
  1974. self.shell_message(msg)
  1975. def on_import_preferences(self):
  1976. """
  1977. Loads the application default settings from a saved file into
  1978. ``self.defaults`` dictionary.
  1979. :return: None
  1980. """
  1981. self.defaults.report_usage("on_import_preferences")
  1982. App.log.debug("App.on_import_preferences()")
  1983. # Show file chooser
  1984. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1985. try:
  1986. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1987. directory=self.data_path,
  1988. filter=filter_)
  1989. except TypeError:
  1990. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1991. filter=filter_)
  1992. filename = str(filename)
  1993. if filename == "":
  1994. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1995. return
  1996. # Load in the defaults from the chosen file
  1997. self.defaults.load(filename=filename)
  1998. self.preferencesUiManager.on_preferences_edited()
  1999. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2000. def on_export_preferences(self):
  2001. """
  2002. Save the defaults dictionary to a file.
  2003. :return: None
  2004. """
  2005. self.defaults.report_usage("on_export_preferences")
  2006. App.log.debug("on_export_preferences()")
  2007. # defaults_file_content = None
  2008. # Show file chooser
  2009. date = str(datetime.today()).rpartition('.')[0]
  2010. date = ''.join(c for c in date if c not in ':-')
  2011. date = date.replace(' ', '_')
  2012. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2013. try:
  2014. filename, _f = FCFileSaveDialog.get_saved_filename(
  2015. caption=_("Export FlatCAM Preferences"),
  2016. directory=self.data_path + '/preferences_' + date,
  2017. ext_filter=filter__
  2018. )
  2019. except TypeError:
  2020. filename, _f = FCFileSaveDialog.get_saved_filename(
  2021. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2022. filename = str(filename)
  2023. if filename == "":
  2024. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2025. return
  2026. # Update options
  2027. self.preferencesUiManager.defaults_read_form()
  2028. self.defaults.propagate_defaults()
  2029. # Save update options
  2030. try:
  2031. self.defaults.write(filename=filename)
  2032. except Exception:
  2033. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2034. return
  2035. if self.defaults["global_open_style"] is False:
  2036. self.file_opened.emit("preferences", filename)
  2037. self.file_saved.emit("preferences", filename)
  2038. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2039. def save_to_file(self, content_to_save, txt_content):
  2040. """
  2041. Save something to a file.
  2042. :return: None
  2043. """
  2044. self.defaults.report_usage("save_to_file")
  2045. App.log.debug("save_to_file()")
  2046. self.date = str(datetime.today()).rpartition('.')[0]
  2047. self.date = ''.join(c for c in self.date if c not in ':-')
  2048. self.date = self.date.replace(' ', '_')
  2049. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2050. path_to_save = self.defaults["global_last_save_folder"] if \
  2051. self.defaults["global_last_save_folder"] is not None else self.data_path
  2052. try:
  2053. filename, _f = FCFileSaveDialog.get_saved_filename(
  2054. caption=_("Save to file"),
  2055. directory=path_to_save + '/file_' + self.date,
  2056. ext_filter=filter__
  2057. )
  2058. except TypeError:
  2059. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2060. filename = str(filename)
  2061. if filename == "":
  2062. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2063. return
  2064. else:
  2065. try:
  2066. with open(filename, 'w') as f:
  2067. ___ = f.read()
  2068. except PermissionError:
  2069. self.inform.emit('[WARNING] %s' %
  2070. _("Permission denied, saving not possible.\n"
  2071. "Most likely another app is holding the file open and not accessible."))
  2072. return
  2073. except IOError:
  2074. App.log.debug('Creating a new file ...')
  2075. f = open(filename, 'w')
  2076. f.close()
  2077. except Exception:
  2078. e = sys.exc_info()[0]
  2079. App.log.error("Could not load the file.")
  2080. App.log.error(str(e))
  2081. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2082. return
  2083. # Save content
  2084. if filename.rpartition('.')[2].lower() == 'html':
  2085. file_content = content_to_save
  2086. else:
  2087. file_content = txt_content
  2088. try:
  2089. with open(filename, "w") as f:
  2090. f.write(file_content)
  2091. except Exception:
  2092. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2093. return
  2094. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2095. def register_recent(self, kind, filename):
  2096. """
  2097. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2098. dictionary.
  2099. :param kind: type of file that was opened
  2100. :param filename: the path and file name for the file that was opened
  2101. :return:
  2102. """
  2103. self.log.debug("register_recent()")
  2104. self.log.debug(" %s" % kind)
  2105. self.log.debug(" %s" % filename)
  2106. record = {'kind': str(kind), 'filename': str(filename)}
  2107. if record in self.recent:
  2108. return
  2109. if record in self.recent_projects:
  2110. return
  2111. if record['kind'] == 'project':
  2112. self.recent_projects.insert(0, record)
  2113. else:
  2114. self.recent.insert(0, record)
  2115. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2116. self.recent.pop()
  2117. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2118. self.recent_projects.pop()
  2119. try:
  2120. f = open(self.data_path + '/recent.json', 'w')
  2121. except IOError:
  2122. App.log.error("Failed to open recent items file for writing.")
  2123. self.inform.emit('[ERROR_NOTCL] %s' %
  2124. _('Failed to open recent files file for writing.'))
  2125. return
  2126. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2127. f.close()
  2128. try:
  2129. fp = open(self.data_path + '/recent_projects.json', 'w')
  2130. except IOError:
  2131. App.log.error("Failed to open recent items file for writing.")
  2132. self.inform.emit('[ERROR_NOTCL] %s' %
  2133. _('Failed to open recent projects file for writing.'))
  2134. return
  2135. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2136. fp.close()
  2137. # Re-build the recent items menu
  2138. self.setup_recent_items()
  2139. def on_about(self):
  2140. """
  2141. Displays the "about" dialog found in the Menu --> Help.
  2142. :return: None
  2143. """
  2144. self.defaults.report_usage("on_about")
  2145. version = self.version
  2146. version_date = self.version_date
  2147. beta = self.beta
  2148. class AboutDialog(QtWidgets.QDialog):
  2149. def __init__(self, app, parent=None):
  2150. QtWidgets.QDialog.__init__(self, parent)
  2151. self.app = app
  2152. # Icon and title
  2153. self.setWindowIcon(parent.app_icon)
  2154. self.setWindowTitle(_("About FlatCAM"))
  2155. self.resize(600, 200)
  2156. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2157. # self.setStyleSheet(
  2158. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2159. # "background-attachment: fixed"
  2160. # )
  2161. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2162. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2163. # palette = QtGui.QPalette()
  2164. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2165. # self.setPalette(palette)
  2166. logo = QtWidgets.QLabel()
  2167. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2168. title = QtWidgets.QLabel(
  2169. "<font size=8><B>FlatCAM</B></font><BR>"
  2170. "{title}<BR>"
  2171. "<BR>"
  2172. "<BR>"
  2173. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2174. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2175. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2176. "<B>{issue}</B></a><BR>".format(
  2177. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2178. devel=_("Development"),
  2179. down=_("DOWNLOAD"),
  2180. issue=_("Issue tracker"))
  2181. )
  2182. title.setOpenExternalLinks(True)
  2183. closebtn = QtWidgets.QPushButton(_("Close"))
  2184. tab_widget = QtWidgets.QTabWidget()
  2185. description_label = QtWidgets.QLabel(
  2186. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2187. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2188. version=version,
  2189. beta=('BETA' if beta else ''),
  2190. date=version_date,
  2191. arch=platform.architecture()[0])
  2192. )
  2193. description_label.setOpenExternalLinks(True)
  2194. lic_lbl_header = QtWidgets.QLabel(
  2195. '%s:<br>%s<br>' % (
  2196. _('Licensed under the MIT license'),
  2197. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2198. "http://www.opensource.org/licenses/mit-license.php</a>"
  2199. )
  2200. )
  2201. lic_lbl_header.setOpenExternalLinks(True)
  2202. lic_lbl_body = QtWidgets.QLabel(
  2203. _(
  2204. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2205. 'of this software and associated documentation files (the "Software"), to deal\n'
  2206. 'in the Software without restriction, including without limitation the rights\n'
  2207. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2208. 'copies of the Software, and to permit persons to whom the Software is\n'
  2209. 'furnished to do so, subject to the following conditions:\n\n'
  2210. 'The above copyright notice and this permission notice shall be included in\n'
  2211. 'all copies or substantial portions of the Software.\n\n'
  2212. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2213. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2214. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2215. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2216. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2217. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2218. 'THE SOFTWARE.'
  2219. )
  2220. )
  2221. attributions_label = QtWidgets.QLabel(
  2222. _(
  2223. 'Some of the icons used are from the following sources:<br>'
  2224. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2225. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2226. 'title="Flaticon">www.flaticon.com</a></div>'
  2227. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2228. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2229. )
  2230. )
  2231. attributions_label.setOpenExternalLinks(True)
  2232. # layouts
  2233. layout1 = QtWidgets.QVBoxLayout()
  2234. layout1_1 = QtWidgets.QHBoxLayout()
  2235. layout1_2 = QtWidgets.QHBoxLayout()
  2236. layout2 = QtWidgets.QHBoxLayout()
  2237. layout3 = QtWidgets.QHBoxLayout()
  2238. self.setLayout(layout1)
  2239. layout1.addLayout(layout1_1)
  2240. layout1.addLayout(layout1_2)
  2241. layout1.addLayout(layout2)
  2242. layout1.addLayout(layout3)
  2243. layout1_1.addStretch()
  2244. layout1_1.addWidget(description_label)
  2245. layout1_2.addWidget(tab_widget)
  2246. self.splash_tab = QtWidgets.QWidget()
  2247. self.splash_tab.setObjectName("splash_about")
  2248. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2249. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2250. tab_widget.addTab(self.splash_tab, _("Splash"))
  2251. self.programmmers_tab = QtWidgets.QWidget()
  2252. self.programmmers_tab.setObjectName("programmers_about")
  2253. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2254. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2255. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2256. self.translators_tab = QtWidgets.QWidget()
  2257. self.translators_tab.setObjectName("translators_about")
  2258. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2259. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2260. tab_widget.addTab(self.translators_tab, _("Translators"))
  2261. self.license_tab = QtWidgets.QWidget()
  2262. self.license_tab.setObjectName("license_about")
  2263. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2264. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2265. tab_widget.addTab(self.license_tab, _("License"))
  2266. self.attributions_tab = QtWidgets.QWidget()
  2267. self.attributions_tab.setObjectName("attributions_about")
  2268. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2269. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2270. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2271. self.splash_tab_layout.addWidget(logo, stretch=0)
  2272. self.splash_tab_layout.addWidget(title, stretch=1)
  2273. pal = QtGui.QPalette()
  2274. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2275. self.prog_grid_lay = QtWidgets.QGridLayout()
  2276. self.prog_grid_lay.setHorizontalSpacing(20)
  2277. self.prog_grid_lay.setColumnStretch(0, 0)
  2278. self.prog_grid_lay.setColumnStretch(2, 1)
  2279. prog_widget = QtWidgets.QWidget()
  2280. prog_widget.setLayout(self.prog_grid_lay)
  2281. prog_scroll = QtWidgets.QScrollArea()
  2282. prog_scroll.setWidget(prog_widget)
  2283. prog_scroll.setWidgetResizable(True)
  2284. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2285. prog_scroll.setPalette(pal)
  2286. self.programmmers_tab_layout.addWidget(prog_scroll)
  2287. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2288. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2289. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2290. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2291. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2292. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2293. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2294. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2295. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2296. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2297. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2298. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2299. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2300. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2301. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2302. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2303. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2304. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2315. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2317. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2318. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2319. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2320. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2321. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2322. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2323. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2325. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2328. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2330. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2332. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2333. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2334. self.translator_grid_lay = QtWidgets.QGridLayout()
  2335. self.translator_grid_lay.setColumnStretch(0, 0)
  2336. self.translator_grid_lay.setColumnStretch(1, 0)
  2337. self.translator_grid_lay.setColumnStretch(2, 1)
  2338. self.translator_grid_lay.setColumnStretch(3, 0)
  2339. # trans_widget = QtWidgets.QWidget()
  2340. # trans_widget.setLayout(self.translator_grid_lay)
  2341. # self.translators_tab_layout.addWidget(trans_widget)
  2342. # self.translators_tab_layout.addStretch()
  2343. trans_widget = QtWidgets.QWidget()
  2344. trans_widget.setLayout(self.translator_grid_lay)
  2345. trans_scroll = QtWidgets.QScrollArea()
  2346. trans_scroll.setWidget(trans_widget)
  2347. trans_scroll.setWidgetResizable(True)
  2348. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2349. trans_scroll.setPalette(pal)
  2350. self.translators_tab_layout.addWidget(trans_scroll)
  2351. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2352. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2353. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2354. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2355. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2356. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2357. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2358. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2359. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2360. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2361. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2362. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2363. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2364. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2365. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2366. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2367. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2368. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2369. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2370. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2371. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2372. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2373. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2374. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2375. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2376. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2377. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2378. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2379. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2380. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2381. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2382. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2383. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2384. self.translator_grid_lay.setColumnStretch(0, 0)
  2385. self.translators_tab_layout.addStretch()
  2386. self.license_tab_layout.addWidget(lic_lbl_header)
  2387. self.license_tab_layout.addWidget(lic_lbl_body)
  2388. self.license_tab_layout.addStretch()
  2389. self.attributions_tab_layout.addWidget(attributions_label)
  2390. self.attributions_tab_layout.addStretch()
  2391. layout3.addStretch()
  2392. layout3.addWidget(closebtn)
  2393. closebtn.clicked.connect(self.accept)
  2394. AboutDialog(app=self, parent=self.ui).exec_()
  2395. def on_readme(self):
  2396. class AboutDialog(QtWidgets.QDialog):
  2397. def __init__(self, app, parent=None):
  2398. QtWidgets.QDialog.__init__(self, parent)
  2399. self.app = app
  2400. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2401. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2402. "<b>new features</b></a>"
  2403. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>report bugs</b></a>"
  2404. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2405. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>donation</b></a>"
  2406. # Icon and title
  2407. self.setWindowIcon(parent.app_icon)
  2408. self.setWindowTitle(_("Important Information's"))
  2409. self.resize(720, 330)
  2410. logo = QtWidgets.QLabel()
  2411. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2412. content = QtWidgets.QLabel(
  2413. "This program is %s and free in a very wide meaning of the word.<br>"
  2414. "Yet it cannot evolve without <b>contributions</b>.<br><br>"
  2415. "If you want to see this application evolve and grow, or if you make money with it,<br>"
  2416. "you can <b>contribute</b> to the development yourself by:<br>"
  2417. "<ul>"
  2418. "<li>adding %s through a Pull Request on the Bitbucket repository</li>"
  2419. "<li>%s by providing the steps required to reproduce the bug</li>"
  2420. "<li>or by making a %s.</li>"
  2421. "</ul>"
  2422. "There are no strings attached.<br>"
  2423. "You don't have to make a %s, and it is totally optional but:"
  2424. "<ul>"
  2425. "<li>it will be welcomed with joy &#128077;</li>"
  2426. "<li>it will give me a reason to continue &#128513;</li>"
  2427. "</ul>" %
  2428. (open_source_link, new_features_link, bugs_link, donation_link, donation_link)
  2429. )
  2430. content.setOpenExternalLinks(True)
  2431. closebtn = QtWidgets.QPushButton(_("Close"))
  2432. # layouts
  2433. layout1 = QtWidgets.QVBoxLayout()
  2434. self.setLayout(layout1)
  2435. pal = QtGui.QPalette()
  2436. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2437. self.grid_lay = QtWidgets.QGridLayout()
  2438. self.grid_lay.setHorizontalSpacing(20)
  2439. self.grid_lay.setColumnStretch(0, 0)
  2440. self.grid_lay.setColumnStretch(1, 1)
  2441. content_widget = QtWidgets.QWidget()
  2442. content_widget.setLayout(self.grid_lay)
  2443. scroll_area = QtWidgets.QScrollArea()
  2444. scroll_area.setWidget(content_widget)
  2445. scroll_area.setWidgetResizable(True)
  2446. scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2447. scroll_area.setPalette(pal)
  2448. self.grid_lay.addWidget(logo, 0, 0)
  2449. self.grid_lay.addWidget(content, 0, 1)
  2450. layout1.addWidget(scroll_area)
  2451. layout2 = QtWidgets.QHBoxLayout()
  2452. layout1.addLayout(layout2)
  2453. layout2.addStretch()
  2454. layout2.addWidget(closebtn)
  2455. closebtn.clicked.connect(self.accept)
  2456. AboutDialog(app=self, parent=self.ui).exec_()
  2457. def install_bookmarks(self, book_dict=None):
  2458. """
  2459. Install the bookmarks actions in the Help menu -> Bookmarks
  2460. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2461. :return: None
  2462. """
  2463. if book_dict is None:
  2464. self.defaults["global_bookmarks"].update(
  2465. {
  2466. '1': ['FlatCAM', "http://flatcam.org"],
  2467. '2': ['Backup Site', ""]
  2468. }
  2469. )
  2470. else:
  2471. self.defaults["global_bookmarks"].clear()
  2472. self.defaults["global_bookmarks"].update(book_dict)
  2473. # first try to disconnect if somehow they get connected from elsewhere
  2474. for act in self.ui.menuhelp_bookmarks.actions():
  2475. try:
  2476. act.triggered.disconnect()
  2477. except TypeError:
  2478. pass
  2479. # clear all actions except the last one who is the Bookmark manager
  2480. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2481. pass
  2482. else:
  2483. self.ui.menuhelp_bookmarks.removeAction(act)
  2484. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2485. if self.defaults["global_bookmarks"]:
  2486. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2487. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2488. # the JSON is first making the keys as strings (therefore I have to use strings too
  2489. # or do the conversion :(
  2490. # )
  2491. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2492. # the '10' entry jsut after '1' therefore ordering as strings
  2493. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2494. key=lambda x: int(x[0]))
  2495. for entry, bookmark in sorted_bookmarks:
  2496. title = bookmark[0]
  2497. weblink = bookmark[1]
  2498. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2499. act.setText(title)
  2500. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2501. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2502. if title == 'Backup Site' and weblink == "":
  2503. act.triggered.connect(self.on_backup_site)
  2504. else:
  2505. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2506. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2507. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2508. def on_bookmarks_manager(self):
  2509. """
  2510. Adds the bookmark manager in a Tab in Plot Area
  2511. :return:
  2512. """
  2513. for idx in range(self.ui.plot_tab_area.count()):
  2514. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2515. # there can be only one instance of Bookmark Manager at one time
  2516. return
  2517. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2518. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2519. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2520. # add the tab if it was closed
  2521. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2522. # delete the absolute and relative position and messages in the infobar
  2523. self.ui.position_label.setText("")
  2524. # self.ui.rel_position_label.setText("")
  2525. # Switch plot_area to preferences page
  2526. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2527. def on_backup_site(self):
  2528. msgbox = QtWidgets.QMessageBox()
  2529. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2530. "1. FlatCAM.org website is down\n"
  2531. "2. Someone forked FlatCAM project and wants to point\n"
  2532. "to his own website\n\n"
  2533. "If you can't get any informations about FlatCAM beta\n"
  2534. "use the YouTube channel link from the Help menu."))
  2535. msgbox.setWindowTitle(_("Alternative website"))
  2536. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2537. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2538. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2539. msgbox.setDefaultButton(bt_yes)
  2540. msgbox.exec_()
  2541. # response = msgbox.clickedButton()
  2542. def on_file_savedefaults(self):
  2543. """
  2544. Callback for menu item File->Save Defaults. Saves application default options
  2545. ``self.defaults`` to current_defaults.FlatConfig.
  2546. :return: None
  2547. """
  2548. self.preferencesUiManager.save_defaults()
  2549. def final_save(self):
  2550. """
  2551. Callback for doing a preferences save to file whenever the application is about to quit.
  2552. If the project has changes, it will ask the user to save the project.
  2553. :return: None
  2554. """
  2555. if self.save_in_progress:
  2556. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2557. return
  2558. if self.should_we_save and self.collection.get_list():
  2559. msgbox = QtWidgets.QMessageBox()
  2560. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2561. "\n"
  2562. "Do you want to Save the project?"))
  2563. msgbox.setWindowTitle(_("Save changes"))
  2564. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2565. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2566. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2567. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2568. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2569. msgbox.setDefaultButton(bt_yes)
  2570. msgbox.exec_()
  2571. response = msgbox.clickedButton()
  2572. if response == bt_yes:
  2573. try:
  2574. self.trayIcon.hide()
  2575. except Exception:
  2576. pass
  2577. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2578. elif response == bt_no:
  2579. try:
  2580. self.trayIcon.hide()
  2581. except Exception:
  2582. pass
  2583. self.quit_application()
  2584. elif response == bt_cancel:
  2585. return
  2586. else:
  2587. try:
  2588. self.trayIcon.hide()
  2589. except Exception:
  2590. pass
  2591. self.quit_application()
  2592. def quit_application(self):
  2593. """
  2594. Called (as a pyslot or not) when the application is quit.
  2595. :return: None
  2596. """
  2597. self.preferencesUiManager.save_defaults(silent=True)
  2598. log.debug("App.quit_application() --> App Defaults saved.")
  2599. if self.cmd_line_headless != 1:
  2600. # save app state to file
  2601. stgs = QSettings("Open Source", "FlatCAM")
  2602. stgs.setValue('saved_gui_state', self.ui.saveState())
  2603. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2604. stgs.setValue(
  2605. 'language',
  2606. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2607. )
  2608. stgs.setValue(
  2609. 'notebook_font_size',
  2610. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2611. )
  2612. stgs.setValue(
  2613. 'axis_font_size',
  2614. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2615. )
  2616. stgs.setValue(
  2617. 'textbox_font_size',
  2618. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2619. )
  2620. stgs.setValue(
  2621. 'hud_font_size',
  2622. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2623. )
  2624. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2625. stgs.setValue(
  2626. 'machinist',
  2627. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2628. )
  2629. # This will write the setting to the platform specific storage.
  2630. del stgs
  2631. log.debug("App.quit_application() --> App UI state saved.")
  2632. # try to quit the Socket opened by ArgsThread class
  2633. try:
  2634. self.new_launch.stop.emit()
  2635. except Exception as err:
  2636. log.debug("App.quit_application() --> %s" % str(err))
  2637. # try to quit the QThread that run ArgsThread class
  2638. try:
  2639. self.th.quit()
  2640. except Exception as e:
  2641. log.debug("App.quit_application() --> %s" % str(e))
  2642. # terminate workers
  2643. self.workers.__del__()
  2644. # quit app by signalling for self.kill_app() method
  2645. # self.close_app_signal.emit()
  2646. QtWidgets.qApp.quit()
  2647. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2648. # we use the following command
  2649. minor_v = sys.version_info.minor
  2650. if minor_v < 8:
  2651. sys.exit(0)
  2652. else:
  2653. os._exit(0) # fix to work with Python 3.8
  2654. @staticmethod
  2655. def kill_app():
  2656. QtWidgets.qApp.quit()
  2657. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2658. # we use the following command
  2659. sys.exit(0)
  2660. def on_portable_checked(self, state):
  2661. """
  2662. Callback called when the checkbox in Preferences GUI is checked.
  2663. It will set the application as portable by creating the preferences and recent files in the
  2664. 'config' folder found in the FlatCAM installation folder.
  2665. :param state: boolean, the state of the checkbox when clicked/checked
  2666. :return:
  2667. """
  2668. line_no = 0
  2669. data = None
  2670. if sys.platform != 'win32':
  2671. # this won't work in Linux or MacOS
  2672. return
  2673. # test if the app was frozen and choose the path for the configuration file
  2674. if getattr(sys, "frozen", False) is True:
  2675. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2676. else:
  2677. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2678. config_file = current_data_path + '\\configuration.txt'
  2679. try:
  2680. with open(config_file, 'r') as f:
  2681. try:
  2682. data = f.readlines()
  2683. except Exception as e:
  2684. log.debug('App.__init__() -->%s' % str(e))
  2685. return
  2686. except FileNotFoundError:
  2687. pass
  2688. for line in data:
  2689. line = line.strip('\n')
  2690. param = str(line).rpartition('=')
  2691. if param[0] == 'portable':
  2692. break
  2693. line_no += 1
  2694. if state:
  2695. data[line_no] = 'portable=True\n'
  2696. # create the new defauults files
  2697. # create current_defaults.FlatConfig file if there is none
  2698. try:
  2699. f = open(current_data_path + '/current_defaults.FlatConfig')
  2700. f.close()
  2701. except IOError:
  2702. App.log.debug('Creating empty current_defaults.FlatConfig')
  2703. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2704. json.dump({}, f)
  2705. f.close()
  2706. # create factory_defaults.FlatConfig file if there is none
  2707. try:
  2708. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2709. f.close()
  2710. except IOError:
  2711. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2712. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2713. json.dump({}, f)
  2714. f.close()
  2715. try:
  2716. f = open(current_data_path + '/recent.json')
  2717. f.close()
  2718. except IOError:
  2719. App.log.debug('Creating empty recent.json')
  2720. f = open(current_data_path + '/recent.json', 'w')
  2721. json.dump([], f)
  2722. f.close()
  2723. try:
  2724. fp = open(current_data_path + '/recent_projects.json')
  2725. fp.close()
  2726. except IOError:
  2727. App.log.debug('Creating empty recent_projects.json')
  2728. fp = open(current_data_path + '/recent_projects.json', 'w')
  2729. json.dump([], fp)
  2730. fp.close()
  2731. # save the current defaults to the new defaults file
  2732. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2733. else:
  2734. data[line_no] = 'portable=False\n'
  2735. with open(config_file, 'w') as f:
  2736. f.writelines(data)
  2737. def on_register_files(self, obj_type=None):
  2738. """
  2739. Called whenever there is a need to register file extensions with FlatCAM.
  2740. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2741. :param obj_type: the type of object to be register for.
  2742. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2743. :return: None
  2744. """
  2745. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2746. new_reg_path = 'Software\\Classes\\'
  2747. # find if the current user is admin
  2748. try:
  2749. is_admin = os.getuid() == 0
  2750. except AttributeError:
  2751. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2752. if is_admin is True:
  2753. root_path = winreg.HKEY_LOCAL_MACHINE
  2754. else:
  2755. root_path = winreg.HKEY_CURRENT_USER
  2756. # create the keys
  2757. def set_reg(name, root_pth, new_reg_path, value):
  2758. try:
  2759. winreg.CreateKey(root_pth, new_reg_path)
  2760. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2761. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2762. return True
  2763. except WindowsError:
  2764. return False
  2765. # delete key in registry
  2766. def delete_reg(root_pth, reg_path, key_to_del):
  2767. key_to_del_path = reg_path + key_to_del
  2768. try:
  2769. winreg.DeleteKey(root_pth, key_to_del_path)
  2770. return True
  2771. except WindowsError:
  2772. return False
  2773. if obj_type is None or obj_type == 'excellon':
  2774. exc_list = \
  2775. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2776. exc_list = [x for x in exc_list if x != '']
  2777. # register all keys in the Preferences window
  2778. for ext in exc_list:
  2779. new_k = new_reg_path + '.%s' % ext
  2780. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2781. # and unregister those that are no longer in the Preferences windows but are in the file
  2782. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2783. if ext not in exc_list:
  2784. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2785. # now write the updated extensions to the self.defaults
  2786. # new_ext = ''
  2787. # for ext in exc_list:
  2788. # new_ext = new_ext + ext + ', '
  2789. # self.defaults["fa_excellon"] = new_ext
  2790. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2791. if obj_type is None or obj_type == 'gcode':
  2792. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2793. gco_list = [x for x in gco_list if x != '']
  2794. # register all keys in the Preferences window
  2795. for ext in gco_list:
  2796. new_k = new_reg_path + '.%s' % ext
  2797. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2798. # and unregister those that are no longer in the Preferences windows but are in the file
  2799. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2800. if ext not in gco_list:
  2801. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2802. # now write the updated extensions to the self.defaults
  2803. # new_ext = ''
  2804. # for ext in gco_list:
  2805. # new_ext = new_ext + ext + ', '
  2806. # self.defaults["fa_gcode"] = new_ext
  2807. self.inform.emit('[success] %s' %
  2808. _("Selected GCode file extensions registered with FlatCAM."))
  2809. if obj_type is None or obj_type == 'gerber':
  2810. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2811. grb_list = [x for x in grb_list if x != '']
  2812. # register all keys in the Preferences window
  2813. for ext in grb_list:
  2814. new_k = new_reg_path + '.%s' % ext
  2815. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2816. # and unregister those that are no longer in the Preferences windows but are in the file
  2817. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2818. if ext not in grb_list:
  2819. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2820. # now write the updated extensions to the self.defaults
  2821. # new_ext = ''
  2822. # for ext in grb_list:
  2823. # new_ext = new_ext + ext + ', '
  2824. # self.defaults["fa_gerber"] = new_ext
  2825. self.inform.emit('[success] %s' %
  2826. _("Selected Gerber file extensions registered with FlatCAM."))
  2827. def add_extension(self, ext_type):
  2828. """
  2829. Add a file extension to the list for a specific object
  2830. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2831. :return:
  2832. """
  2833. if ext_type == 'excellon':
  2834. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2835. if new_ext == '':
  2836. return
  2837. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2838. if new_ext in old_val:
  2839. return
  2840. old_val.append(new_ext)
  2841. old_val.sort()
  2842. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2843. if ext_type == 'gcode':
  2844. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2845. if new_ext == '':
  2846. return
  2847. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2848. if new_ext in old_val:
  2849. return
  2850. old_val.append(new_ext)
  2851. old_val.sort()
  2852. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2853. if ext_type == 'gerber':
  2854. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2855. if new_ext == '':
  2856. return
  2857. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2858. if new_ext in old_val:
  2859. return
  2860. old_val.append(new_ext)
  2861. old_val.sort()
  2862. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2863. if ext_type == 'keyword':
  2864. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2865. if new_kw == '':
  2866. return
  2867. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2868. if new_kw in old_val:
  2869. return
  2870. old_val.append(new_kw)
  2871. old_val.sort()
  2872. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2873. # update the self.myKeywords so the model is updated
  2874. self.autocomplete_kw_list = \
  2875. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2876. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2877. self.shell._edit.set_model_data(self.myKeywords)
  2878. def del_extension(self, ext_type):
  2879. """
  2880. Remove a file extension from the list for a specific object
  2881. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2882. :return:
  2883. """
  2884. if ext_type == 'excellon':
  2885. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2886. if new_ext == '':
  2887. return
  2888. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2889. if new_ext not in old_val:
  2890. return
  2891. old_val.remove(new_ext)
  2892. old_val.sort()
  2893. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2894. if ext_type == 'gcode':
  2895. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2896. if new_ext == '':
  2897. return
  2898. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2899. if new_ext not in old_val:
  2900. return
  2901. old_val.remove(new_ext)
  2902. old_val.sort()
  2903. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2904. if ext_type == 'gerber':
  2905. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2906. if new_ext == '':
  2907. return
  2908. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2909. if new_ext not in old_val:
  2910. return
  2911. old_val.remove(new_ext)
  2912. old_val.sort()
  2913. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2914. if ext_type == 'keyword':
  2915. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2916. if new_kw == '':
  2917. return
  2918. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2919. if new_kw not in old_val:
  2920. return
  2921. old_val.remove(new_kw)
  2922. old_val.sort()
  2923. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2924. # update the self.myKeywords so the model is updated
  2925. self.autocomplete_kw_list = \
  2926. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2927. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2928. self.shell._edit.set_model_data(self.myKeywords)
  2929. def restore_extensions(self, ext_type):
  2930. """
  2931. Restore all file extensions associations with FlatCAM, for a specific object
  2932. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2933. :return:
  2934. """
  2935. if ext_type == 'excellon':
  2936. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  2937. # for the ability to open Excellon files with .txt extension
  2938. new_exc_list = deepcopy(self.exc_list)
  2939. try:
  2940. new_exc_list.remove('txt')
  2941. except ValueError:
  2942. pass
  2943. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  2944. if ext_type == 'gcode':
  2945. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  2946. if ext_type == 'gerber':
  2947. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  2948. if ext_type == 'keyword':
  2949. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  2950. # update the self.myKeywords so the model is updated
  2951. self.autocomplete_kw_list = self.default_keywords
  2952. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2953. self.shell._edit.set_model_data(self.myKeywords)
  2954. def delete_all_extensions(self, ext_type):
  2955. """
  2956. Delete all file extensions associations with FlatCAM, for a specific object
  2957. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2958. :return:
  2959. """
  2960. if ext_type == 'excellon':
  2961. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  2962. if ext_type == 'gcode':
  2963. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  2964. if ext_type == 'gerber':
  2965. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  2966. if ext_type == 'keyword':
  2967. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  2968. # update the self.myKeywords so the model is updated
  2969. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  2970. self.shell._edit.set_model_data(self.myKeywords)
  2971. def on_edit_join(self, name=None):
  2972. """
  2973. Callback for Edit->Join. Joins the selected geometry objects into
  2974. a new one.
  2975. :return: None
  2976. """
  2977. self.defaults.report_usage("on_edit_join()")
  2978. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2979. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2980. geo_type_set = set()
  2981. objs = self.collection.get_selected()
  2982. if len(objs) < 2:
  2983. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2984. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2985. return 'fail'
  2986. for obj in objs:
  2987. geo_type_set.add(obj.multigeo)
  2988. # if len(geo_type_list) == 1 means that all list elements are the same
  2989. if len(geo_type_set) != 1:
  2990. self.inform.emit('[ERROR] %s' %
  2991. _("Failed join. The Geometry objects are of different types.\n"
  2992. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2993. "convert from one to another and retry joining \n"
  2994. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2995. "the result may not be what was expected. \n"
  2996. "Check the generated GCODE."))
  2997. return
  2998. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2999. if True in geo_type_set:
  3000. def initialize(geo_obj, app):
  3001. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3002. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3003. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3004. for v in geo_obj.tools.values():
  3005. v['data']['name'] = obj_name_multi
  3006. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3007. else:
  3008. def initialize(geo_obj, app):
  3009. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3010. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3011. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3012. for v in geo_obj.tools.values():
  3013. v['data']['name'] = obj_name_single
  3014. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3015. self.should_we_save = True
  3016. def on_edit_join_exc(self):
  3017. """
  3018. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3019. a new Excellon.
  3020. :return: None
  3021. """
  3022. self.defaults.report_usage("on_edit_join_exc()")
  3023. objs = self.collection.get_selected()
  3024. for obj in objs:
  3025. if not isinstance(obj, ExcellonObject):
  3026. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3027. return
  3028. if len(objs) < 2:
  3029. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3030. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3031. return 'fail'
  3032. def initialize(exc_obj, app):
  3033. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3034. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3035. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3036. self.should_we_save = True
  3037. def on_edit_join_grb(self):
  3038. """
  3039. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3040. a new Gerber object.
  3041. :return: None
  3042. """
  3043. self.defaults.report_usage("on_edit_join_grb()")
  3044. objs = self.collection.get_selected()
  3045. for obj in objs:
  3046. if not isinstance(obj, GerberObject):
  3047. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3048. return
  3049. if len(objs) < 2:
  3050. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3051. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3052. return 'fail'
  3053. def initialize(grb_obj, app):
  3054. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3055. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3056. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3057. self.should_we_save = True
  3058. def on_convert_singlegeo_to_multigeo(self):
  3059. """
  3060. Called for converting a Geometry object from single-geo to multi-geo.
  3061. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3062. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3063. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3064. the solid-geometry of that tool.
  3065. :return: None
  3066. """
  3067. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3068. obj = self.collection.get_active()
  3069. if obj is None:
  3070. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3071. return
  3072. if not isinstance(obj, GeometryObject):
  3073. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3074. return
  3075. obj.multigeo = True
  3076. for tooluid, dict_value in obj.tools.items():
  3077. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3078. if not isinstance(obj.solid_geometry, list):
  3079. obj.solid_geometry = [obj.solid_geometry]
  3080. # obj.solid_geometry[:] = []
  3081. obj.plot()
  3082. self.should_we_save = True
  3083. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3084. def on_convert_multigeo_to_singlegeo(self):
  3085. """
  3086. Called for converting a Geometry object from multi-geo to single-geo.
  3087. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3088. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3089. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3090. the solid-geometry of that tool.
  3091. :return: None
  3092. """
  3093. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3094. obj = self.collection.get_active()
  3095. if obj is None:
  3096. self.inform.emit('[ERROR_NOTCL] %s' %
  3097. _("Failed. Select a Geometry Object and try again."))
  3098. return
  3099. if not isinstance(obj, GeometryObject):
  3100. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3101. (_("Expected a GeometryObject, got"), type(obj)))
  3102. return
  3103. obj.multigeo = False
  3104. total_solid_geometry = []
  3105. for tooluid, dict_value in obj.tools.items():
  3106. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3107. # clear the original geometry
  3108. dict_value['solid_geometry'][:] = []
  3109. obj.solid_geometry = deepcopy(total_solid_geometry)
  3110. obj.plot()
  3111. self.should_we_save = True
  3112. self.inform.emit('[success] %s' %
  3113. _("A Geometry object was converted to SingleGeo type."))
  3114. def on_defaults_dict_change(self, field):
  3115. """
  3116. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3117. Edit -> Preferences tab window.
  3118. :param field: the key of the self.defaults dictionary that was changed.
  3119. :return: None
  3120. """
  3121. self.preferencesUiManager.defaults_write_form_field(field=field)
  3122. if field == "units":
  3123. self.set_screen_units(self.defaults['units'])
  3124. def set_screen_units(self, units):
  3125. """
  3126. Set the FlatCAM units on the status bar.
  3127. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3128. :return: None
  3129. """
  3130. self.ui.units_label.setText("[" + units.lower() + "]")
  3131. def on_toggle_units_click(self):
  3132. try:
  3133. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3134. except (TypeError, AttributeError):
  3135. pass
  3136. if self.defaults["units"] == 'MM':
  3137. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3138. else:
  3139. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3140. self.on_toggle_units(no_pref=True)
  3141. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3142. lambda: self.on_toggle_units(no_pref=False))
  3143. def on_toggle_units(self, no_pref=False):
  3144. """
  3145. Callback for the Units radio-button change in the Preferences tab.
  3146. Changes the application's default units adn for the project too.
  3147. If changing the project's units, the change propagates to all of
  3148. the objects in the project.
  3149. :return: None
  3150. """
  3151. self.defaults.report_usage("on_toggle_units")
  3152. if self.toggle_units_ignore:
  3153. return
  3154. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3155. # If option is the same, then ignore
  3156. if new_units == self.defaults["units"].upper():
  3157. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3158. return
  3159. # Keys in self.defaults for which to scale their values
  3160. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3161. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3162. "tools_iso_tool_vtipdia",
  3163. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3164. "gerber_editor_ma_high",
  3165. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3166. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3167. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3168. "excellon_feedrate_probe", "excellon_milling_dia",
  3169. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3170. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3171. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3172. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3173. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3174. "geometry_extracut_length", "geometry_z_pdepth",
  3175. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3176. 'cncjob_tooldia',
  3177. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3178. "tools_paintnewdia",
  3179. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3180. "tools_nccnewdia", "tools_ncc_offset_value",
  3181. "tools_2sided_drilldia",
  3182. "tools_film_boundary", "tools_film_scale_stroke",
  3183. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3184. "tools_cutout_depthperpass",
  3185. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3186. "tools_panelize_spacing_rows",
  3187. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3188. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3189. "tools_transform_buffer_dis",
  3190. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3191. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3192. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3193. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3194. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3195. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3196. "tools_cr_h2h_val", "tools_cr_dh_val",
  3197. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3198. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3199. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3200. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3201. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3202. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3203. "tools_copper_thieving_mask_clearance",
  3204. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3205. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3206. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3207. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3208. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3209. "tools_invert_margin",
  3210. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3211. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3212. def scale_defaults(sfactor):
  3213. for dim in dimensions:
  3214. if dim in [
  3215. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3216. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3217. 'tools_transform_mirror_point'
  3218. ]:
  3219. if self.defaults[dim] is None or self.defaults[dim] == '':
  3220. continue
  3221. try:
  3222. coordinates = self.defaults[dim].split(",")
  3223. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3224. coords_xy[0] *= sfactor
  3225. coords_xy[1] *= sfactor
  3226. self.defaults[dim] = "%.*f, %.*f" % (
  3227. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3228. except Exception as e:
  3229. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3230. elif dim in [
  3231. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3232. ]:
  3233. if self.defaults[dim] is None or self.defaults[dim] == '':
  3234. continue
  3235. try:
  3236. self.defaults[dim] = float(self.defaults[dim])
  3237. tools_diameters = [self.defaults[dim]]
  3238. except ValueError:
  3239. try:
  3240. tools_string = self.defaults[dim].split(",")
  3241. tools_diameters = [eval(a) for a in tools_string if a != '']
  3242. except Exception as e:
  3243. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3244. continue
  3245. self.defaults[dim] = ''
  3246. td_len = len(tools_diameters)
  3247. if td_len > 1:
  3248. for t in range(td_len):
  3249. tools_diameters[t] *= sfactor
  3250. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3251. else:
  3252. tools_diameters[0] *= sfactor
  3253. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3254. elif dim in ['global_gridx', 'global_gridy']:
  3255. # format the number of decimals to the one specified in self.decimals
  3256. try:
  3257. val = float(self.defaults[dim]) * sfactor
  3258. except Exception as e:
  3259. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3260. continue
  3261. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3262. else:
  3263. # the number of decimals for the rest is kept unchanged
  3264. if self.defaults[dim]:
  3265. try:
  3266. val = float(self.defaults[dim]) * sfactor
  3267. except Exception as e:
  3268. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3269. continue
  3270. self.defaults[dim] = val
  3271. # The scaling factor depending on choice of units.
  3272. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3273. # Changing project units. Warn user.
  3274. msgbox = QtWidgets.QMessageBox()
  3275. msgbox.setWindowTitle(_("Toggle Units"))
  3276. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3277. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3278. msgbox.setText(_("Changing the units of the project\n"
  3279. "will scale all objects.\n\n"
  3280. "Do you want to continue?"))
  3281. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3282. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3283. msgbox.setDefaultButton(bt_ok)
  3284. msgbox.exec_()
  3285. response = msgbox.clickedButton()
  3286. if response == bt_ok:
  3287. if no_pref is False:
  3288. self.preferencesUiManager.defaults_read_form()
  3289. scale_defaults(factor)
  3290. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3291. self.defaults["units"] = new_units
  3292. # update the defaults from form, some may assume that the conversion is enough and it's not
  3293. self.on_options_app2project()
  3294. # update the objects
  3295. for obj in self.collection.get_list():
  3296. obj.convert_units(new_units)
  3297. # make that the properties stored in the object are also updated
  3298. self.app_obj.object_changed.emit(obj)
  3299. # rebuild the object UI
  3300. obj.build_ui()
  3301. # change this only if the workspace is active
  3302. if self.defaults['global_workspace'] is True:
  3303. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3304. # adjust the grid values on the main toolbar
  3305. val_x = float(self.defaults['global_gridx']) * factor
  3306. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3307. current = self.collection.get_active()
  3308. if current is not None:
  3309. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3310. if not isinstance(current, GeometryObject):
  3311. current.to_form()
  3312. # replot all objects
  3313. self.plot_all()
  3314. # set the status labels to reflect the current FlatCAM units
  3315. self.set_screen_units(new_units)
  3316. # signal to the app that we changed the object properties and it should save the project
  3317. self.should_we_save = True
  3318. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3319. else:
  3320. # Undo toggling
  3321. self.toggle_units_ignore = True
  3322. if self.defaults['units'].upper() == 'MM':
  3323. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3324. else:
  3325. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3326. self.toggle_units_ignore = False
  3327. # store the grid values so they are not changed in the next step
  3328. val_x = float(self.defaults['global_gridx'])
  3329. val_y = float(self.defaults['global_gridy'])
  3330. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3331. self.preferencesUiManager.defaults_read_form()
  3332. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3333. # in self.defaults from the GUI elements but
  3334. # I don't want it for the grid values, so I update them here
  3335. self.defaults['global_gridx'] = val_x
  3336. self.defaults['global_gridy'] = val_y
  3337. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3338. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3339. def on_tab_rmb_click(self, checked):
  3340. self.ui.notebook.set_detachable(val=checked)
  3341. self.defaults["global_tabs_detachable"] = checked
  3342. self.ui.plot_tab_area.set_detachable(val=checked)
  3343. self.defaults["global_tabs_detachable"] = checked
  3344. def on_tab_setup_context_menu(self):
  3345. initial_checked = self.defaults["global_tabs_detachable"]
  3346. action_name = str(_("Detachable Tabs"))
  3347. action = QtWidgets.QAction(self)
  3348. action.setCheckable(True)
  3349. action.setText(action_name)
  3350. action.setChecked(initial_checked)
  3351. self.ui.notebook.tabBar.addAction(action)
  3352. self.ui.plot_tab_area.tabBar.addAction(action)
  3353. try:
  3354. action.triggered.disconnect()
  3355. except TypeError:
  3356. pass
  3357. action.triggered.connect(self.on_tab_rmb_click)
  3358. def on_deselect_all(self):
  3359. self.collection.set_all_inactive()
  3360. self.delete_selection_shape()
  3361. def on_workspace_modified(self):
  3362. # self.save_defaults(silent=True)
  3363. self.plotcanvas.delete_workspace()
  3364. self.preferencesUiManager.defaults_read_form()
  3365. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3366. def on_workspace(self):
  3367. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3368. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3369. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3370. else:
  3371. self.plotcanvas.delete_workspace()
  3372. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3373. self.preferencesUiManager.defaults_read_form()
  3374. # self.save_defaults(silent=True)
  3375. def on_workspace_toggle(self):
  3376. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3377. try:
  3378. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3379. except TypeError:
  3380. pass
  3381. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3382. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3383. self.on_workspace()
  3384. def on_cursor_type(self, val):
  3385. """
  3386. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3387. :return: None
  3388. """
  3389. self.app_cursor.enabled = False
  3390. if val == 'small':
  3391. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3392. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3393. self.app_cursor = self.plotcanvas.new_cursor()
  3394. else:
  3395. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3396. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3397. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3398. if self.ui.grid_snap_btn.isChecked():
  3399. self.app_cursor.enabled = True
  3400. else:
  3401. self.app_cursor.enabled = False
  3402. def on_tool_add_keypress(self):
  3403. # ## Current application units in Upper Case
  3404. self.units = self.defaults['units'].upper()
  3405. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3406. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3407. if notebook_widget_name == 'selected_tab':
  3408. if self.collection.get_active().kind == 'geometry':
  3409. # Tool add works for Geometry only if Advanced is True in Preferences
  3410. if self.defaults["global_app_level"] == 'a':
  3411. tool_add_popup = FCInputDialog(title="New Tool ...",
  3412. text='Enter a Tool Diameter:',
  3413. min=0.0000, max=99.9999, decimals=4)
  3414. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3415. val, ok = tool_add_popup.get_value()
  3416. if ok:
  3417. if float(val) == 0:
  3418. self.inform.emit('[WARNING_NOTCL] %s' %
  3419. _("Please enter a tool diameter with non-zero value, in Float format."))
  3420. return
  3421. self.collection.get_active().on_tool_add(dia=float(val))
  3422. else:
  3423. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3424. else:
  3425. msgbox = QtWidgets.QMessageBox()
  3426. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3427. "Go to Preferences -> General - Show Advanced Options."))
  3428. msgbox.setWindowTitle("Tool adding ...")
  3429. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3430. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3431. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3432. msgbox.setDefaultButton(bt_ok)
  3433. msgbox.exec_()
  3434. # work only if the notebook tab on focus is the Tools_Tab
  3435. if notebook_widget_name == 'tool_tab':
  3436. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3437. # and only if the tool is NCC Tool
  3438. if tool_widget == self.ncclear_tool.toolName:
  3439. self.ncclear_tool.on_add_tool_by_key()
  3440. # and only if the tool is Paint Area Tool
  3441. elif tool_widget == self.paint_tool.toolName:
  3442. self.paint_tool.on_add_tool_by_key()
  3443. # and only if the tool is Solder Paste Dispensing Tool
  3444. elif tool_widget == self.paste_tool.toolName:
  3445. self.paste_tool.on_add_tool_by_key()
  3446. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3447. # See description below.
  3448. def on_delete_keypress(self):
  3449. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3450. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3451. if notebook_widget_name == 'selected_tab':
  3452. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3453. self.collection.get_active().on_tool_delete()
  3454. # work only if the notebook tab on focus is the Tools_Tab
  3455. elif notebook_widget_name == 'tool_tab':
  3456. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3457. # and only if the tool is NCC Tool
  3458. if tool_widget == self.ncclear_tool.toolName:
  3459. self.ncclear_tool.on_tool_delete()
  3460. # and only if the tool is Paint Tool
  3461. elif tool_widget == self.paint_tool.toolName:
  3462. self.paint_tool.on_tool_delete()
  3463. # and only if the tool is Solder Paste Dispensing Tool
  3464. elif tool_widget == self.paste_tool.toolName:
  3465. self.paste_tool.on_tool_delete()
  3466. # and only if the tool is Isolation Tool
  3467. elif tool_widget == self.isolation_tool.toolName:
  3468. self.isolation_tool.on_tool_delete()
  3469. else:
  3470. self.on_delete()
  3471. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3472. # some screens you have to be careful where you hover with your mouse.
  3473. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3474. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3475. # Complicated, I know :)
  3476. def on_delete(self, force_deletion=False):
  3477. """
  3478. Delete the currently selected FlatCAMObjs.
  3479. :param force_deletion: used by Tcl command
  3480. :return: None
  3481. """
  3482. self.defaults.report_usage("on_delete()")
  3483. response = None
  3484. bt_ok = None
  3485. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3486. # a geometry object before we update it.
  3487. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3488. and self.grb_editor.editor_active is False:
  3489. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3490. msgbox = QtWidgets.QMessageBox()
  3491. msgbox.setWindowTitle(_("Delete objects"))
  3492. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3493. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3494. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3495. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3496. "the selected objects?"))
  3497. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3498. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3499. msgbox.setDefaultButton(bt_ok)
  3500. msgbox.exec_()
  3501. response = msgbox.clickedButton()
  3502. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3503. response = bt_ok
  3504. if response == bt_ok:
  3505. if self.collection.get_active():
  3506. self.log.debug("App.on_delete()")
  3507. for obj_active in self.collection.get_selected():
  3508. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3509. if obj_active.kind == 'gerber':
  3510. for el in obj_active.mark_shapes:
  3511. obj_active.mark_shapes[el].clear(update=True)
  3512. obj_active.mark_shapes[el].enabled = False
  3513. # obj_active.mark_shapes[el] = None
  3514. del el
  3515. elif obj_active.kind == 'cncjob':
  3516. try:
  3517. obj_active.text_col.enabled = False
  3518. del obj_active.text_col
  3519. obj_active.annotation.clear(update=True)
  3520. del obj_active.annotation
  3521. except AttributeError as e:
  3522. log.debug(
  3523. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3524. )
  3525. while self.collection.get_selected():
  3526. self.delete_first_selected()
  3527. # make sure that the selection shape is deleted, too
  3528. self.delete_selection_shape()
  3529. # if there are no longer objects delete also the exclusion areas shapes
  3530. if not self.collection.get_list():
  3531. self.exc_areas.clear_shapes()
  3532. self.inform.emit('%s...' % _("Object(s) deleted"))
  3533. else:
  3534. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3535. else:
  3536. self.inform.emit(_("Save the work in Editor and try again ..."))
  3537. def delete_first_selected(self):
  3538. # Keep this for later
  3539. try:
  3540. sel_obj = self.collection.get_active()
  3541. name = sel_obj.options["name"]
  3542. isPlotted = sel_obj.options["plot"]
  3543. except AttributeError:
  3544. self.log.debug("Nothing selected for deletion")
  3545. return
  3546. if self.is_legacy is True:
  3547. # Remove plot only if the object was plotted otherwise delaxes will fail
  3548. if isPlotted:
  3549. try:
  3550. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3551. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3552. except Exception as e:
  3553. log.debug("App.delete_first_selected() --> %s" % str(e))
  3554. self.plotcanvas.auto_adjust_axes()
  3555. # Remove from dictionary
  3556. self.collection.delete_active()
  3557. # Clear form
  3558. self.setup_component_editor()
  3559. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3560. def on_set_origin(self):
  3561. """
  3562. Set the origin to the left mouse click position
  3563. :return: None
  3564. """
  3565. # display the message for the user
  3566. # and ask him to click on the desired position
  3567. self.defaults.report_usage("on_set_origin()")
  3568. def origin_replot():
  3569. def worker_task():
  3570. with self.proc_container.new('%s...' % _("Plotting")):
  3571. for obj in self.collection.get_list():
  3572. obj.plot()
  3573. self.plotcanvas.fit_view()
  3574. if self.is_legacy:
  3575. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3576. else:
  3577. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3578. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3579. self.inform.emit(_('Click to set the origin ...'))
  3580. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3581. # first disconnect it as it may have been used by something else
  3582. try:
  3583. self.replot_signal.disconnect()
  3584. except TypeError:
  3585. pass
  3586. self.replot_signal[list].connect(origin_replot)
  3587. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3588. """
  3589. :param event:
  3590. :param location:
  3591. :param noplot:
  3592. :param use_thread:
  3593. :return:
  3594. """
  3595. noplot_sig = noplot
  3596. def worker_task():
  3597. with self.proc_container.new(_("Setting Origin...")):
  3598. obj_list = self.collection.get_list()
  3599. for obj in obj_list:
  3600. obj.offset((x, y))
  3601. self.app_obj.object_changed.emit(obj)
  3602. # Update the object bounding box options
  3603. a, b, c, d = obj.bounds()
  3604. obj.options['xmin'] = a
  3605. obj.options['ymin'] = b
  3606. obj.options['xmax'] = c
  3607. obj.options['ymax'] = d
  3608. self.inform.emit('[success] %s...' % _('Origin set'))
  3609. for obj in obj_list:
  3610. out_name = obj.options["name"]
  3611. if obj.kind == 'gerber':
  3612. obj.source_file = self.export_gerber(
  3613. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3614. elif obj.kind == 'excellon':
  3615. obj.source_file = self.export_excellon(
  3616. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3617. if noplot_sig is False:
  3618. self.replot_signal.emit([])
  3619. if location is not None:
  3620. if len(location) != 2:
  3621. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3622. return 'fail'
  3623. x, y = location
  3624. if use_thread is True:
  3625. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3626. else:
  3627. worker_task()
  3628. self.should_we_save = True
  3629. return
  3630. if event is not None and event.button == 1:
  3631. if self.is_legacy is False:
  3632. event_pos = event.pos
  3633. else:
  3634. event_pos = (event.xdata, event.ydata)
  3635. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3636. if self.grid_status():
  3637. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3638. else:
  3639. pos = pos_canvas
  3640. x = 0 - pos[0]
  3641. y = 0 - pos[1]
  3642. if use_thread is True:
  3643. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3644. else:
  3645. worker_task()
  3646. self.should_we_save = True
  3647. def on_move2origin(self, use_thread=True):
  3648. """
  3649. Move selected objects to origin.
  3650. :param use_thread: Control if to use threaded operation. Boolean.
  3651. :return:
  3652. """
  3653. def worker_task():
  3654. with self.proc_container.new(_("Moving to Origin...")):
  3655. obj_list = self.collection.get_selected()
  3656. if not obj_list:
  3657. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3658. return
  3659. xminlist = []
  3660. yminlist = []
  3661. # first get a bounding box to fit all
  3662. for obj in obj_list:
  3663. xmin, ymin, xmax, ymax = obj.bounds()
  3664. xminlist.append(xmin)
  3665. yminlist.append(ymin)
  3666. # get the minimum x,y for all objects selected
  3667. x = min(xminlist)
  3668. y = min(yminlist)
  3669. for obj in obj_list:
  3670. obj.offset((-x, -y))
  3671. self.app_obj.object_changed.emit(obj)
  3672. # Update the object bounding box options
  3673. a, b, c, d = obj.bounds()
  3674. obj.options['xmin'] = a
  3675. obj.options['ymin'] = b
  3676. obj.options['xmax'] = c
  3677. obj.options['ymax'] = d
  3678. for obj in obj_list:
  3679. obj.plot()
  3680. for obj in obj_list:
  3681. out_name = obj.options["name"]
  3682. if obj.kind == 'gerber':
  3683. obj.source_file = self.export_gerber(
  3684. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3685. elif obj.kind == 'excellon':
  3686. obj.source_file = self.export_excellon(
  3687. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3688. self.inform.emit('[success] %s...' % _('Origin set'))
  3689. if use_thread is True:
  3690. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3691. else:
  3692. worker_task()
  3693. self.should_we_save = True
  3694. def on_jump_to(self, custom_location=None, fit_center=True):
  3695. """
  3696. Jump to a location by setting the mouse cursor location.
  3697. :param custom_location: Jump to a specified point. (x, y) tuple.
  3698. :param fit_center: If to fit view. Boolean.
  3699. :return:
  3700. """
  3701. self.defaults.report_usage("on_jump_to()")
  3702. if not custom_location:
  3703. dia_box_location = None
  3704. try:
  3705. dia_box_location = eval(self.clipboard.text())
  3706. except Exception:
  3707. pass
  3708. if type(dia_box_location) == tuple:
  3709. dia_box_location = str(dia_box_location)
  3710. else:
  3711. dia_box_location = None
  3712. # dia_box = Dialog_box(title=_("Jump to ..."),
  3713. # label=_("Enter the coordinates in format X,Y:"),
  3714. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3715. # initial_text=dia_box_location)
  3716. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3717. label=_("Enter the coordinates in format X,Y:"),
  3718. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3719. initial_text=dia_box_location,
  3720. reference=self.defaults['global_jump_ref'])
  3721. if dia_box.ok is True:
  3722. try:
  3723. location = eval(dia_box.location)
  3724. if not isinstance(location, tuple):
  3725. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3726. return
  3727. if dia_box.reference == 'rel':
  3728. rel_x = self.mouse[0] + location[0]
  3729. rel_y = self.mouse[1] + location[1]
  3730. location = (rel_x, rel_y)
  3731. self.defaults['global_jump_ref'] = dia_box.reference
  3732. except Exception:
  3733. return
  3734. else:
  3735. return
  3736. else:
  3737. location = custom_location
  3738. self.jump_signal.emit(location)
  3739. if fit_center:
  3740. self.plotcanvas.fit_center(loc=location)
  3741. cursor = QtGui.QCursor()
  3742. if self.is_legacy is False:
  3743. # I don't know where those differences come from but they are constant for the current
  3744. # execution of the application and they are multiples of a value around 0.0263mm.
  3745. # In a random way sometimes they are more sometimes they are less
  3746. # if units == 'MM':
  3747. # cal_factor = 0.0263
  3748. # else:
  3749. # cal_factor = 0.0263 / 25.4
  3750. cal_location = (location[0], location[1])
  3751. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3752. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3753. j_pos = (
  3754. int(canvas_origin.x() + round(jump_loc[0])),
  3755. int(canvas_origin.y() + round(jump_loc[1]))
  3756. )
  3757. cursor.setPos(j_pos[0], j_pos[1])
  3758. else:
  3759. # find the canvas origin which is in the top left corner
  3760. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3761. # determine the coordinates for the lowest left point of the canvas
  3762. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3763. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3764. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3765. # canvas) and the point (width, height) is in the top-right location
  3766. loc = self.plotcanvas.axes.transData.transform_point(location)
  3767. j_pos = (
  3768. int(x0 + loc[0]),
  3769. int(y0 - loc[1])
  3770. )
  3771. cursor.setPos(j_pos[0], j_pos[1])
  3772. self.plotcanvas.mouse = [location[0], location[1]]
  3773. if self.defaults["global_cursor_color_enabled"] is True:
  3774. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3775. else:
  3776. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3777. if self.grid_status():
  3778. # Update cursor
  3779. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3780. symbol='++', edge_color=self.cursor_color_3D,
  3781. edge_width=self.defaults["global_cursor_width"],
  3782. size=self.defaults["global_cursor_size"])
  3783. # Set the relative position label
  3784. dx = location[0] - float(self.rel_point1[0])
  3785. dy = location[1] - float(self.rel_point1[1])
  3786. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3787. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3788. # # Set the position label
  3789. #
  3790. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3791. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3792. units = self.defaults["units"].lower()
  3793. self.plotcanvas.text_hud.text = \
  3794. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3795. dx, units, dy, units, location[0], units, location[1], units)
  3796. self.inform.emit('[success] %s' % _("Done."))
  3797. return location
  3798. def on_locate(self, obj, fit_center=True):
  3799. """
  3800. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3801. :param obj: The object on which to locate certain points
  3802. :param fit_center: If to fit view. Boolean.
  3803. :return: A point location. (x, y) tuple.
  3804. """
  3805. self.defaults.report_usage("on_locate()")
  3806. if obj is None:
  3807. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3808. return 'fail'
  3809. class DialogBoxChoice(QtWidgets.QDialog):
  3810. def __init__(self, title=None, icon=None, choice='bl'):
  3811. """
  3812. :param title: string with the window title
  3813. """
  3814. super(DialogBoxChoice, self).__init__()
  3815. self.ok = False
  3816. self.setWindowIcon(icon)
  3817. self.setWindowTitle(str(title))
  3818. self.form = QtWidgets.QFormLayout(self)
  3819. self.ref_radio = RadioSet([
  3820. {"label": _("Bottom-Left"), "value": "bl"},
  3821. {"label": _("Top-Left"), "value": "tl"},
  3822. {"label": _("Bottom-Right"), "value": "br"},
  3823. {"label": _("Top-Right"), "value": "tr"},
  3824. {"label": _("Center"), "value": "c"}
  3825. ], orientation='vertical', stretch=False)
  3826. self.ref_radio.set_value(choice)
  3827. self.form.addRow(self.ref_radio)
  3828. self.button_box = QtWidgets.QDialogButtonBox(
  3829. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3830. Qt.Horizontal, parent=self)
  3831. self.form.addRow(self.button_box)
  3832. self.button_box.accepted.connect(self.accept)
  3833. self.button_box.rejected.connect(self.reject)
  3834. if self.exec_() == QtWidgets.QDialog.Accepted:
  3835. self.ok = True
  3836. self.location_point = self.ref_radio.get_value()
  3837. else:
  3838. self.ok = False
  3839. self.location_point = None
  3840. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3841. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3842. choice=self.defaults['global_locate_pt'])
  3843. if dia_box.ok is True:
  3844. try:
  3845. location_point = dia_box.location_point
  3846. self.defaults['global_locate_pt'] = dia_box.location_point
  3847. except Exception:
  3848. return
  3849. else:
  3850. return
  3851. loc_b = obj.bounds()
  3852. if location_point == 'bl':
  3853. location = (loc_b[0], loc_b[1])
  3854. elif location_point == 'tl':
  3855. location = (loc_b[0], loc_b[3])
  3856. elif location_point == 'br':
  3857. location = (loc_b[2], loc_b[1])
  3858. elif location_point == 'tr':
  3859. location = (loc_b[2], loc_b[3])
  3860. else:
  3861. # center
  3862. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3863. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3864. location = (cx, cy)
  3865. self.locate_signal.emit(location, location_point)
  3866. if fit_center:
  3867. self.plotcanvas.fit_center(loc=location)
  3868. cursor = QtGui.QCursor()
  3869. if self.is_legacy is False:
  3870. # I don't know where those differences come from but they are constant for the current
  3871. # execution of the application and they are multiples of a value around 0.0263mm.
  3872. # In a random way sometimes they are more sometimes they are less
  3873. # if units == 'MM':
  3874. # cal_factor = 0.0263
  3875. # else:
  3876. # cal_factor = 0.0263 / 25.4
  3877. cal_location = (location[0], location[1])
  3878. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3879. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3880. j_pos = (
  3881. int(canvas_origin.x() + round(jump_loc[0])),
  3882. int(canvas_origin.y() + round(jump_loc[1]))
  3883. )
  3884. cursor.setPos(j_pos[0], j_pos[1])
  3885. else:
  3886. # find the canvas origin which is in the top left corner
  3887. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3888. # determine the coordinates for the lowest left point of the canvas
  3889. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3890. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3891. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3892. # canvas) and the point (width, height) is in the top-right location
  3893. loc = self.plotcanvas.axes.transData.transform_point(location)
  3894. j_pos = (
  3895. int(x0 + loc[0]),
  3896. int(y0 - loc[1])
  3897. )
  3898. cursor.setPos(j_pos[0], j_pos[1])
  3899. self.plotcanvas.mouse = [location[0], location[1]]
  3900. if self.defaults["global_cursor_color_enabled"] is True:
  3901. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3902. else:
  3903. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3904. if self.grid_status():
  3905. # Update cursor
  3906. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3907. symbol='++', edge_color=self.cursor_color_3D,
  3908. edge_width=self.defaults["global_cursor_width"],
  3909. size=self.defaults["global_cursor_size"])
  3910. # Set the relative position label
  3911. self.dx = location[0] - float(self.rel_point1[0])
  3912. self.dy = location[1] - float(self.rel_point1[1])
  3913. # Set the position label
  3914. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3915. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3916. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3917. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  3918. units = self.defaults["units"].lower()
  3919. self.plotcanvas.text_hud.text = \
  3920. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3921. self.dx, units, self.dy, units, location[0], units, location[1], units)
  3922. self.inform.emit('[success] %s' % _("Done."))
  3923. return location
  3924. def on_copy_command(self):
  3925. """
  3926. Will copy a selection of objects, creating new objects.
  3927. :return:
  3928. """
  3929. self.defaults.report_usage("on_copy_command()")
  3930. def initialize(obj_init, app):
  3931. """
  3932. :param obj_init: the new object
  3933. :type obj_init: class
  3934. :param app: An instance of the App class
  3935. :type app: App
  3936. :return: None
  3937. :rtype:
  3938. """
  3939. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3940. try:
  3941. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3942. except AttributeError:
  3943. pass
  3944. try:
  3945. obj_init.apertures = deepcopy(obj.apertures)
  3946. except AttributeError:
  3947. pass
  3948. try:
  3949. if obj.tools:
  3950. obj_init.tools = deepcopy(obj.tools)
  3951. except Exception as err:
  3952. log.debug("App.on_copy_command() --> %s" % str(err))
  3953. try:
  3954. obj_init.source_file = deepcopy(obj.source_file)
  3955. except (AttributeError, TypeError):
  3956. pass
  3957. def initialize_excellon(obj_init, app):
  3958. obj_init.source_file = deepcopy(obj.source_file)
  3959. obj_init.tools = deepcopy(obj.tools)
  3960. # drills are offset, so they need to be deep copied
  3961. obj_init.drills = deepcopy(obj.drills)
  3962. # slots are offset, so they need to be deep copied
  3963. obj_init.slots = deepcopy(obj.slots)
  3964. obj_init.create_geometry()
  3965. def initialize_script(obj_init, app_obj):
  3966. obj_init.source_file = deepcopy(obj.source_file)
  3967. def initialize_document(obj_init, app_obj):
  3968. obj_init.source_file = deepcopy(obj.source_file)
  3969. for obj in self.collection.get_selected():
  3970. obj_name = obj.options["name"]
  3971. try:
  3972. if isinstance(obj, ExcellonObject):
  3973. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3974. elif isinstance(obj, GerberObject):
  3975. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  3976. elif isinstance(obj, GeometryObject):
  3977. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  3978. elif isinstance(obj, ScriptObject):
  3979. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  3980. elif isinstance(obj, DocumentObject):
  3981. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  3982. except Exception as e:
  3983. return "Operation failed: %s" % str(e)
  3984. def on_copy_object2(self, custom_name):
  3985. def initialize_geometry(obj_init, app):
  3986. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3987. try:
  3988. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3989. except AttributeError:
  3990. pass
  3991. try:
  3992. obj_init.apertures = deepcopy(obj.apertures)
  3993. except AttributeError:
  3994. pass
  3995. try:
  3996. if obj.tools:
  3997. obj_init.tools = deepcopy(obj.tools)
  3998. except Exception as ee:
  3999. log.debug("on_copy_object2() --> %s" % str(ee))
  4000. def initialize_gerber(obj_init, app):
  4001. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4002. obj_init.apertures = deepcopy(obj.apertures)
  4003. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4004. def initialize_excellon(obj_init, app):
  4005. obj_init.tools = deepcopy(obj.tools)
  4006. # drills are offset, so they need to be deep copied
  4007. obj_init.drills = deepcopy(obj.drills)
  4008. # slots are offset, so they need to be deep copied
  4009. obj_init.slots = deepcopy(obj.slots)
  4010. obj_init.create_geometry()
  4011. for obj in self.collection.get_selected():
  4012. obj_name = obj.options["name"]
  4013. try:
  4014. if isinstance(obj, ExcellonObject):
  4015. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4016. elif isinstance(obj, GerberObject):
  4017. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4018. elif isinstance(obj, GeometryObject):
  4019. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4020. except Exception as er:
  4021. return "Operation failed: %s" % str(er)
  4022. def on_rename_object(self, text):
  4023. """
  4024. Will rename an object.
  4025. :param text: New name for the object.
  4026. :return:
  4027. """
  4028. self.defaults.report_usage("on_rename_object()")
  4029. named_obj = self.collection.get_active()
  4030. for obj in named_obj:
  4031. if obj is list:
  4032. self.on_rename_object(text)
  4033. else:
  4034. try:
  4035. obj.options['name'] = text
  4036. except Exception as e:
  4037. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4038. def convert_any2geo(self):
  4039. """
  4040. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4041. :return:
  4042. """
  4043. self.defaults.report_usage("convert_any2geo()")
  4044. def initialize(obj_init, app):
  4045. obj_init.solid_geometry = obj.solid_geometry
  4046. try:
  4047. obj_init.follow_geometry = obj.follow_geometry
  4048. except AttributeError:
  4049. pass
  4050. try:
  4051. obj_init.apertures = obj.apertures
  4052. except AttributeError:
  4053. pass
  4054. try:
  4055. if obj.tools:
  4056. obj_init.tools = obj.tools
  4057. except AttributeError:
  4058. pass
  4059. def initialize_excellon(obj_init, app):
  4060. # objs = self.collection.get_selected()
  4061. # GeometryObject.merge(objs, obj)
  4062. solid_geo = []
  4063. for tool in obj.tools:
  4064. for geo in obj.tools[tool]['solid_geometry']:
  4065. solid_geo.append(geo)
  4066. obj_init.solid_geometry = deepcopy(solid_geo)
  4067. if not self.collection.get_selected():
  4068. log.warning("App.convert_any2geo --> No object selected")
  4069. self.inform.emit('[WARNING_NOTCL] %s' %
  4070. _("No object is selected. Select an object and try again."))
  4071. return
  4072. for obj in self.collection.get_selected():
  4073. obj_name = obj.options["name"]
  4074. try:
  4075. if isinstance(obj, ExcellonObject):
  4076. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4077. else:
  4078. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4079. except Exception as e:
  4080. return "Operation failed: %s" % str(e)
  4081. def convert_any2gerber(self):
  4082. """
  4083. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4084. :return:
  4085. """
  4086. self.defaults.report_usage("convert_any2gerber()")
  4087. def initialize_geometry(obj_init, app):
  4088. apertures = {}
  4089. apid = 0
  4090. apertures[str(apid)] = {}
  4091. apertures[str(apid)]['geometry'] = []
  4092. for obj_orig in obj.solid_geometry:
  4093. new_elem = {}
  4094. new_elem['solid'] = obj_orig
  4095. try:
  4096. new_elem['follow'] = obj_orig.exterior
  4097. except AttributeError:
  4098. pass
  4099. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4100. apertures[str(apid)]['size'] = 0.0
  4101. apertures[str(apid)]['type'] = 'C'
  4102. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4103. obj_init.apertures = deepcopy(apertures)
  4104. def initialize_excellon(obj_init, app):
  4105. apertures = {}
  4106. apid = 10
  4107. for tool in obj.tools:
  4108. apertures[str(apid)] = {}
  4109. apertures[str(apid)]['geometry'] = []
  4110. for geo in obj.tools[tool]['solid_geometry']:
  4111. new_el = {}
  4112. new_el['solid'] = geo
  4113. new_el['follow'] = geo.exterior
  4114. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4115. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4116. apertures[str(apid)]['type'] = 'C'
  4117. apid += 1
  4118. # create solid_geometry
  4119. solid_geometry = []
  4120. for apid in apertures:
  4121. for geo_el in apertures[apid]['geometry']:
  4122. solid_geometry.append(geo_el['solid'])
  4123. solid_geometry = MultiPolygon(solid_geometry)
  4124. solid_geometry = solid_geometry.buffer(0.0000001)
  4125. obj_init.solid_geometry = deepcopy(solid_geometry)
  4126. obj_init.apertures = deepcopy(apertures)
  4127. # clear the working objects (perhaps not necessary due of Python GC)
  4128. apertures.clear()
  4129. if not self.collection.get_selected():
  4130. log.warning("App.convert_any2gerber --> No object selected")
  4131. self.inform.emit('[WARNING_NOTCL] %s' %
  4132. _("No object is selected. Select an object and try again."))
  4133. return
  4134. for obj in self.collection.get_selected():
  4135. obj_name = obj.options["name"]
  4136. try:
  4137. if isinstance(obj, ExcellonObject):
  4138. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4139. elif isinstance(obj, GeometryObject):
  4140. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4141. else:
  4142. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4143. except Exception as e:
  4144. return "Operation failed: %s" % str(e)
  4145. def abort_all_tasks(self):
  4146. """
  4147. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4148. on the first possible occasion.
  4149. :return:
  4150. """
  4151. if self.abort_flag is False:
  4152. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4153. self.abort_flag = True
  4154. self.cleanup.emit()
  4155. def app_is_idle(self):
  4156. if self.abort_flag:
  4157. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4158. self.abort_flag = False
  4159. def on_selectall(self):
  4160. """
  4161. Will draw a selection box shape around the selected objects.
  4162. :return:
  4163. """
  4164. self.defaults.report_usage("on_selectall()")
  4165. # delete the possible selection box around a possible selected object
  4166. self.delete_selection_shape()
  4167. for name in self.collection.get_names():
  4168. self.collection.set_active(name)
  4169. curr_sel_obj = self.collection.get_by_name(name)
  4170. # create the selection box around the selected object
  4171. if self.defaults['global_selection_shape'] is True:
  4172. self.draw_selection_shape(curr_sel_obj)
  4173. def on_toggle_preferences(self):
  4174. pref_open = False
  4175. for idx in range(self.ui.plot_tab_area.count()):
  4176. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4177. pref_open = True
  4178. if pref_open:
  4179. for idx in range(self.ui.plot_tab_area.count()):
  4180. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4181. self.ui.plot_tab_area.removeTab(idx)
  4182. break
  4183. self.ui.pref_status_label.setStyleSheet("")
  4184. else:
  4185. self.on_preferences()
  4186. self.ui.pref_status_label.setStyleSheet("""
  4187. QLabel
  4188. {
  4189. color: black;
  4190. background-color: lightseagreen;
  4191. }
  4192. """
  4193. )
  4194. def on_preferences(self):
  4195. """
  4196. Adds the Preferences in a Tab in Plot Area
  4197. :return:
  4198. """
  4199. # add the tab if it was closed
  4200. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4201. # delete the absolute and relative position and messages in the infobar
  4202. self.ui.position_label.setText("")
  4203. # self.ui.rel_position_label.setText("")
  4204. # Switch plot_area to preferences page
  4205. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4206. # self.ui.show()
  4207. # detect changes in the preferences
  4208. for idx in range(self.ui.pref_tab_area.count()):
  4209. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4210. try:
  4211. try:
  4212. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4213. except (TypeError, AttributeError):
  4214. pass
  4215. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4216. except AttributeError:
  4217. pass
  4218. try:
  4219. try:
  4220. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4221. except (TypeError, AttributeError):
  4222. pass
  4223. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4224. except AttributeError:
  4225. pass
  4226. try:
  4227. try:
  4228. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4229. except (TypeError, AttributeError):
  4230. pass
  4231. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4232. except AttributeError:
  4233. pass
  4234. try:
  4235. try:
  4236. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4237. except (TypeError, AttributeError):
  4238. pass
  4239. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4240. except AttributeError:
  4241. pass
  4242. try:
  4243. try:
  4244. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4245. except (TypeError, AttributeError):
  4246. pass
  4247. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4248. except AttributeError:
  4249. pass
  4250. def on_tools_database(self, source='app'):
  4251. """
  4252. Adds the Tools Database in a Tab in Plot Area.
  4253. :return:
  4254. """
  4255. for idx in range(self.ui.plot_tab_area.count()):
  4256. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4257. # there can be only one instance of Tools Database at one time
  4258. return
  4259. if source == 'app':
  4260. self.tools_db_tab = ToolsDB2(
  4261. app=self,
  4262. parent=self.ui,
  4263. callback_on_edited=self.on_tools_db_edited,
  4264. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4265. )
  4266. elif source == 'ncc':
  4267. self.tools_db_tab = ToolsDB2(
  4268. app=self,
  4269. parent=self.ui,
  4270. callback_on_edited=self.on_tools_db_edited,
  4271. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4272. )
  4273. elif source == 'paint':
  4274. self.tools_db_tab = ToolsDB2(
  4275. app=self,
  4276. parent=self.ui,
  4277. callback_on_edited=self.on_tools_db_edited,
  4278. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4279. )
  4280. elif source == 'iso':
  4281. self.tools_db_tab = ToolsDB2(
  4282. app=self,
  4283. parent=self.ui,
  4284. callback_on_edited=self.on_tools_db_edited,
  4285. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4286. )
  4287. # add the tab if it was closed
  4288. try:
  4289. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4290. self.tools_db_tab.setObjectName("database_tab")
  4291. except Exception as e:
  4292. log.debug("App.on_tools_database() --> %s" % str(e))
  4293. return
  4294. # delete the absolute and relative position and messages in the infobar
  4295. self.ui.position_label.setText("")
  4296. # self.ui.rel_position_label.setText("")
  4297. # Switch plot_area to preferences page
  4298. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4299. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4300. self.tools_db_tab.ui_connect()
  4301. def on_tools_db_edited(self):
  4302. """
  4303. Executed whenever a tool is edited in Tools Database.
  4304. Will color the text of the Tools Database tab to Red color.
  4305. :return:
  4306. """
  4307. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4308. for idx in range(self.ui.plot_tab_area.count()):
  4309. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4310. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4311. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4312. self.tools_db_changed_flag = True
  4313. def on_geometry_tool_add_from_db_executed(self, tool):
  4314. """
  4315. Here add the tool from DB in the selected geometry object.
  4316. :return:
  4317. """
  4318. tool_from_db = deepcopy(tool)
  4319. obj = self.collection.get_active()
  4320. if obj.kind == 'geometry':
  4321. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4322. # close the tab and delete it
  4323. for idx in range(self.ui.plot_tab_area.count()):
  4324. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4325. wdg = self.ui.plot_tab_area.widget(idx)
  4326. wdg.deleteLater()
  4327. self.ui.plot_tab_area.removeTab(idx)
  4328. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4329. elif obj.kind == 'gerber':
  4330. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4331. # close the tab and delete it
  4332. for idx in range(self.ui.plot_tab_area.count()):
  4333. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4334. wdg = self.ui.plot_tab_area.widget(idx)
  4335. wdg.deleteLater()
  4336. self.ui.plot_tab_area.removeTab(idx)
  4337. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4338. else:
  4339. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4340. def on_plot_area_tab_closed(self, tab_obj_name):
  4341. """
  4342. Executed whenever a QTab is closed in the Plot Area.
  4343. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4344. :return:
  4345. """
  4346. if tab_obj_name == "preferences_tab":
  4347. self.preferencesUiManager.on_close_preferences_tab()
  4348. elif tab_obj_name == "database_tab":
  4349. # disconnect the signals from the table widget in tab
  4350. self.tools_db_tab.ui_disconnect()
  4351. if self.tools_db_changed_flag is True:
  4352. msgbox = QtWidgets.QMessageBox()
  4353. msgbox.setText(_("One or more Tools are edited.\n"
  4354. "Do you want to update the Tools Database?"))
  4355. msgbox.setWindowTitle(_("Save Tools Database"))
  4356. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4357. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4358. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4359. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4360. msgbox.setDefaultButton(bt_yes)
  4361. msgbox.exec_()
  4362. response = msgbox.clickedButton()
  4363. if response == bt_yes:
  4364. self.tools_db_tab.on_save_tools_db()
  4365. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4366. else:
  4367. self.tools_db_changed_flag = False
  4368. self.inform.emit('')
  4369. return
  4370. self.tools_db_tab.deleteLater()
  4371. elif tab_obj_name == "text_editor_tab":
  4372. self.toggle_codeeditor = False
  4373. elif tab_obj_name == "bookmarks_tab":
  4374. self.book_dialog_tab.rebuild_actions()
  4375. self.book_dialog_tab.deleteLater()
  4376. else:
  4377. return
  4378. # def on_plotarea_tab_closed(self, tab_idx):
  4379. # """
  4380. #
  4381. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4382. # :return:
  4383. # """
  4384. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4385. #
  4386. # if widget is not None:
  4387. # widget.deleteLater()
  4388. # self.ui.plot_tab_area.removeTab(tab_idx)
  4389. def on_flipy(self):
  4390. """
  4391. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4392. :return:
  4393. """
  4394. self.defaults.report_usage("on_flipy()")
  4395. obj_list = self.collection.get_selected()
  4396. xminlist = []
  4397. yminlist = []
  4398. xmaxlist = []
  4399. ymaxlist = []
  4400. if not obj_list:
  4401. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4402. else:
  4403. try:
  4404. # first get a bounding box to fit all
  4405. for obj in obj_list:
  4406. xmin, ymin, xmax, ymax = obj.bounds()
  4407. xminlist.append(xmin)
  4408. yminlist.append(ymin)
  4409. xmaxlist.append(xmax)
  4410. ymaxlist.append(ymax)
  4411. # get the minimum x,y and maximum x,y for all objects selected
  4412. xminimal = min(xminlist)
  4413. yminimal = min(yminlist)
  4414. xmaximal = max(xmaxlist)
  4415. ymaximal = max(ymaxlist)
  4416. px = 0.5 * (xminimal + xmaximal)
  4417. py = 0.5 * (yminimal + ymaximal)
  4418. # execute mirroring
  4419. for obj in obj_list:
  4420. obj.mirror('X', [px, py])
  4421. obj.plot()
  4422. self.app_obj.object_changed.emit(obj)
  4423. self.inform.emit('[success] %s' %
  4424. _("Flip on Y axis done."))
  4425. except Exception as e:
  4426. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4427. return
  4428. def on_flipx(self):
  4429. """
  4430. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4431. :return:
  4432. """
  4433. self.defaults.report_usage("on_flipx()")
  4434. obj_list = self.collection.get_selected()
  4435. xminlist = []
  4436. yminlist = []
  4437. xmaxlist = []
  4438. ymaxlist = []
  4439. if not obj_list:
  4440. self.inform.emit('[WARNING_NOTCL] %s' %
  4441. _("No object selected to Flip on X axis."))
  4442. else:
  4443. try:
  4444. # first get a bounding box to fit all
  4445. for obj in obj_list:
  4446. xmin, ymin, xmax, ymax = obj.bounds()
  4447. xminlist.append(xmin)
  4448. yminlist.append(ymin)
  4449. xmaxlist.append(xmax)
  4450. ymaxlist.append(ymax)
  4451. # get the minimum x,y and maximum x,y for all objects selected
  4452. xminimal = min(xminlist)
  4453. yminimal = min(yminlist)
  4454. xmaximal = max(xmaxlist)
  4455. ymaximal = max(ymaxlist)
  4456. px = 0.5 * (xminimal + xmaximal)
  4457. py = 0.5 * (yminimal + ymaximal)
  4458. # execute mirroring
  4459. for obj in obj_list:
  4460. obj.mirror('Y', [px, py])
  4461. obj.plot()
  4462. self.app_obj.object_changed.emit(obj)
  4463. self.inform.emit('[success] %s' %
  4464. _("Flip on X axis done."))
  4465. except Exception as e:
  4466. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4467. return
  4468. def on_rotate(self, silent=False, preset=None):
  4469. """
  4470. Executed when Options -> Rotate Selection menu entry is clicked.
  4471. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4472. :param preset: A value to be used as predefined angle for rotation.
  4473. :return:
  4474. """
  4475. self.defaults.report_usage("on_rotate()")
  4476. obj_list = self.collection.get_selected()
  4477. xminlist = []
  4478. yminlist = []
  4479. xmaxlist = []
  4480. ymaxlist = []
  4481. if not obj_list:
  4482. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4483. else:
  4484. if silent is False:
  4485. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4486. min=-360, max=360, decimals=4,
  4487. init_val=float(self.defaults['tools_transform_rotate']))
  4488. num, ok = rotatebox.get_value()
  4489. else:
  4490. num = preset
  4491. ok = True
  4492. if ok:
  4493. try:
  4494. # first get a bounding box to fit all
  4495. for obj in obj_list:
  4496. xmin, ymin, xmax, ymax = obj.bounds()
  4497. xminlist.append(xmin)
  4498. yminlist.append(ymin)
  4499. xmaxlist.append(xmax)
  4500. ymaxlist.append(ymax)
  4501. # get the minimum x,y and maximum x,y for all objects selected
  4502. xminimal = min(xminlist)
  4503. yminimal = min(yminlist)
  4504. xmaximal = max(xmaxlist)
  4505. ymaximal = max(ymaxlist)
  4506. px = 0.5 * (xminimal + xmaximal)
  4507. py = 0.5 * (yminimal + ymaximal)
  4508. for sel_obj in obj_list:
  4509. sel_obj.rotate(-float(num), point=(px, py))
  4510. sel_obj.plot()
  4511. self.app_obj.object_changed.emit(sel_obj)
  4512. self.inform.emit('[success] %s' % _("Rotation done."))
  4513. except Exception as e:
  4514. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4515. return
  4516. def on_skewx(self):
  4517. """
  4518. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4519. :return:
  4520. """
  4521. self.defaults.report_usage("on_skewx()")
  4522. obj_list = self.collection.get_selected()
  4523. xminlist = []
  4524. yminlist = []
  4525. if not obj_list:
  4526. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4527. else:
  4528. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4529. min=-360, max=360, decimals=4,
  4530. init_val=float(self.defaults['tools_transform_skew_x']))
  4531. num, ok = skewxbox.get_value()
  4532. if ok:
  4533. # first get a bounding box to fit all
  4534. for obj in obj_list:
  4535. xmin, ymin, xmax, ymax = obj.bounds()
  4536. xminlist.append(xmin)
  4537. yminlist.append(ymin)
  4538. # get the minimum x,y and maximum x,y for all objects selected
  4539. xminimal = min(xminlist)
  4540. yminimal = min(yminlist)
  4541. for obj in obj_list:
  4542. obj.skew(num, 0, point=(xminimal, yminimal))
  4543. obj.plot()
  4544. self.app_obj.object_changed.emit(obj)
  4545. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4546. def on_skewy(self):
  4547. """
  4548. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4549. :return:
  4550. """
  4551. self.defaults.report_usage("on_skewy()")
  4552. obj_list = self.collection.get_selected()
  4553. xminlist = []
  4554. yminlist = []
  4555. if not obj_list:
  4556. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4557. else:
  4558. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4559. min=-360, max=360, decimals=4,
  4560. init_val=float(self.defaults['tools_transform_skew_y']))
  4561. num, ok = skewybox.get_value()
  4562. if ok:
  4563. # first get a bounding box to fit all
  4564. for obj in obj_list:
  4565. xmin, ymin, xmax, ymax = obj.bounds()
  4566. xminlist.append(xmin)
  4567. yminlist.append(ymin)
  4568. # get the minimum x,y and maximum x,y for all objects selected
  4569. xminimal = min(xminlist)
  4570. yminimal = min(yminlist)
  4571. for obj in obj_list:
  4572. obj.skew(0, num, point=(xminimal, yminimal))
  4573. obj.plot()
  4574. self.app_obj.object_changed.emit(obj)
  4575. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4576. def on_plots_updated(self):
  4577. """
  4578. Callback used to report when the plots have changed.
  4579. Adjust axes and zooms to fit.
  4580. :return: None
  4581. """
  4582. if self.is_legacy is False:
  4583. self.plotcanvas.update()
  4584. else:
  4585. self.plotcanvas.auto_adjust_axes()
  4586. self.on_zoom_fit()
  4587. self.collection.update_view()
  4588. # self.inform.emit(_("Plots updated ..."))
  4589. def on_toolbar_replot(self):
  4590. """
  4591. Callback for toolbar button. Re-plots all objects.
  4592. :return: None
  4593. """
  4594. self.log.debug("on_toolbar_replot()")
  4595. try:
  4596. self.collection.get_active().read_form()
  4597. except AttributeError:
  4598. self.log.debug("on_toolbar_replot(): AttributeError")
  4599. pass
  4600. self.plot_all()
  4601. def grid_status(self):
  4602. return True if self.ui.grid_snap_btn.isChecked() else False
  4603. def populate_cmenu_grids(self):
  4604. units = self.defaults['units'].lower()
  4605. # for act in self.ui.cmenu_gridmenu.actions():
  4606. # act.triggered.disconnect()
  4607. self.ui.cmenu_gridmenu.clear()
  4608. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4609. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4610. _("Grid On/Off"))
  4611. grid_toggle.setCheckable(True)
  4612. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4613. self.ui.cmenu_gridmenu.addSeparator()
  4614. for grid in sorted_list:
  4615. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4616. "%s" % str(grid))
  4617. action.triggered.connect(self.set_grid)
  4618. self.ui.cmenu_gridmenu.addSeparator()
  4619. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4620. _("Add"))
  4621. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4622. _("Delete"))
  4623. grid_add.triggered.connect(self.on_grid_add)
  4624. grid_delete.triggered.connect(self.on_grid_delete)
  4625. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4626. def set_grid(self):
  4627. menu_action = self.sender()
  4628. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4629. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4630. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4631. def on_grid_add(self):
  4632. # ## Current application units in lower Case
  4633. units = self.defaults['units'].lower()
  4634. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4635. text=_('Enter a Grid Value:'),
  4636. min=0.0000, max=99.9999, decimals=4)
  4637. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4638. val, ok = grid_add_popup.get_value()
  4639. if ok:
  4640. if float(val) == 0:
  4641. self.inform.emit('[WARNING_NOTCL] %s' %
  4642. _("Please enter a grid value with non-zero value, in Float format."))
  4643. return
  4644. else:
  4645. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4646. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4647. self.inform.emit('[success] %s...' % _("New Grid added"))
  4648. else:
  4649. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4650. else:
  4651. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4652. def on_grid_delete(self):
  4653. # ## Current application units in lower Case
  4654. units = self.defaults['units'].lower()
  4655. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4656. text='Enter a Grid Value:',
  4657. min=0.0000, max=99.9999, decimals=4)
  4658. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4659. val, ok = grid_del_popup.get_value()
  4660. if ok:
  4661. if float(val) == 0:
  4662. self.inform.emit('[WARNING_NOTCL] %s' %
  4663. _("Please enter a grid value with non-zero value, in Float format."))
  4664. return
  4665. else:
  4666. try:
  4667. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4668. except ValueError:
  4669. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4670. return
  4671. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4672. else:
  4673. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4674. def on_shortcut_list(self):
  4675. self.defaults.report_usage("on_shortcut_list()")
  4676. # add the tab if it was closed
  4677. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4678. # delete the absolute and relative position and messages in the infobar
  4679. self.ui.position_label.setText("")
  4680. # self.ui.rel_position_label.setText("")
  4681. # Switch plot_area to preferences page
  4682. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4683. # self.ui.show()
  4684. def on_select_tab(self, name):
  4685. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4686. if self.ui.splitter.sizes()[0] == 0:
  4687. self.ui.splitter.setSizes([1, 1])
  4688. else:
  4689. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4690. self.ui.splitter.setSizes([0, 1])
  4691. if name == 'project':
  4692. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4693. elif name == 'selected':
  4694. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4695. elif name == 'tool':
  4696. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4697. def on_copy_name(self):
  4698. self.defaults.report_usage("on_copy_name()")
  4699. obj = self.collection.get_active()
  4700. try:
  4701. name = obj.options["name"]
  4702. except AttributeError:
  4703. log.debug("on_copy_name() --> No object selected to copy it's name")
  4704. self.inform.emit('[WARNING_NOTCL] %s' %
  4705. _(" No object selected to copy it's name"))
  4706. return
  4707. self.clipboard.setText(name)
  4708. self.inform.emit(_("Name copied on clipboard ..."))
  4709. def on_mouse_click_over_plot(self, event):
  4710. """
  4711. Default actions are:
  4712. :param event: Contains information about the event, like which button
  4713. was clicked, the pixel coordinates and the axes coordinates.
  4714. :return: None
  4715. """
  4716. self.pos = []
  4717. if self.is_legacy is False:
  4718. event_pos = event.pos
  4719. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4720. # # Set the mouse button for panning
  4721. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4722. else:
  4723. event_pos = (event.xdata, event.ydata)
  4724. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4725. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4726. # So it can receive key presses
  4727. self.plotcanvas.native.setFocus()
  4728. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4729. if self.grid_status():
  4730. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4731. else:
  4732. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4733. try:
  4734. if event.button == 1:
  4735. # Reset here the relative coordinates so there is a new reference on the click position
  4736. if self.rel_point1 is None:
  4737. self.rel_point1 = self.pos
  4738. else:
  4739. self.rel_point2 = copy(self.rel_point1)
  4740. self.rel_point1 = self.pos
  4741. self.on_mouse_move_over_plot(event, origin_click=True)
  4742. except Exception as e:
  4743. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4744. def on_mouse_double_click_over_plot(self, event):
  4745. if event.button == 1:
  4746. self.doubleclick = True
  4747. def on_mouse_move_over_plot(self, event, origin_click=None):
  4748. """
  4749. Callback for the mouse motion event over the plot.
  4750. :param event: Contains information about the event.
  4751. :param origin_click
  4752. :return: None
  4753. """
  4754. if self.is_legacy is False:
  4755. event_pos = event.pos
  4756. if self.defaults["global_pan_button"] == '2':
  4757. pan_button = 2
  4758. else:
  4759. pan_button = 3
  4760. self.event_is_dragging = event.is_dragging
  4761. else:
  4762. event_pos = (event.xdata, event.ydata)
  4763. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4764. if self.defaults["global_pan_button"] == '2':
  4765. pan_button = 3
  4766. else:
  4767. pan_button = 2
  4768. self.event_is_dragging = self.plotcanvas.is_dragging
  4769. # So it can receive key presses but not when the Tcl Shell is active
  4770. if not self.ui.shell_dock.isVisible():
  4771. if not self.plotcanvas.native.hasFocus():
  4772. self.plotcanvas.native.setFocus()
  4773. self.pos_jump = event_pos
  4774. self.ui.popMenu.mouse_is_panning = False
  4775. if origin_click is None:
  4776. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4777. if event.button == pan_button and self.event_is_dragging == 1:
  4778. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4779. if self.ui.popMenu.popup_active:
  4780. self.ui.popMenu.popup_active = False
  4781. return
  4782. self.ui.popMenu.mouse_is_panning = True
  4783. return
  4784. if self.rel_point1 is not None:
  4785. try: # May fail in case mouse not within axes
  4786. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4787. if pos_canvas[0] is None or pos_canvas[1] is None:
  4788. return
  4789. if self.grid_status():
  4790. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4791. # Update cursor
  4792. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4793. symbol='++', edge_color=self.cursor_color_3D,
  4794. edge_width=self.defaults["global_cursor_width"],
  4795. size=self.defaults["global_cursor_size"])
  4796. else:
  4797. pos = (pos_canvas[0], pos_canvas[1])
  4798. self.dx = pos[0] - float(self.rel_point1[0])
  4799. self.dy = pos[1] - float(self.rel_point1[1])
  4800. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4801. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4802. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4803. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4804. units = self.defaults["units"].lower()
  4805. self.plotcanvas.text_hud.text = \
  4806. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4807. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4808. self.mouse = [pos[0], pos[1]]
  4809. # if the mouse is moved and the LMB is clicked then the action is a selection
  4810. if self.event_is_dragging == 1 and event.button == 1:
  4811. self.delete_selection_shape()
  4812. if self.dx < 0:
  4813. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4814. face_color=self.defaults['global_alt_sel_fill'])
  4815. self.selection_type = False
  4816. elif self.dx >= 0:
  4817. self.draw_moving_selection_shape(self.pos, pos)
  4818. self.selection_type = True
  4819. else:
  4820. self.selection_type = None
  4821. else:
  4822. self.selection_type = None
  4823. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  4824. if self.defaults['global_hover']:
  4825. for obj in self.collection.get_list():
  4826. try:
  4827. # select the object(s) only if it is enabled (plotted)
  4828. if obj.options['plot']:
  4829. if obj not in self.collection.get_selected():
  4830. poly_obj = Polygon(
  4831. [(obj.options['xmin'], obj.options['ymin']),
  4832. (obj.options['xmax'], obj.options['ymin']),
  4833. (obj.options['xmax'], obj.options['ymax']),
  4834. (obj.options['xmin'], obj.options['ymax'])]
  4835. )
  4836. if Point(pos).within(poly_obj):
  4837. if obj.isHovering is False:
  4838. obj.isHovering = True
  4839. obj.notHovering = True
  4840. # create the selection box around the selected object
  4841. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4842. else:
  4843. if obj.notHovering is True:
  4844. obj.notHovering = False
  4845. obj.isHovering = False
  4846. self.delete_hover_shape()
  4847. except Exception:
  4848. # the Exception here will happen if we try to select on screen and we have an
  4849. # newly (and empty) just created Geometry or Excellon object that do not have the
  4850. # xmin, xmax, ymin, ymax options.
  4851. # In this case poly_obj creation (see above) will fail
  4852. pass
  4853. except Exception as e:
  4854. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4855. self.ui.position_label.setText("")
  4856. # self.ui.rel_position_label.setText("")
  4857. self.mouse = None
  4858. def on_mouse_click_release_over_plot(self, event):
  4859. """
  4860. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4861. and has been registered in ''self.__init__()''.
  4862. :param event: contains information about the event.
  4863. :return:
  4864. """
  4865. if self.is_legacy is False:
  4866. event_pos = event.pos
  4867. right_button = 2
  4868. else:
  4869. event_pos = (event.xdata, event.ydata)
  4870. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4871. right_button = 3
  4872. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4873. if self.grid_status():
  4874. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4875. else:
  4876. pos = (pos_canvas[0], pos_canvas[1])
  4877. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4878. # canvas menu
  4879. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  4880. self.ui.popMenu.mouse_is_panning = False
  4881. self.cursor = QtGui.QCursor()
  4882. self.populate_cmenu_grids()
  4883. self.ui.popMenu.popup(self.cursor.pos())
  4884. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4885. # selection and then select a type of selection ("enclosing" or "touching")
  4886. if event.button == 1: # left click
  4887. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4888. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4889. if modifiers == QtCore.Qt.ShiftModifier:
  4890. # do not auto open the Project Tab
  4891. self.click_noproject = True
  4892. self.clipboard.setText(
  4893. self.defaults["global_point_clipboard_format"] %
  4894. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  4895. )
  4896. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  4897. return
  4898. if self.doubleclick is True:
  4899. self.doubleclick = False
  4900. if self.collection.get_selected():
  4901. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4902. if self.ui.splitter.sizes()[0] == 0:
  4903. self.ui.splitter.setSizes([1, 1])
  4904. try:
  4905. # delete the selection shape(S) as it may be in the way
  4906. self.delete_selection_shape()
  4907. self.delete_hover_shape()
  4908. except Exception as e:
  4909. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  4910. return
  4911. else:
  4912. # WORKAROUND for LEGACY MODE
  4913. if self.is_legacy is True:
  4914. # if there is no move on canvas then we have no dragging selection
  4915. if self.dx == 0 or self.dy == 0:
  4916. self.selection_type = None
  4917. if self.selection_type is not None:
  4918. try:
  4919. self.selection_area_handler(self.pos, pos, self.selection_type)
  4920. self.selection_type = None
  4921. except Exception as e:
  4922. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  4923. return
  4924. else:
  4925. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4926. if key_modifier == QtCore.Qt.ShiftModifier:
  4927. mod_key = 'Shift'
  4928. elif key_modifier == QtCore.Qt.ControlModifier:
  4929. mod_key = 'Control'
  4930. else:
  4931. mod_key = None
  4932. try:
  4933. if self.command_active is None:
  4934. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4935. # deselect, and if it's not selected then it will be selected
  4936. # If there is no active command (self.command_active is None) then we check if we clicked
  4937. # on a object by checking the bounding limits against mouse click position
  4938. if mod_key == self.defaults["global_mselect_key"]:
  4939. self.select_objects(key='multisel')
  4940. else:
  4941. # If there is no active command (self.command_active is None) then we check if
  4942. # we clicked on a object by checking the bounding limits against mouse click position
  4943. self.select_objects()
  4944. self.delete_hover_shape()
  4945. except Exception as e:
  4946. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  4947. return
  4948. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4949. """
  4950. :param start_pos: mouse position when the selection LMB click was done
  4951. :param end_pos: mouse position when the left mouse button is released
  4952. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4953. :return:
  4954. """
  4955. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4956. # delete previous selection shape
  4957. self.delete_selection_shape()
  4958. # make all objects inactive
  4959. self.collection.set_all_inactive()
  4960. for obj in self.collection.get_list():
  4961. try:
  4962. # select the object(s) only if it is enabled (plotted)
  4963. if obj.options['plot']:
  4964. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4965. (obj.options['xmax'], obj.options['ymin']),
  4966. (obj.options['xmax'], obj.options['ymax']),
  4967. (obj.options['xmin'], obj.options['ymax'])])
  4968. if sel_type is True:
  4969. if poly_obj.within(poly_selection):
  4970. # create the selection box around the selected object
  4971. if self.defaults['global_selection_shape'] is True:
  4972. self.draw_selection_shape(obj)
  4973. self.collection.set_active(obj.options['name'])
  4974. else:
  4975. if poly_selection.intersects(poly_obj):
  4976. # create the selection box around the selected object
  4977. if self.defaults['global_selection_shape'] is True:
  4978. self.draw_selection_shape(obj)
  4979. self.collection.set_active(obj.options['name'])
  4980. obj.selection_shape_drawn = True
  4981. except Exception as e:
  4982. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4983. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4984. # In this case poly_obj creation (see above) will fail
  4985. log.debug("App.selection_area_handler() --> %s" % str(e))
  4986. def select_objects(self, key=None):
  4987. """
  4988. Will select objects clicked on canvas
  4989. :param key: for future use in cumulative selection
  4990. :return:
  4991. """
  4992. # list where we store the overlapped objects under our mouse left click position
  4993. if key is None:
  4994. self.objects_under_the_click_list = []
  4995. # Populate the list with the overlapped objects on the click position
  4996. curr_x, curr_y = self.pos
  4997. for obj in self.all_objects_list:
  4998. # ScriptObject and DocumentObject objects can't be selected
  4999. if obj.kind == 'script' or obj.kind == 'document':
  5000. continue
  5001. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5002. continue
  5003. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5004. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5005. if obj.options['name'] not in self.objects_under_the_click_list:
  5006. if obj.options['plot']:
  5007. # add objects to the objects_under_the_click list only if the object is plotted
  5008. # (active and not disabled)
  5009. self.objects_under_the_click_list.append(obj.options['name'])
  5010. try:
  5011. if self.objects_under_the_click_list:
  5012. curr_sel_obj = self.collection.get_active()
  5013. # case when there is only an object under the click and we toggle it
  5014. if len(self.objects_under_the_click_list) == 1:
  5015. if curr_sel_obj is None:
  5016. self.collection.set_active(self.objects_under_the_click_list[0])
  5017. curr_sel_obj = self.collection.get_active()
  5018. # create the selection box around the selected object
  5019. if self.defaults['global_selection_shape'] is True:
  5020. self.draw_selection_shape(curr_sel_obj)
  5021. curr_sel_obj.selection_shape_drawn = True
  5022. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5023. self.collection.on_objects_selection(False)
  5024. self.delete_selection_shape()
  5025. curr_sel_obj.selection_shape_drawn = False
  5026. self.collection.set_active(self.objects_under_the_click_list[0])
  5027. curr_sel_obj = self.collection.get_active()
  5028. # create the selection box around the selected object
  5029. if self.defaults['global_selection_shape'] is True:
  5030. self.draw_selection_shape(curr_sel_obj)
  5031. curr_sel_obj.selection_shape_drawn = True
  5032. self.selected_message(curr_sel_obj=curr_sel_obj)
  5033. elif curr_sel_obj.selection_shape_drawn is False:
  5034. if self.defaults['global_selection_shape'] is True:
  5035. self.draw_selection_shape(curr_sel_obj)
  5036. curr_sel_obj.selection_shape_drawn = True
  5037. else:
  5038. self.collection.on_objects_selection(False)
  5039. self.delete_selection_shape()
  5040. if self.call_source != 'app':
  5041. self.call_source = 'app'
  5042. self.selected_message(curr_sel_obj=curr_sel_obj)
  5043. else:
  5044. # If there is no selected object
  5045. # make active the first element of the overlapped objects list
  5046. if self.collection.get_active() is None:
  5047. self.collection.set_active(self.objects_under_the_click_list[0])
  5048. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5049. name_sel_obj = self.collection.get_active().options['name']
  5050. # In case that there is a selected object but it is not in the overlapped object list
  5051. # make that object inactive and activate the first element in the overlapped object list
  5052. if name_sel_obj not in self.objects_under_the_click_list:
  5053. self.collection.set_inactive(name_sel_obj)
  5054. name_sel_obj = self.objects_under_the_click_list[0]
  5055. self.collection.set_active(name_sel_obj)
  5056. else:
  5057. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5058. self.collection.set_all_inactive()
  5059. self.collection.set_active(
  5060. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5061. curr_sel_obj = self.collection.get_active()
  5062. # delete the possible selection box around a possible selected object
  5063. self.delete_selection_shape()
  5064. curr_sel_obj.selection_shape_drawn = False
  5065. # create the selection box around the selected object
  5066. if self.defaults['global_selection_shape'] is True:
  5067. self.draw_selection_shape(curr_sel_obj)
  5068. curr_sel_obj.selection_shape_drawn = True
  5069. self.selected_message(curr_sel_obj=curr_sel_obj)
  5070. else:
  5071. # deselect everything
  5072. self.collection.on_objects_selection(False)
  5073. # delete the possible selection box around a possible selected object
  5074. self.delete_selection_shape()
  5075. for o in self.collection.get_list():
  5076. o.selection_shape_drawn = False
  5077. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5078. # only when working on App
  5079. if self.call_source == 'app':
  5080. if self.click_noproject is False:
  5081. # if the Tool Tab is in focus don't change focus to Project Tab
  5082. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5083. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5084. else:
  5085. # restore auto open the Project Tab
  5086. self.click_noproject = False
  5087. # delete any text in the status bar, implicitly the last object name that was selected
  5088. # self.inform.emit("")
  5089. else:
  5090. self.call_source = 'app'
  5091. except Exception as e:
  5092. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5093. def selected_message(self, curr_sel_obj):
  5094. if curr_sel_obj:
  5095. if curr_sel_obj.kind == 'gerber':
  5096. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5097. color='green',
  5098. name=str(curr_sel_obj.options['name']),
  5099. tx=_("selected"))
  5100. )
  5101. elif curr_sel_obj.kind == 'excellon':
  5102. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5103. color='brown',
  5104. name=str(curr_sel_obj.options['name']),
  5105. tx=_("selected"))
  5106. )
  5107. elif curr_sel_obj.kind == 'cncjob':
  5108. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5109. color='blue',
  5110. name=str(curr_sel_obj.options['name']),
  5111. tx=_("selected"))
  5112. )
  5113. elif curr_sel_obj.kind == 'geometry':
  5114. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5115. color='red',
  5116. name=str(curr_sel_obj.options['name']),
  5117. tx=_("selected"))
  5118. )
  5119. def delete_hover_shape(self):
  5120. self.hover_shapes.clear()
  5121. self.hover_shapes.redraw()
  5122. def draw_hover_shape(self, sel_obj, color=None):
  5123. """
  5124. :param sel_obj: The object for which the hover shape must be drawn
  5125. :param color: The color of the hover shape
  5126. :return: None
  5127. """
  5128. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5129. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5130. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5131. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5132. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5133. if self.defaults['units'].upper() == 'MM':
  5134. hover_rect = hover_rect.buffer(-0.1)
  5135. hover_rect = hover_rect.buffer(0.2)
  5136. else:
  5137. hover_rect = hover_rect.buffer(-0.00393)
  5138. hover_rect = hover_rect.buffer(0.00787)
  5139. # if color:
  5140. # face = Color(color)
  5141. # face.alpha = 0.2
  5142. # outline = Color(color, alpha=0.8)
  5143. # else:
  5144. # face = Color(self.defaults['global_sel_fill'])
  5145. # face.alpha = 0.2
  5146. # outline = self.defaults['global_sel_line']
  5147. if color:
  5148. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5149. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5150. else:
  5151. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5152. outline = self.defaults['global_sel_line']
  5153. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5154. if self.is_legacy is True:
  5155. self.hover_shapes.redraw()
  5156. def delete_selection_shape(self):
  5157. self.move_tool.sel_shapes.clear()
  5158. self.move_tool.sel_shapes.redraw()
  5159. def draw_selection_shape(self, sel_obj, color=None):
  5160. """
  5161. Will draw a selection shape around the selected object.
  5162. :param sel_obj: The object for which the selection shape must be drawn
  5163. :param color: The color for the selection shape.
  5164. :return: None
  5165. """
  5166. if sel_obj is None:
  5167. return
  5168. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5169. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5170. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5171. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5172. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5173. if self.defaults['units'].upper() == 'MM':
  5174. sel_rect = sel_rect.buffer(-0.1)
  5175. sel_rect = sel_rect.buffer(0.2)
  5176. else:
  5177. sel_rect = sel_rect.buffer(-0.00393)
  5178. sel_rect = sel_rect.buffer(0.00787)
  5179. if color:
  5180. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5181. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5182. else:
  5183. if self.is_legacy is False:
  5184. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5185. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5186. else:
  5187. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5188. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5189. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5190. color=outline,
  5191. face_color=face,
  5192. update=True,
  5193. layer=0,
  5194. tolerance=None))
  5195. if self.is_legacy is True:
  5196. self.move_tool.sel_shapes.redraw()
  5197. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5198. """
  5199. Will draw a selection shape when dragging mouse on canvas.
  5200. :param old_coords: Old coordinates
  5201. :param coords: New coordinates
  5202. :param kwargs: Keyword arguments
  5203. :return:
  5204. """
  5205. if 'color' in kwargs:
  5206. color = kwargs['color']
  5207. else:
  5208. color = self.defaults['global_sel_line']
  5209. if 'face_color' in kwargs:
  5210. face_color = kwargs['face_color']
  5211. else:
  5212. face_color = self.defaults['global_sel_fill']
  5213. if 'face_alpha' in kwargs:
  5214. face_alpha = kwargs['face_alpha']
  5215. else:
  5216. face_alpha = 0.3
  5217. x0, y0 = old_coords
  5218. x1, y1 = coords
  5219. pt1 = (x0, y0)
  5220. pt2 = (x1, y0)
  5221. pt3 = (x1, y1)
  5222. pt4 = (x0, y1)
  5223. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5224. # color_t = Color(face_color)
  5225. # color_t.alpha = face_alpha
  5226. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5227. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5228. layer=0, tolerance=None)
  5229. if self.is_legacy is True:
  5230. self.move_tool.sel_shapes.redraw()
  5231. def on_file_new_click(self):
  5232. """
  5233. Callback for menu item File -> New.
  5234. Executed on clicking the Menu -> File -> New Project
  5235. :return:
  5236. """
  5237. if self.collection.get_list() and self.should_we_save:
  5238. msgbox = QtWidgets.QMessageBox()
  5239. # msgbox.setText("<B>Save changes ...</B>")
  5240. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5241. "Creating a New project will delete them.\n"
  5242. "Do you want to Save the project?"))
  5243. msgbox.setWindowTitle(_("Save changes"))
  5244. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5245. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5246. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5247. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5248. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5249. msgbox.setDefaultButton(bt_yes)
  5250. msgbox.exec_()
  5251. response = msgbox.clickedButton()
  5252. if response == bt_yes:
  5253. self.on_file_saveprojectas()
  5254. elif response == bt_cancel:
  5255. return
  5256. elif response == bt_no:
  5257. self.on_file_new()
  5258. else:
  5259. self.on_file_new()
  5260. self.inform.emit('[success] %s...' % _("New Project created"))
  5261. def on_file_new(self, cli=None):
  5262. """
  5263. Returns the application to its startup state. This method is thread-safe.
  5264. :param cli: Boolean. If True this method was run from command line
  5265. :return: None
  5266. """
  5267. self.defaults.report_usage("on_file_new")
  5268. # Remove everything from memory
  5269. App.log.debug("on_file_new()")
  5270. # close any editor that might be open
  5271. if self.call_source != 'app':
  5272. self.editor2object(cleanup=True)
  5273. # ## EDITOR section
  5274. self.geo_editor = FlatCAMGeoEditor(self)
  5275. self.exc_editor = FlatCAMExcEditor(self)
  5276. self.grb_editor = FlatCAMGrbEditor(self)
  5277. # Clear pool
  5278. self.clear_pool()
  5279. for obj in self.collection.get_list():
  5280. # delete shapes left drawn from mark shape_collections, if any
  5281. if isinstance(obj, GerberObject):
  5282. try:
  5283. for el in obj.mark_shapes:
  5284. obj.mark_shapes[el].clear(update=True)
  5285. obj.mark_shapes[el].enabled = False
  5286. del el
  5287. except AttributeError:
  5288. pass
  5289. # also delete annotation shapes, if any
  5290. elif isinstance(obj, CNCJobObject):
  5291. try:
  5292. obj.text_col.enabled = False
  5293. del obj.text_col
  5294. obj.annotation.clear(update=True)
  5295. del obj.annotation
  5296. except AttributeError:
  5297. pass
  5298. # delete the exclusion areas
  5299. self.exc_areas.clear_shapes()
  5300. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5301. self.shell.init_tcl()
  5302. # delete any selection shape on canvas
  5303. self.delete_selection_shape()
  5304. # delete all FlatCAM objects
  5305. self.collection.delete_all()
  5306. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5307. self.setup_component_editor()
  5308. # Clear project filename
  5309. self.project_filename = None
  5310. # Load the application defaults
  5311. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5312. # Re-fresh project options
  5313. self.on_options_app2project()
  5314. # Init FlatCAMTools
  5315. self.init_tools()
  5316. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5317. if cli is None:
  5318. # we need to go in reverse because once we remove a tab then the index changes
  5319. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5320. # and so on. Therefore the deletion should be done in reverse
  5321. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5322. for index in range(wdg_count, -1, -1):
  5323. try:
  5324. self.ui.plot_tab_area.closeTab(index)
  5325. except Exception as e:
  5326. log.debug("App.on_file_new() --> %s" % str(e))
  5327. # # And then add again the Plot Area
  5328. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5329. self.ui.plot_tab_area.protectTab(0)
  5330. # take the focus of the Notebook on Project Tab.
  5331. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5332. self.set_ui_title(name=_("New Project - Not saved"))
  5333. def obj_properties(self):
  5334. """
  5335. Will launch the object Properties Tool
  5336. :return:
  5337. """
  5338. self.defaults.report_usage("obj_properties()")
  5339. self.properties_tool.run(toggle=False)
  5340. def on_project_context_save(self):
  5341. """
  5342. Wrapper, will save the object function of it's type
  5343. :return:
  5344. """
  5345. obj = self.collection.get_active()
  5346. if type(obj) == GeometryObject:
  5347. self.on_file_exportdxf()
  5348. elif type(obj) == ExcellonObject:
  5349. self.on_file_saveexcellon()
  5350. elif type(obj) == CNCJobObject:
  5351. obj.on_exportgcode_button_click()
  5352. elif type(obj) == GerberObject:
  5353. self.on_file_savegerber()
  5354. elif type(obj) == ScriptObject:
  5355. self.on_file_savescript()
  5356. elif type(obj) == DocumentObject:
  5357. self.on_file_savedocument()
  5358. def obj_move(self):
  5359. """
  5360. Callback for the Move menu entry in various Context Menu's.
  5361. :return:
  5362. """
  5363. self.defaults.report_usage("obj_move()")
  5364. self.move_tool.run(toggle=False)
  5365. def on_fileopengerber(self, signal, name=None):
  5366. """
  5367. File menu callback for opening a Gerber.
  5368. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5369. :param name:
  5370. :return: None
  5371. """
  5372. self.defaults.report_usage("on_fileopengerber")
  5373. App.log.debug("on_fileopengerber()")
  5374. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5375. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5376. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5377. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5378. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5379. "*.mil);;" \
  5380. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5381. "Allegro Files (*.art);;" \
  5382. "Mentor Files (*.pho *.gdo);;" \
  5383. "All Files (*.*)"
  5384. if name is None:
  5385. try:
  5386. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5387. directory=self.get_last_folder(),
  5388. filter=_filter_,
  5389. initialFilter=self.last_op_gerber_filter)
  5390. except TypeError:
  5391. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5392. filenames = [str(filename) for filename in filenames]
  5393. self.last_op_gerber_filter = _f
  5394. else:
  5395. filenames = [name]
  5396. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5397. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5398. _("Opening Gerber file.")),
  5399. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5400. color=QtGui.QColor("gray"))
  5401. if len(filenames) == 0:
  5402. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5403. else:
  5404. for filename in filenames:
  5405. if filename != '':
  5406. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5407. def on_fileopenexcellon(self, signal, name=None):
  5408. """
  5409. File menu callback for opening an Excellon file.
  5410. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5411. :param name:
  5412. :return: None
  5413. """
  5414. self.defaults.report_usage("on_fileopenexcellon")
  5415. App.log.debug("on_fileopenexcellon()")
  5416. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5417. "All Files (*.*)"
  5418. if name is None:
  5419. try:
  5420. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5421. directory=self.get_last_folder(),
  5422. filter=_filter_,
  5423. initialFilter=self.last_op_excellon_filter)
  5424. except TypeError:
  5425. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5426. filenames = [str(filename) for filename in filenames]
  5427. self.last_op_excellon_filter = _f
  5428. else:
  5429. filenames = [str(name)]
  5430. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5431. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5432. _("Opening Excellon file.")),
  5433. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5434. color=QtGui.QColor("gray"))
  5435. if len(filenames) == 0:
  5436. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5437. else:
  5438. for filename in filenames:
  5439. if filename != '':
  5440. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5441. def on_fileopengcode(self, signal, name=None):
  5442. """
  5443. File menu call back for opening gcode.
  5444. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5445. :param name:
  5446. :return:
  5447. """
  5448. self.defaults.report_usage("on_fileopengcode")
  5449. App.log.debug("on_fileopengcode()")
  5450. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5451. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5452. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5453. "All Files (*.*)"
  5454. if name is None:
  5455. try:
  5456. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5457. directory=self.get_last_folder(),
  5458. filter=_filter_,
  5459. initialFilter=self.last_op_gcode_filter)
  5460. except TypeError:
  5461. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5462. filenames = [str(filename) for filename in filenames]
  5463. self.last_op_gcode_filter = _f
  5464. else:
  5465. filenames = [name]
  5466. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5467. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5468. _("Opening G-Code file.")),
  5469. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5470. color=QtGui.QColor("gray"))
  5471. if len(filenames) == 0:
  5472. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5473. else:
  5474. for filename in filenames:
  5475. if filename != '':
  5476. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5477. def on_file_openproject(self, signal):
  5478. """
  5479. File menu callback for opening a project.
  5480. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5481. :return: None
  5482. """
  5483. self.defaults.report_usage("on_file_openproject")
  5484. App.log.debug("on_file_openproject()")
  5485. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5486. try:
  5487. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5488. directory=self.get_last_folder(), filter=_filter_)
  5489. except TypeError:
  5490. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5491. # The Qt methods above will return a QString which can cause problems later.
  5492. # So far json.dump() will fail to serialize it.
  5493. # TODO: Improve the serialization methods and remove this fix.
  5494. filename = str(filename)
  5495. if filename == "":
  5496. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5497. else:
  5498. # self.worker_task.emit({'fcn': self.open_project,
  5499. # 'params': [filename]})
  5500. # The above was failing because open_project() is not
  5501. # thread safe. The new_project()
  5502. self.open_project(filename)
  5503. def on_fileopenhpgl2(self, signal, name=None):
  5504. """
  5505. File menu callback for opening a HPGL2.
  5506. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5507. :param name:
  5508. :return: None
  5509. """
  5510. self.defaults.report_usage("on_fileopenhpgl2")
  5511. App.log.debug("on_fileopenhpgl2()")
  5512. _filter_ = "HPGL2 Files (*.plt);;" \
  5513. "All Files (*.*)"
  5514. if name is None:
  5515. try:
  5516. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5517. directory=self.get_last_folder(),
  5518. filter=_filter_)
  5519. except TypeError:
  5520. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5521. filenames = [str(filename) for filename in filenames]
  5522. else:
  5523. filenames = [name]
  5524. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5525. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5526. _("Opening HPGL2 file.")),
  5527. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5528. color=QtGui.QColor("gray"))
  5529. if len(filenames) == 0:
  5530. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5531. else:
  5532. for filename in filenames:
  5533. if filename != '':
  5534. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5535. def on_file_openconfig(self, signal):
  5536. """
  5537. File menu callback for opening a config file.
  5538. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5539. :return: None
  5540. """
  5541. self.defaults.report_usage("on_file_openconfig")
  5542. App.log.debug("on_file_openconfig()")
  5543. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5544. try:
  5545. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5546. directory=self.data_path, filter=_filter_)
  5547. except TypeError:
  5548. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5549. filter=_filter_)
  5550. if filename == "":
  5551. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5552. else:
  5553. self.open_config_file(filename)
  5554. def on_file_exportsvg(self):
  5555. """
  5556. Callback for menu item File->Export SVG.
  5557. :return: None
  5558. """
  5559. self.defaults.report_usage("on_file_exportsvg")
  5560. App.log.debug("on_file_exportsvg()")
  5561. obj = self.collection.get_active()
  5562. if obj is None:
  5563. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5564. msg = _("Please Select a Geometry object to export")
  5565. msgbox = QtWidgets.QMessageBox()
  5566. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5567. msgbox.setInformativeText(msg)
  5568. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5569. msgbox.setDefaultButton(bt_ok)
  5570. msgbox.exec_()
  5571. return
  5572. # Check for more compatible types and add as required
  5573. if (not isinstance(obj, GeometryObject)
  5574. and not isinstance(obj, GerberObject)
  5575. and not isinstance(obj, CNCJobObject)
  5576. and not isinstance(obj, ExcellonObject)):
  5577. msg = '[ERROR_NOTCL] %s' % \
  5578. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5579. msgbox = QtWidgets.QMessageBox()
  5580. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5581. msgbox.setInformativeText(msg)
  5582. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5583. msgbox.setDefaultButton(bt_ok)
  5584. msgbox.exec_()
  5585. return
  5586. name = obj.options["name"]
  5587. _filter = "SVG File (*.svg);;All Files (*.*)"
  5588. try:
  5589. filename, _f = FCFileSaveDialog.get_saved_filename(
  5590. caption=_("Export SVG"),
  5591. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5592. ext_filter=_filter)
  5593. except TypeError:
  5594. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5595. filename = str(filename)
  5596. if filename == "":
  5597. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5598. return
  5599. else:
  5600. self.export_svg(name, filename)
  5601. if self.defaults["global_open_style"] is False:
  5602. self.file_opened.emit("SVG", filename)
  5603. self.file_saved.emit("SVG", filename)
  5604. def on_file_exportpng(self):
  5605. self.defaults.report_usage("on_file_exportpng")
  5606. App.log.debug("on_file_exportpng()")
  5607. self.date = str(datetime.today()).rpartition('.')[0]
  5608. self.date = ''.join(c for c in self.date if c not in ':-')
  5609. self.date = self.date.replace(' ', '_')
  5610. data = None
  5611. if self.is_legacy is False:
  5612. image = _screenshot(alpha=False)
  5613. data = np.asarray(image)
  5614. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5615. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5616. return
  5617. filter_ = "PNG File (*.png);;All Files (*.*)"
  5618. try:
  5619. filename, _f = FCFileSaveDialog.get_saved_filename(
  5620. caption=_("Export PNG Image"),
  5621. directory=self.get_last_save_folder() + '/png_' + self.date,
  5622. ext_filter=filter_)
  5623. except TypeError:
  5624. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  5625. filename = str(filename)
  5626. if filename == "":
  5627. self.inform.emit(_("Cancelled."))
  5628. return
  5629. else:
  5630. if self.is_legacy is False:
  5631. write_png(filename, data)
  5632. else:
  5633. self.plotcanvas.figure.savefig(filename)
  5634. if self.defaults["global_open_style"] is False:
  5635. self.file_opened.emit("png", filename)
  5636. self.file_saved.emit("png", filename)
  5637. def on_file_savegerber(self):
  5638. """
  5639. Callback for menu item in Project context menu.
  5640. :return: None
  5641. """
  5642. self.defaults.report_usage("on_file_savegerber")
  5643. App.log.debug("on_file_savegerber()")
  5644. obj = self.collection.get_active()
  5645. if obj is None:
  5646. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5647. return
  5648. # Check for more compatible types and add as required
  5649. if not isinstance(obj, GerberObject):
  5650. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5651. return
  5652. name = self.collection.get_active().options["name"]
  5653. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5654. try:
  5655. filename, _f = FCFileSaveDialog.get_saved_filename(
  5656. caption="Save Gerber source file",
  5657. directory=self.get_last_save_folder() + '/' + name,
  5658. ext_filter=_filter)
  5659. except TypeError:
  5660. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  5661. filename = str(filename)
  5662. if filename == "":
  5663. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5664. return
  5665. else:
  5666. self.save_source_file(name, filename)
  5667. if self.defaults["global_open_style"] is False:
  5668. self.file_opened.emit("Gerber", filename)
  5669. self.file_saved.emit("Gerber", filename)
  5670. def on_file_savescript(self):
  5671. """
  5672. Callback for menu item in Project context menu.
  5673. :return: None
  5674. """
  5675. self.defaults.report_usage("on_file_savescript")
  5676. App.log.debug("on_file_savescript()")
  5677. obj = self.collection.get_active()
  5678. if obj is None:
  5679. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5680. return
  5681. # Check for more compatible types and add as required
  5682. if not isinstance(obj, ScriptObject):
  5683. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5684. return
  5685. name = self.collection.get_active().options["name"]
  5686. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5687. try:
  5688. filename, _f = FCFileSaveDialog.get_saved_filename(
  5689. caption="Save Script source file",
  5690. directory=self.get_last_save_folder() + '/' + name,
  5691. ext_filter=_filter)
  5692. except TypeError:
  5693. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  5694. filename = str(filename)
  5695. if filename == "":
  5696. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5697. return
  5698. else:
  5699. self.save_source_file(name, filename)
  5700. if self.defaults["global_open_style"] is False:
  5701. self.file_opened.emit("Script", filename)
  5702. self.file_saved.emit("Script", filename)
  5703. def on_file_savedocument(self):
  5704. """
  5705. Callback for menu item in Project context menu.
  5706. :return: None
  5707. """
  5708. self.defaults.report_usage("on_file_savedocument")
  5709. App.log.debug("on_file_savedocument()")
  5710. obj = self.collection.get_active()
  5711. if obj is None:
  5712. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5713. return
  5714. # Check for more compatible types and add as required
  5715. if not isinstance(obj, ScriptObject):
  5716. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5717. return
  5718. name = self.collection.get_active().options["name"]
  5719. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5720. try:
  5721. filename, _f = FCFileSaveDialog.get_saved_filename(
  5722. caption="Save Document source file",
  5723. directory=self.get_last_save_folder() + '/' + name,
  5724. ext_filter=_filter)
  5725. except TypeError:
  5726. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  5727. ext_filter=_filter)
  5728. filename = str(filename)
  5729. if filename == "":
  5730. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5731. return
  5732. else:
  5733. self.save_source_file(name, filename)
  5734. if self.defaults["global_open_style"] is False:
  5735. self.file_opened.emit("Document", filename)
  5736. self.file_saved.emit("Document", filename)
  5737. def on_file_saveexcellon(self):
  5738. """
  5739. Callback for menu item in project context menu.
  5740. :return: None
  5741. """
  5742. self.defaults.report_usage("on_file_saveexcellon")
  5743. App.log.debug("on_file_saveexcellon()")
  5744. obj = self.collection.get_active()
  5745. if obj is None:
  5746. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5747. return
  5748. # Check for more compatible types and add as required
  5749. if not isinstance(obj, ExcellonObject):
  5750. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5751. return
  5752. name = self.collection.get_active().options["name"]
  5753. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5754. try:
  5755. filename, _f = FCFileSaveDialog.get_saved_filename(
  5756. caption=_("Save Excellon source file"),
  5757. directory=self.get_last_save_folder() + '/' + name,
  5758. ext_filter=_filter)
  5759. except TypeError:
  5760. filename, _f = FCFileSaveDialog.get_saved_filename(
  5761. caption=_("Save Excellon source file"), ext_filter=_filter)
  5762. filename = str(filename)
  5763. if filename == "":
  5764. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5765. return
  5766. else:
  5767. self.save_source_file(name, filename)
  5768. if self.defaults["global_open_style"] is False:
  5769. self.file_opened.emit("Excellon", filename)
  5770. self.file_saved.emit("Excellon", filename)
  5771. def on_file_exportexcellon(self):
  5772. """
  5773. Callback for menu item File->Export->Excellon.
  5774. :return: None
  5775. """
  5776. self.defaults.report_usage("on_file_exportexcellon")
  5777. App.log.debug("on_file_exportexcellon()")
  5778. obj = self.collection.get_active()
  5779. if obj is None:
  5780. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5781. return
  5782. # Check for more compatible types and add as required
  5783. if not isinstance(obj, ExcellonObject):
  5784. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5785. return
  5786. name = self.collection.get_active().options["name"]
  5787. _filter = self.defaults["excellon_save_filters"]
  5788. try:
  5789. filename, _f = FCFileSaveDialog.get_saved_filename(
  5790. caption=_("Export Excellon"),
  5791. directory=self.get_last_save_folder() + '/' + name,
  5792. ext_filter=_filter)
  5793. except TypeError:
  5794. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  5795. filename = str(filename)
  5796. if filename == "":
  5797. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5798. return
  5799. else:
  5800. used_extension = filename.rpartition('.')[2]
  5801. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5802. self.export_excellon(name, filename)
  5803. if self.defaults["global_open_style"] is False:
  5804. self.file_opened.emit("Excellon", filename)
  5805. self.file_saved.emit("Excellon", filename)
  5806. def on_file_exportgerber(self):
  5807. """
  5808. Callback for menu item File->Export->Gerber.
  5809. :return: None
  5810. """
  5811. self.defaults.report_usage("on_file_exportgerber")
  5812. App.log.debug("on_file_exportgerber()")
  5813. obj = self.collection.get_active()
  5814. if obj is None:
  5815. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5816. return
  5817. # Check for more compatible types and add as required
  5818. if not isinstance(obj, GerberObject):
  5819. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5820. return
  5821. name = self.collection.get_active().options["name"]
  5822. _filter_ = self.defaults['gerber_save_filters']
  5823. try:
  5824. filename, _f = FCFileSaveDialog.get_saved_filename(
  5825. caption=_("Export Gerber"),
  5826. directory=self.get_last_save_folder() + '/' + name,
  5827. ext_filter=_filter_)
  5828. except TypeError:
  5829. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  5830. filename = str(filename)
  5831. if filename == "":
  5832. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5833. return
  5834. else:
  5835. used_extension = filename.rpartition('.')[2]
  5836. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5837. self.export_gerber(name, filename)
  5838. if self.defaults["global_open_style"] is False:
  5839. self.file_opened.emit("Gerber", filename)
  5840. self.file_saved.emit("Gerber", filename)
  5841. def on_file_exportdxf(self):
  5842. """
  5843. Callback for menu item File->Export DXF.
  5844. :return: None
  5845. """
  5846. self.defaults.report_usage("on_file_exportdxf")
  5847. App.log.debug("on_file_exportdxf()")
  5848. obj = self.collection.get_active()
  5849. if obj is None:
  5850. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5851. msg = _("Please Select a Geometry object to export")
  5852. msgbox = QtWidgets.QMessageBox()
  5853. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5854. msgbox.setInformativeText(msg)
  5855. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5856. msgbox.setDefaultButton(bt_ok)
  5857. msgbox.exec_()
  5858. return
  5859. # Check for more compatible types and add as required
  5860. if not isinstance(obj, GeometryObject):
  5861. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5862. msgbox = QtWidgets.QMessageBox()
  5863. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5864. msgbox.setInformativeText(msg)
  5865. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5866. msgbox.setDefaultButton(bt_ok)
  5867. msgbox.exec_()
  5868. return
  5869. name = self.collection.get_active().options["name"]
  5870. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5871. try:
  5872. filename, _f = FCFileSaveDialog.get_saved_filename(
  5873. caption=_("Export DXF"),
  5874. directory=self.get_last_save_folder() + '/' + name,
  5875. ext_filter=_filter_)
  5876. except TypeError:
  5877. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  5878. filename = str(filename)
  5879. if filename == "":
  5880. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5881. return
  5882. else:
  5883. self.export_dxf(name, filename)
  5884. if self.defaults["global_open_style"] is False:
  5885. self.file_opened.emit("DXF", filename)
  5886. self.file_saved.emit("DXF", filename)
  5887. def on_file_importsvg(self, type_of_obj):
  5888. """
  5889. Callback for menu item File->Import SVG.
  5890. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5891. :type type_of_obj: str
  5892. :return: None
  5893. """
  5894. self.defaults.report_usage("on_file_importsvg")
  5895. App.log.debug("on_file_importsvg()")
  5896. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  5897. try:
  5898. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5899. directory=self.get_last_folder(), filter=_filter_)
  5900. except TypeError:
  5901. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5902. filter=_filter_)
  5903. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5904. type_of_obj = "geometry"
  5905. filenames = [str(filename) for filename in filenames]
  5906. if len(filenames) == 0:
  5907. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5908. else:
  5909. for filename in filenames:
  5910. if filename != '':
  5911. self.worker_task.emit({'fcn': self.import_svg,
  5912. 'params': [filename, type_of_obj]})
  5913. def on_file_importdxf(self, type_of_obj):
  5914. """
  5915. Callback for menu item File->Import DXF.
  5916. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5917. :type type_of_obj: str
  5918. :return: None
  5919. """
  5920. self.defaults.report_usage("on_file_importdxf")
  5921. App.log.debug("on_file_importdxf()")
  5922. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5923. try:
  5924. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5925. directory=self.get_last_folder(),
  5926. filter=_filter_)
  5927. except TypeError:
  5928. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5929. filter=_filter_)
  5930. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5931. type_of_obj = "geometry"
  5932. filenames = [str(filename) for filename in filenames]
  5933. if len(filenames) == 0:
  5934. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5935. else:
  5936. for filename in filenames:
  5937. if filename != '':
  5938. self.worker_task.emit({'fcn': self.import_dxf,
  5939. 'params': [filename, type_of_obj]})
  5940. # ###############################################################################################################
  5941. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5942. # ###############################################################################################################
  5943. def init_code_editor(self, name):
  5944. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  5945. # add the tab if it was closed
  5946. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5947. self.text_editor_tab.setObjectName('text_editor_tab')
  5948. # delete the absolute and relative position and messages in the infobar
  5949. self.ui.position_label.setText("")
  5950. # self.ui.rel_position_label.setText("")
  5951. # first clear previous text in text editor (if any)
  5952. self.text_editor_tab.code_editor.clear()
  5953. self.text_editor_tab.code_editor.setReadOnly(False)
  5954. self.toggle_codeeditor = True
  5955. self.text_editor_tab.code_editor.completer_enable = False
  5956. self.text_editor_tab.buttonRun.hide()
  5957. # make sure to keep a reference to the code editor
  5958. self.reference_code_editor = self.text_editor_tab.code_editor
  5959. # Switch plot_area to CNCJob tab
  5960. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5961. def on_view_source(self):
  5962. """
  5963. Called when the user wants to see the source file of the selected object
  5964. :return:
  5965. """
  5966. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5967. self.proc_container.view.set_busy(_("Loading..."))
  5968. try:
  5969. obj = self.collection.get_active()
  5970. except Exception as e:
  5971. log.debug("App.on_view_source() --> %s" % str(e))
  5972. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5973. return 'fail'
  5974. if obj is None:
  5975. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5976. return 'fail'
  5977. flt = "All Files (*.*)"
  5978. if obj.kind == 'gerber':
  5979. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5980. elif obj.kind == 'excellon':
  5981. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5982. elif obj.kind == 'cncjob':
  5983. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5984. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  5985. # add the tab if it was closed
  5986. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5987. self.source_editor_tab.setObjectName('source_editor_tab')
  5988. # delete the absolute and relative position and messages in the infobar
  5989. self.ui.position_label.setText("")
  5990. # self.ui.rel_position_label.setText("")
  5991. # first clear previous text in text editor (if any)
  5992. self.source_editor_tab.code_editor.clear()
  5993. self.source_editor_tab.code_editor.setReadOnly(False)
  5994. self.source_editor_tab.code_editor.completer_enable = False
  5995. self.source_editor_tab.buttonRun.hide()
  5996. # Switch plot_area to CNCJob tab
  5997. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5998. try:
  5999. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6000. except TypeError:
  6001. pass
  6002. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6003. try:
  6004. self.source_editor_tab.buttonSave.clicked.disconnect()
  6005. except TypeError:
  6006. pass
  6007. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6008. # then append the text from GCode to the text editor
  6009. if obj.kind == 'cncjob':
  6010. try:
  6011. file = obj.export_gcode(
  6012. preamble=self.defaults["cncjob_prepend"],
  6013. postamble=self.defaults["cncjob_append"],
  6014. to_file=True)
  6015. if file == 'fail':
  6016. return 'fail'
  6017. except AttributeError:
  6018. self.inform.emit('[WARNING_NOTCL] %s' %
  6019. _("There is no selected object for which to see it's source file code."))
  6020. return 'fail'
  6021. else:
  6022. try:
  6023. file = StringIO(obj.source_file)
  6024. except (AttributeError, TypeError):
  6025. self.inform.emit('[WARNING_NOTCL] %s' %
  6026. _("There is no selected object for which to see it's source file code."))
  6027. return 'fail'
  6028. self.source_editor_tab.t_frame.hide()
  6029. try:
  6030. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6031. # for line in file:
  6032. # QtWidgets.QApplication.processEvents()
  6033. # proc_line = str(line).strip('\n')
  6034. # self.source_editor_tab.code_editor.append(proc_line)
  6035. except Exception as e:
  6036. log.debug('App.on_view_source() -->%s' % str(e))
  6037. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6038. return
  6039. self.source_editor_tab.handleTextChanged()
  6040. self.source_editor_tab.t_frame.show()
  6041. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6042. self.proc_container.view.set_idle()
  6043. # self.ui.show()
  6044. def on_toggle_code_editor(self):
  6045. self.defaults.report_usage("on_toggle_code_editor()")
  6046. if self.toggle_codeeditor is False:
  6047. self.init_code_editor(name=_("Code Editor"))
  6048. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6049. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6050. self.text_editor_tab.buttonSave.clicked.disconnect()
  6051. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6052. else:
  6053. for idx in range(self.ui.plot_tab_area.count()):
  6054. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6055. self.ui.plot_tab_area.closeTab(idx)
  6056. break
  6057. self.toggle_codeeditor = False
  6058. def on_code_editor_close(self):
  6059. self.toggle_codeeditor = False
  6060. def goto_text_line(self):
  6061. """
  6062. Will scroll a text to the specified text line.
  6063. :return: None
  6064. """
  6065. dia_box = Dialog_box(title=_("Go to Line ..."),
  6066. label=_("Line:"),
  6067. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6068. initial_text='')
  6069. try:
  6070. line = int(dia_box.location) - 1
  6071. except (ValueError, TypeError):
  6072. line = 0
  6073. if dia_box.ok:
  6074. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6075. # at the top of the window
  6076. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6077. # get the document() of the TextEditor
  6078. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6079. # create a Text Cursor based on the searched line
  6080. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6081. # set cursor of the code editor with the cursor at the searcehd line
  6082. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6083. def on_filenewscript(self, silent=False):
  6084. """
  6085. Will create a new script file and open it in the Code Editor
  6086. :param silent: if True will not display status messages
  6087. :return: None
  6088. """
  6089. if silent is False:
  6090. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6091. # delete the absolute and relative position and messages in the infobar
  6092. self.ui.position_label.setText("")
  6093. # self.ui.rel_position_label.setText("")
  6094. self.app_obj.new_script_object()
  6095. # script_text = script_obj.source_file
  6096. #
  6097. # self.proc_container.view.set_busy(_("Loading..."))
  6098. # script_obj.script_editor_tab.t_frame.hide()
  6099. #
  6100. # script_obj.script_editor_tab.t_frame.show()
  6101. # self.proc_container.view.set_idle()
  6102. def on_fileopenscript(self, name=None, silent=False):
  6103. """
  6104. Will open a Tcl script file into the Code Editor
  6105. :param silent: if True will not display status messages
  6106. :param name: name of a Tcl script file to open
  6107. :return: None
  6108. """
  6109. self.defaults.report_usage("on_fileopenscript")
  6110. App.log.debug("on_fileopenscript()")
  6111. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6112. "All Files (*.*)"
  6113. if name:
  6114. filenames = [name]
  6115. else:
  6116. try:
  6117. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6118. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6119. except TypeError:
  6120. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6121. if len(filenames) == 0:
  6122. if silent is False:
  6123. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6124. else:
  6125. for filename in filenames:
  6126. if filename != '':
  6127. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6128. def on_fileopenscript_example(self, name=None, silent=False):
  6129. """
  6130. Will open a Tcl script file into the Code Editor
  6131. :param silent: if True will not display status messages
  6132. :param name: name of a Tcl script file to open
  6133. :return:
  6134. """
  6135. self.defaults.report_usage("on_fileopenscript_example")
  6136. log.debug("on_fileopenscript_example()")
  6137. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6138. "All Files (*.*)"
  6139. # test if the app was frozen and choose the path for the configuration file
  6140. if getattr(sys, "frozen", False) is True:
  6141. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6142. else:
  6143. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6144. if name:
  6145. filenames = [name]
  6146. else:
  6147. try:
  6148. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6149. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6150. except TypeError:
  6151. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6152. if len(filenames) == 0:
  6153. if silent is False:
  6154. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6155. else:
  6156. for filename in filenames:
  6157. if filename != '':
  6158. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6159. def on_filerunscript(self, name=None, silent=False):
  6160. """
  6161. File menu callback for loading and running a TCL script.
  6162. :param silent: if True will not display status messages
  6163. :param name: name of a Tcl script file to be run by FlatCAM
  6164. :return: None
  6165. """
  6166. self.defaults.report_usage("on_filerunscript")
  6167. App.log.debug("on_file_runscript()")
  6168. if name:
  6169. filename = name
  6170. if self.cmd_line_headless != 1:
  6171. self.splash.showMessage('%s: %ssec\n%s' %
  6172. (_("Canvas initialization started.\n"
  6173. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6174. _("Executing ScriptObject file.")
  6175. ),
  6176. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6177. color=QtGui.QColor("gray"))
  6178. else:
  6179. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6180. "All Files (*.*)"
  6181. try:
  6182. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6183. directory=self.get_last_folder(), filter=_filter_)
  6184. except TypeError:
  6185. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6186. # The Qt methods above will return a QString which can cause problems later.
  6187. # So far json.dump() will fail to serialize it.
  6188. filename = str(filename)
  6189. if filename == "":
  6190. if silent is False:
  6191. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6192. else:
  6193. if self.cmd_line_headless != 1:
  6194. if self.ui.shell_dock.isHidden():
  6195. self.ui.shell_dock.show()
  6196. try:
  6197. with open(filename, "r") as tcl_script:
  6198. cmd_line_shellfile_content = tcl_script.read()
  6199. if self.cmd_line_headless != 1:
  6200. self.shell.exec_command(cmd_line_shellfile_content)
  6201. else:
  6202. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6203. if silent is False:
  6204. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6205. except Exception as e:
  6206. log.debug("App.on_filerunscript() -> %s" % str(e))
  6207. sys.exit(2)
  6208. def on_file_saveproject(self, silent=False):
  6209. """
  6210. Callback for menu item File->Save Project. Saves the project to
  6211. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6212. if set to None. The project is saved by calling ``self.save_project()``.
  6213. :param silent: if True will not display status messages
  6214. :return: None
  6215. """
  6216. self.defaults.report_usage("on_file_saveproject")
  6217. if self.project_filename is None:
  6218. self.on_file_saveprojectas()
  6219. else:
  6220. self.worker_task.emit({'fcn': self.save_project,
  6221. 'params': [self.project_filename, silent]})
  6222. if self.defaults["global_open_style"] is False:
  6223. self.file_opened.emit("project", self.project_filename)
  6224. self.file_saved.emit("project", self.project_filename)
  6225. self.set_ui_title(name=self.project_filename)
  6226. self.should_we_save = False
  6227. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6228. """
  6229. Callback for menu item File->Save Project As... Opens a file
  6230. chooser and saves the project to the given file via
  6231. ``self.save_project()``.
  6232. :param make_copy if to be create a copy of the project; boolean
  6233. :param use_thread: if to be run in a separate thread; boolean
  6234. :param quit_action: if to be followed by quiting the application; boolean
  6235. :return: None
  6236. """
  6237. self.defaults.report_usage("on_file_saveprojectas")
  6238. self.date = str(datetime.today()).rpartition('.')[0]
  6239. self.date = ''.join(c for c in self.date if c not in ':-')
  6240. self.date = self.date.replace(' ', '_')
  6241. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6242. try:
  6243. filename, _f = FCFileSaveDialog.get_saved_filename(
  6244. caption=_("Save Project As ..."),
  6245. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6246. proj=_("Project")),
  6247. ext_filter=filter_
  6248. )
  6249. except TypeError:
  6250. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6251. filename = str(filename)
  6252. if filename == '':
  6253. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6254. return
  6255. if use_thread is True:
  6256. self.worker_task.emit({'fcn': self.save_project,
  6257. 'params': [filename, quit_action]})
  6258. else:
  6259. self.save_project(filename, quit_action)
  6260. # self.save_project(filename)
  6261. if self.defaults["global_open_style"] is False:
  6262. self.file_opened.emit("project", filename)
  6263. self.file_saved.emit("project", filename)
  6264. if not make_copy:
  6265. self.project_filename = filename
  6266. self.set_ui_title(name=self.project_filename)
  6267. self.should_we_save = False
  6268. def on_file_save_objects_pdf(self, use_thread=True):
  6269. self.date = str(datetime.today()).rpartition('.')[0]
  6270. self.date = ''.join(c for c in self.date if c not in ':-')
  6271. self.date = self.date.replace(' ', '_')
  6272. try:
  6273. obj_selection = self.collection.get_selected()
  6274. if len(obj_selection) == 1:
  6275. obj_name = str(obj_selection[0].options['name'])
  6276. else:
  6277. obj_name = _("FlatCAM objects print")
  6278. except AttributeError as err:
  6279. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6280. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6281. return
  6282. if not obj_selection:
  6283. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6284. return
  6285. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6286. try:
  6287. filename, _f = FCFileSaveDialog.get_saved_filename(
  6288. caption=_("Save Object as PDF ..."),
  6289. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6290. obj_name=obj_name,
  6291. date=self.date),
  6292. ext_filter=filter_
  6293. )
  6294. except TypeError:
  6295. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6296. filename = str(filename)
  6297. if filename == '':
  6298. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6299. return
  6300. if use_thread is True:
  6301. self.proc_container.new(_("Printing PDF ... Please wait."))
  6302. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6303. else:
  6304. self.save_pdf(filename, obj_selection)
  6305. # self.save_project(filename)
  6306. if self.defaults["global_open_style"] is False:
  6307. self.file_opened.emit("pdf", filename)
  6308. self.file_saved.emit("pdf", filename)
  6309. def save_pdf(self, file_name, obj_selection):
  6310. p_size = self.defaults['global_workspaceT']
  6311. orientation = self.defaults['global_workspace_orientation']
  6312. color = 'black'
  6313. transparency_level = 1.0
  6314. self.pagesize = {}
  6315. self.pagesize.update(
  6316. {
  6317. 'Bounds': None,
  6318. 'A0': (841 * mm, 1189 * mm),
  6319. 'A1': (594 * mm, 841 * mm),
  6320. 'A2': (420 * mm, 594 * mm),
  6321. 'A3': (297 * mm, 420 * mm),
  6322. 'A4': (210 * mm, 297 * mm),
  6323. 'A5': (148 * mm, 210 * mm),
  6324. 'A6': (105 * mm, 148 * mm),
  6325. 'A7': (74 * mm, 105 * mm),
  6326. 'A8': (52 * mm, 74 * mm),
  6327. 'A9': (37 * mm, 52 * mm),
  6328. 'A10': (26 * mm, 37 * mm),
  6329. 'B0': (1000 * mm, 1414 * mm),
  6330. 'B1': (707 * mm, 1000 * mm),
  6331. 'B2': (500 * mm, 707 * mm),
  6332. 'B3': (353 * mm, 500 * mm),
  6333. 'B4': (250 * mm, 353 * mm),
  6334. 'B5': (176 * mm, 250 * mm),
  6335. 'B6': (125 * mm, 176 * mm),
  6336. 'B7': (88 * mm, 125 * mm),
  6337. 'B8': (62 * mm, 88 * mm),
  6338. 'B9': (44 * mm, 62 * mm),
  6339. 'B10': (31 * mm, 44 * mm),
  6340. 'C0': (917 * mm, 1297 * mm),
  6341. 'C1': (648 * mm, 917 * mm),
  6342. 'C2': (458 * mm, 648 * mm),
  6343. 'C3': (324 * mm, 458 * mm),
  6344. 'C4': (229 * mm, 324 * mm),
  6345. 'C5': (162 * mm, 229 * mm),
  6346. 'C6': (114 * mm, 162 * mm),
  6347. 'C7': (81 * mm, 114 * mm),
  6348. 'C8': (57 * mm, 81 * mm),
  6349. 'C9': (40 * mm, 57 * mm),
  6350. 'C10': (28 * mm, 40 * mm),
  6351. # American paper sizes
  6352. 'LETTER': (8.5 * inch, 11 * inch),
  6353. 'LEGAL': (8.5 * inch, 14 * inch),
  6354. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6355. # From https://en.wikipedia.org/wiki/Paper_size
  6356. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6357. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6358. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6359. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6360. 'LEDGER': (17 * inch, 11 * inch),
  6361. }
  6362. )
  6363. exported_svg = []
  6364. for obj in obj_selection:
  6365. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6366. scale_factor_x=None, scale_factor_y=None,
  6367. skew_factor_x=None, skew_factor_y=None,
  6368. mirror=None)
  6369. if obj.kind.lower() == 'gerber':
  6370. # color = self.defaults["gerber_plot_fill"][:-2]
  6371. color = obj.fill_color[:-2]
  6372. elif obj.kind.lower() == 'excellon':
  6373. color = '#C40000'
  6374. elif obj.kind.lower() == 'geometry':
  6375. color = self.defaults["global_draw_color"]
  6376. # Change the attributes of the exported SVG
  6377. # We don't need stroke-width
  6378. # We set opacity to maximum
  6379. # We set the colour to WHITE
  6380. root = ET.fromstring(svg_obj)
  6381. for child in root:
  6382. child.set('fill', str(color))
  6383. child.set('opacity', str(transparency_level))
  6384. child.set('stroke', str(color))
  6385. exported_svg.append(ET.tostring(root))
  6386. xmin = Inf
  6387. ymin = Inf
  6388. xmax = -Inf
  6389. ymax = -Inf
  6390. for obj in obj_selection:
  6391. try:
  6392. gxmin, gymin, gxmax, gymax = obj.bounds()
  6393. xmin = min([xmin, gxmin])
  6394. ymin = min([ymin, gymin])
  6395. xmax = max([xmax, gxmax])
  6396. ymax = max([ymax, gymax])
  6397. except Exception as e:
  6398. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6399. # Determine bounding area for svg export
  6400. bounds = [xmin, ymin, xmax, ymax]
  6401. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6402. # This contain the measure units
  6403. uom = obj_selection[0].units.lower()
  6404. # Define a boundary around SVG of about 1.0mm (~39mils)
  6405. if uom in "mm":
  6406. boundary = 1.0
  6407. else:
  6408. boundary = 0.0393701
  6409. # Convert everything to strings for use in the xml doc
  6410. svgwidth = str(size[0] + (2 * boundary))
  6411. svgheight = str(size[1] + (2 * boundary))
  6412. minx = str(bounds[0] - boundary)
  6413. miny = str(bounds[1] + boundary + size[1])
  6414. # Add a SVG Header and footer to the svg output from shapely
  6415. # The transform flips the Y Axis so that everything renders
  6416. # properly within svg apps such as inkscape
  6417. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6418. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6419. svg_header += 'width="' + svgwidth + uom + '" '
  6420. svg_header += 'height="' + svgheight + uom + '" '
  6421. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6422. svg_header += '>'
  6423. svg_header += '<g transform="scale(1,-1)">'
  6424. svg_footer = '</g> </svg>'
  6425. svg_elem = str(svg_header)
  6426. for svg_item in exported_svg:
  6427. svg_elem += str(svg_item)
  6428. svg_elem += str(svg_footer)
  6429. # Parse the xml through a xml parser just to add line feeds
  6430. # and to make it look more pretty for the output
  6431. doc = parse_xml_string(svg_elem)
  6432. doc_final = doc.toprettyxml()
  6433. try:
  6434. if self.defaults['units'].upper() == 'IN':
  6435. unit = inch
  6436. else:
  6437. unit = mm
  6438. doc_final = StringIO(doc_final)
  6439. drawing = svg2rlg(doc_final)
  6440. if p_size == 'Bounds':
  6441. renderPDF.drawToFile(drawing, file_name)
  6442. else:
  6443. if orientation == 'p':
  6444. page_size = portrait(self.pagesize[p_size])
  6445. else:
  6446. page_size = landscape(self.pagesize[p_size])
  6447. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6448. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6449. renderPDF.draw(drawing, my_canvas, 0, 0)
  6450. my_canvas.save()
  6451. except Exception as e:
  6452. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6453. return 'fail'
  6454. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6455. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6456. """
  6457. Exports a Geometry Object to an SVG file.
  6458. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6459. :param filename: Path to the SVG file to save to.
  6460. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6461. :return:
  6462. """
  6463. self.defaults.report_usage("export_svg()")
  6464. if filename is None:
  6465. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6466. is not None else self.defaults["global_last_folder"]
  6467. self.log.debug("export_svg()")
  6468. try:
  6469. obj = self.collection.get_by_name(str(obj_name))
  6470. except Exception:
  6471. # TODO: The return behavior has not been established... should raise exception?
  6472. return "Could not retrieve object: %s" % obj_name
  6473. with self.proc_container.new(_("Exporting SVG")) as proc:
  6474. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6475. # Determine bounding area for svg export
  6476. bounds = obj.bounds()
  6477. size = obj.size()
  6478. # Convert everything to strings for use in the xml doc
  6479. svgwidth = str(size[0])
  6480. svgheight = str(size[1])
  6481. minx = str(bounds[0])
  6482. miny = str(bounds[1] - size[1])
  6483. uom = obj.units.lower()
  6484. # Add a SVG Header and footer to the svg output from shapely
  6485. # The transform flips the Y Axis so that everything renders
  6486. # properly within svg apps such as inkscape
  6487. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6488. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6489. svg_header += 'width="' + svgwidth + uom + '" '
  6490. svg_header += 'height="' + svgheight + uom + '" '
  6491. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6492. svg_header += '<g transform="scale(1,-1)">'
  6493. svg_footer = '</g> </svg>'
  6494. svg_elem = svg_header + exported_svg + svg_footer
  6495. # Parse the xml through a xml parser just to add line feeds
  6496. # and to make it look more pretty for the output
  6497. svgcode = parse_xml_string(svg_elem)
  6498. svgcode = svgcode.toprettyxml()
  6499. try:
  6500. with open(filename, 'w') as fp:
  6501. fp.write(svgcode)
  6502. except PermissionError:
  6503. self.inform.emit('[WARNING] %s' %
  6504. _("Permission denied, saving not possible.\n"
  6505. "Most likely another app is holding the file open and not accessible."))
  6506. return 'fail'
  6507. if self.defaults["global_open_style"] is False:
  6508. self.file_opened.emit("SVG", filename)
  6509. self.file_saved.emit("SVG", filename)
  6510. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6511. def save_source_file(self, obj_name, filename, use_thread=True):
  6512. """
  6513. Exports a FlatCAM Object to an Gerber/Excellon file.
  6514. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6515. :param filename: Path to the Gerber file to save to.
  6516. :param use_thread: if to be run in a separate thread
  6517. :return:
  6518. """
  6519. self.defaults.report_usage("save source file()")
  6520. if filename is None:
  6521. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6522. is not None else self.defaults["global_last_folder"]
  6523. self.log.debug("save source file()")
  6524. obj = self.collection.get_by_name(obj_name)
  6525. file_string = StringIO(obj.source_file)
  6526. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6527. if file_string.getvalue() == '':
  6528. self.inform.emit('[ERROR_NOTCL] %s' %
  6529. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6530. return 'fail'
  6531. try:
  6532. with open(filename, 'w') as file:
  6533. file.writelines('G04*\n')
  6534. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6535. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6536. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6537. file.writelines('G04 Created on : %s*\n' % time_string)
  6538. for line in file_string:
  6539. file.writelines(line)
  6540. except PermissionError:
  6541. self.inform.emit('[WARNING] %s' %
  6542. _("Permission denied, saving not possible.\n"
  6543. "Most likely another app is holding the file open and not accessible."))
  6544. return 'fail'
  6545. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6546. """
  6547. Exports a Excellon Object to an Excellon file.
  6548. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6549. :param filename: Path to the Excellon file to save to.
  6550. :param local_use:
  6551. :param use_thread: if to be run in a separate thread
  6552. :return:
  6553. """
  6554. self.defaults.report_usage("export_excellon()")
  6555. if filename is None:
  6556. if self.defaults["global_last_save_folder"]:
  6557. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6558. else:
  6559. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6560. self.log.debug("export_excellon()")
  6561. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6562. self.defaults["excellon_exp_decimals"]
  6563. )
  6564. if local_use is None:
  6565. try:
  6566. obj = self.collection.get_by_name(str(obj_name))
  6567. except Exception:
  6568. return "Could not retrieve object: %s" % obj_name
  6569. else:
  6570. obj = local_use
  6571. if not isinstance(obj, ExcellonObject):
  6572. self.inform.emit('[ERROR_NOTCL] %s' %
  6573. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6574. return
  6575. # updated units
  6576. eunits = self.defaults["excellon_exp_units"]
  6577. ewhole = self.defaults["excellon_exp_integer"]
  6578. efract = self.defaults["excellon_exp_decimals"]
  6579. ezeros = self.defaults["excellon_exp_zeros"]
  6580. eformat = self.defaults["excellon_exp_format"]
  6581. slot_type = self.defaults["excellon_exp_slot_type"]
  6582. fc_units = self.defaults['units'].upper()
  6583. if fc_units == 'MM':
  6584. factor = 1 if eunits == 'METRIC' else 0.03937
  6585. else:
  6586. factor = 25.4 if eunits == 'METRIC' else 1
  6587. def make_excellon():
  6588. try:
  6589. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6590. header = 'M48\n'
  6591. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6592. (str(self.version), str(self.version_date))
  6593. header += ';Filename: %s' % str(obj_name) + '\n'
  6594. header += ';Created on : %s' % time_str + '\n'
  6595. if eformat == 'dec':
  6596. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6597. header += eunits + '\n'
  6598. for tool in obj.tools:
  6599. if eunits == 'METRIC':
  6600. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6601. tool=str(tool),
  6602. dec=2)
  6603. else:
  6604. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6605. tool=str(tool),
  6606. dec=4)
  6607. else:
  6608. if ezeros == 'LZ':
  6609. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6610. form='ndec', e_zeros='LZ', factor=factor,
  6611. slot_type=slot_type)
  6612. header += '%s,%s\n' % (eunits, 'LZ')
  6613. header += format_exc
  6614. for tool in obj.tools:
  6615. if eunits == 'METRIC':
  6616. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6617. tool=str(tool),
  6618. dec=2)
  6619. else:
  6620. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6621. tool=str(tool),
  6622. dec=4)
  6623. else:
  6624. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6625. form='ndec', e_zeros='TZ', factor=factor,
  6626. slot_type=slot_type)
  6627. header += '%s,%s\n' % (eunits, 'TZ')
  6628. header += format_exc
  6629. for tool in obj.tools:
  6630. if eunits == 'METRIC':
  6631. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6632. tool=str(tool),
  6633. dec=2)
  6634. else:
  6635. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6636. tool=str(tool),
  6637. dec=4)
  6638. header += '%\n'
  6639. footer = 'M30\n'
  6640. exported_excellon = header
  6641. exported_excellon += excellon_code
  6642. exported_excellon += footer
  6643. if local_use is None:
  6644. try:
  6645. with open(filename, 'w') as fp:
  6646. fp.write(exported_excellon)
  6647. except PermissionError:
  6648. self.inform.emit('[WARNING] %s' %
  6649. _("Permission denied, saving not possible.\n"
  6650. "Most likely another app is holding the file open and not accessible."))
  6651. return 'fail'
  6652. if self.defaults["global_open_style"] is False:
  6653. self.file_opened.emit("Excellon", filename)
  6654. self.file_saved.emit("Excellon", filename)
  6655. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6656. else:
  6657. return exported_excellon
  6658. except Exception as e:
  6659. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6660. return 'fail'
  6661. if use_thread is True:
  6662. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6663. def job_thread_exc(app_obj):
  6664. ret = make_excellon()
  6665. if ret == 'fail':
  6666. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6667. return
  6668. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6669. else:
  6670. eret = make_excellon()
  6671. if eret == 'fail':
  6672. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6673. return 'fail'
  6674. if local_use is not None:
  6675. return eret
  6676. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6677. """
  6678. Exports a Gerber Object to an Gerber file.
  6679. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6680. :param filename: Path to the Gerber file to save to.
  6681. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6682. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6683. :param use_thread: if to be run in a separate thread
  6684. :return:
  6685. """
  6686. self.defaults.report_usage("export_gerber()")
  6687. if filename is None:
  6688. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6689. is not None else self.defaults["global_last_folder"]
  6690. self.log.debug("export_gerber()")
  6691. if local_use is None:
  6692. try:
  6693. obj = self.collection.get_by_name(str(obj_name))
  6694. except Exception:
  6695. return "Could not retrieve object: %s" % obj_name
  6696. else:
  6697. obj = local_use
  6698. # updated units
  6699. gunits = self.defaults["gerber_exp_units"]
  6700. gwhole = self.defaults["gerber_exp_integer"]
  6701. gfract = self.defaults["gerber_exp_decimals"]
  6702. gzeros = self.defaults["gerber_exp_zeros"]
  6703. fc_units = self.defaults['units'].upper()
  6704. if fc_units == 'MM':
  6705. factor = 1 if gunits == 'MM' else 0.03937
  6706. else:
  6707. factor = 25.4 if gunits == 'MM' else 1
  6708. def make_gerber():
  6709. try:
  6710. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6711. header = 'G04*\n'
  6712. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6713. (str(self.version), str(self.version_date))
  6714. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6715. header += 'G04 Created on : %s*' % time_str + '\n'
  6716. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6717. header += "%MO{units}*%\n".format(units=gunits)
  6718. for apid in obj.apertures:
  6719. if obj.apertures[apid]['type'] == 'C':
  6720. header += "%ADD{apid}{type},{size}*%\n".format(
  6721. apid=str(apid),
  6722. type='C',
  6723. size=(factor * obj.apertures[apid]['size'])
  6724. )
  6725. elif obj.apertures[apid]['type'] == 'R':
  6726. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6727. apid=str(apid),
  6728. type='R',
  6729. width=(factor * obj.apertures[apid]['width']),
  6730. height=(factor * obj.apertures[apid]['height'])
  6731. )
  6732. elif obj.apertures[apid]['type'] == 'O':
  6733. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6734. apid=str(apid),
  6735. type='O',
  6736. width=(factor * obj.apertures[apid]['width']),
  6737. height=(factor * obj.apertures[apid]['height'])
  6738. )
  6739. header += '\n'
  6740. # obsolete units but some software may need it
  6741. if gunits == 'IN':
  6742. header += 'G70*\n'
  6743. else:
  6744. header += 'G71*\n'
  6745. # Absolute Mode
  6746. header += 'G90*\n'
  6747. header += 'G01*\n'
  6748. # positive polarity
  6749. header += '%LPD*%\n'
  6750. footer = 'M02*\n'
  6751. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6752. exported_gerber = header
  6753. exported_gerber += gerber_code
  6754. exported_gerber += footer
  6755. if local_use is None:
  6756. try:
  6757. with open(filename, 'w') as fp:
  6758. fp.write(exported_gerber)
  6759. except PermissionError:
  6760. self.inform.emit('[WARNING] %s' %
  6761. _("Permission denied, saving not possible.\n"
  6762. "Most likely another app is holding the file open and not accessible."))
  6763. return 'fail'
  6764. if self.defaults["global_open_style"] is False:
  6765. self.file_opened.emit("Gerber", filename)
  6766. self.file_saved.emit("Gerber", filename)
  6767. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6768. else:
  6769. return exported_gerber
  6770. except Exception as e:
  6771. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6772. return 'fail'
  6773. if use_thread is True:
  6774. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6775. def job_thread_grb(app_obj):
  6776. ret = make_gerber()
  6777. if ret == 'fail':
  6778. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6779. return
  6780. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6781. else:
  6782. gret = make_gerber()
  6783. if gret == 'fail':
  6784. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6785. return 'fail'
  6786. if local_use is not None:
  6787. return gret
  6788. def export_dxf(self, obj_name, filename, use_thread=True):
  6789. """
  6790. Exports a Geometry Object to an DXF file.
  6791. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6792. :param filename: Path to the DXF file to save to.
  6793. :param use_thread: if to be run in a separate thread
  6794. :return:
  6795. """
  6796. self.defaults.report_usage("export_dxf()")
  6797. if filename is None:
  6798. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6799. is not None else self.defaults["global_last_folder"]
  6800. self.log.debug("export_dxf()")
  6801. try:
  6802. obj = self.collection.get_by_name(str(obj_name))
  6803. except Exception:
  6804. # TODO: The return behavior has not been established... should raise exception?
  6805. return "Could not retrieve object: %s" % obj_name
  6806. def make_dxf():
  6807. try:
  6808. dxf_code = obj.export_dxf()
  6809. dxf_code.saveas(filename)
  6810. if self.defaults["global_open_style"] is False:
  6811. self.file_opened.emit("DXF", filename)
  6812. self.file_saved.emit("DXF", filename)
  6813. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6814. except Exception:
  6815. return 'fail'
  6816. if use_thread is True:
  6817. with self.proc_container.new(_("Exporting DXF")) as proc:
  6818. def job_thread_exc(app_obj):
  6819. ret_dxf_val = make_dxf()
  6820. if ret_dxf_val == 'fail':
  6821. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6822. return
  6823. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6824. else:
  6825. ret = make_dxf()
  6826. if ret == 'fail':
  6827. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6828. return
  6829. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6830. """
  6831. Adds a new Geometry Object to the projects and populates
  6832. it with shapes extracted from the SVG file.
  6833. :param plot: If True then the resulting object will be plotted on canvas
  6834. :param filename: Path to the SVG file.
  6835. :param geo_type: Type of FlatCAM object that will be created from SVG
  6836. :param outname: The name given to the resulting FlatCAM object
  6837. :return:
  6838. """
  6839. self.defaults.report_usage("import_svg()")
  6840. log.debug("App.import_svg()")
  6841. obj_type = ""
  6842. if geo_type is None or geo_type == "geometry":
  6843. obj_type = "geometry"
  6844. elif geo_type == "gerber":
  6845. obj_type = "gerber"
  6846. else:
  6847. self.inform.emit('[ERROR_NOTCL] %s' %
  6848. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6849. return
  6850. units = self.defaults['units'].upper()
  6851. def obj_init(geo_obj, app_obj):
  6852. geo_obj.import_svg(filename, obj_type, units=units)
  6853. geo_obj.multigeo = False
  6854. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6855. with self.proc_container.new(_("Importing SVG")) as proc:
  6856. # Object name
  6857. name = outname or filename.split('/')[-1].split('\\')[-1]
  6858. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6859. if ret == 'fail':
  6860. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6861. return 'fail'
  6862. # Register recent file
  6863. self.file_opened.emit("svg", filename)
  6864. # AppGUI feedback
  6865. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6866. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  6867. """
  6868. Adds a new Geometry Object to the projects and populates
  6869. it with shapes extracted from the DXF file.
  6870. :param filename: Path to the DXF file.
  6871. :param geo_type: Type of FlatCAM object that will be created from DXF
  6872. :param outname: Name for the imported Geometry
  6873. :param plot: If True then the resulting object will be plotted on canvas
  6874. :return:
  6875. """
  6876. self.defaults.report_usage("import_dxf()")
  6877. obj_type = ""
  6878. if geo_type is None or geo_type == "geometry":
  6879. obj_type = "geometry"
  6880. elif geo_type == "gerber":
  6881. obj_type = geo_type
  6882. else:
  6883. self.inform.emit('[ERROR_NOTCL] %s' %
  6884. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6885. return
  6886. units = self.defaults['units'].upper()
  6887. def obj_init(geo_obj, app_obj):
  6888. geo_obj.import_dxf(filename, obj_type, units=units)
  6889. geo_obj.multigeo = False
  6890. with self.proc_container.new(_("Importing DXF")):
  6891. # Object name
  6892. name = outname or filename.split('/')[-1].split('\\')[-1]
  6893. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6894. if ret == 'fail':
  6895. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6896. return 'fail'
  6897. # Register recent file
  6898. self.file_opened.emit("dxf", filename)
  6899. # AppGUI feedback
  6900. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6901. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  6902. """
  6903. Opens a Gerber file, parses it and creates a new object for
  6904. it in the program. Thread-safe.
  6905. :param outname: Name of the resulting object. None causes the
  6906. name to be that of the file. Str.
  6907. :param filename: Gerber file filename
  6908. :type filename: str
  6909. :param plot: boolean, to plot or not the resulting object
  6910. :param from_tcl: True if run from Tcl Shell
  6911. :return: None
  6912. """
  6913. # How the object should be initialized
  6914. def obj_init(gerber_obj, app_obj):
  6915. assert isinstance(gerber_obj, GerberObject), \
  6916. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  6917. # Opening the file happens here
  6918. try:
  6919. gerber_obj.parse_file(filename)
  6920. except IOError:
  6921. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  6922. return "fail"
  6923. except ParseError as err:
  6924. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  6925. app_obj.log.error(str(err))
  6926. return "fail"
  6927. except Exception as e:
  6928. log.debug("App.open_gerber() --> %s" % str(e))
  6929. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  6930. msg += traceback.format_exc()
  6931. app_obj.inform.emit(msg)
  6932. return "fail"
  6933. if gerber_obj.is_empty():
  6934. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  6935. _("Object is not Gerber file or empty. Aborting object creation."))
  6936. return "fail"
  6937. App.log.debug("open_gerber()")
  6938. with self.proc_container.new(_("Opening Gerber")):
  6939. # Object name
  6940. name = outname or filename.split('/')[-1].split('\\')[-1]
  6941. # # ## Object creation # ##
  6942. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6943. if ret_val == 'fail':
  6944. if from_tcl:
  6945. filename = self.defaults['global_tcl_path'] + '/' + name
  6946. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6947. if ret_val == 'fail':
  6948. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  6949. return 'fail'
  6950. # Register recent file
  6951. self.file_opened.emit("gerber", filename)
  6952. # AppGUI feedback
  6953. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6954. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  6955. """
  6956. Opens an Excellon file, parses it and creates a new object for
  6957. it in the program. Thread-safe.
  6958. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6959. :param filename: Excellon file filename
  6960. :type filename: str
  6961. :param plot: boolean, to plot or not the resulting object
  6962. :param from_tcl: True if run from Tcl Shell
  6963. :return: None
  6964. """
  6965. App.log.debug("open_excellon()")
  6966. # How the object should be initialized
  6967. def obj_init(excellon_obj, app_obj):
  6968. try:
  6969. ret = excellon_obj.parse_file(filename=filename)
  6970. if ret == "fail":
  6971. log.debug("Excellon parsing failed.")
  6972. self.inform.emit('[ERROR_NOTCL] %s' %
  6973. _("This is not Excellon file."))
  6974. return "fail"
  6975. except IOError:
  6976. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  6977. (_("Cannot open file"), filename))
  6978. log.debug("Could not open Excellon object.")
  6979. return "fail"
  6980. except Exception:
  6981. msg = '[ERROR_NOTCL] %s' % \
  6982. _("An internal error has occurred. See shell.\n")
  6983. msg += traceback.format_exc()
  6984. app_obj.inform.emit(msg)
  6985. return "fail"
  6986. ret = excellon_obj.create_geometry()
  6987. if ret == 'fail':
  6988. log.debug("Could not create geometry for Excellon object.")
  6989. return "fail"
  6990. for tool in excellon_obj.tools:
  6991. if excellon_obj.tools[tool]['solid_geometry']:
  6992. return
  6993. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  6994. return "fail"
  6995. with self.proc_container.new(_("Opening Excellon.")):
  6996. # Object name
  6997. name = outname or filename.split('/')[-1].split('\\')[-1]
  6998. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  6999. if ret_val == 'fail':
  7000. if from_tcl:
  7001. filename = self.defaults['global_tcl_path'] + '/' + name
  7002. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7003. if ret_val == 'fail':
  7004. self.inform.emit('[ERROR_NOTCL] %s' %
  7005. _('Open Excellon file failed. Probable not an Excellon file.'))
  7006. return
  7007. # Register recent file
  7008. self.file_opened.emit("excellon", filename)
  7009. # AppGUI feedback
  7010. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7011. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7012. """
  7013. Opens a G-gcode file, parses it and creates a new object for
  7014. it in the program. Thread-safe.
  7015. :param filename: G-code file filename
  7016. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7017. :param force_parsing:
  7018. :param plot: If True plot the object on canvas
  7019. :param from_tcl: True if run from Tcl Shell
  7020. :return: None
  7021. """
  7022. App.log.debug("open_gcode()")
  7023. # How the object should be initialized
  7024. def obj_init(job_obj, app_obj_):
  7025. """
  7026. :param job_obj: the resulting object
  7027. :type app_obj_: App
  7028. """
  7029. assert isinstance(app_obj_, App), \
  7030. "Initializer expected App, got %s" % type(app_obj_)
  7031. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7032. try:
  7033. f = open(filename)
  7034. gcode = f.read()
  7035. f.close()
  7036. except IOError:
  7037. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7038. return "fail"
  7039. job_obj.gcode = gcode
  7040. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7041. if gcode_ret == "fail":
  7042. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7043. return "fail"
  7044. job_obj.create_geometry()
  7045. with self.proc_container.new(_("Opening G-Code.")):
  7046. # Object name
  7047. name = outname or filename.split('/')[-1].split('\\')[-1]
  7048. # New object creation and file processing
  7049. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7050. if ret_val == 'fail':
  7051. if from_tcl:
  7052. filename = self.defaults['global_tcl_path'] + '/' + name
  7053. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7054. if ret_val == 'fail':
  7055. self.inform.emit('[ERROR_NOTCL] %s' %
  7056. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7057. "Try to load it from File menu.\n "
  7058. "Attempting to create a FlatCAM CNCJob Object from "
  7059. "G-Code file failed during processing"))
  7060. return "fail"
  7061. # Register recent file
  7062. self.file_opened.emit("cncjob", filename)
  7063. # AppGUI feedback
  7064. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7065. def open_hpgl2(self, filename, outname=None):
  7066. """
  7067. Opens a HPGL2 file, parses it and creates a new object for
  7068. it in the program. Thread-safe.
  7069. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7070. :param filename: HPGL2 file filename
  7071. :return: None
  7072. """
  7073. filename = filename
  7074. # How the object should be initialized
  7075. def obj_init(geo_obj, app_obj):
  7076. assert isinstance(geo_obj, GeometryObject), \
  7077. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7078. # Opening the file happens here
  7079. obj = HPGL2(self)
  7080. try:
  7081. HPGL2.parse_file(obj, filename)
  7082. except IOError:
  7083. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7084. return "fail"
  7085. except ParseError as err:
  7086. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7087. app_obj.log.error(str(err))
  7088. return "fail"
  7089. except Exception as e:
  7090. log.debug("App.open_hpgl2() --> %s" % str(e))
  7091. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7092. msg += traceback.format_exc()
  7093. app_obj.inform.emit(msg)
  7094. return "fail"
  7095. geo_obj.multigeo = True
  7096. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7097. geo_obj.tools = deepcopy(obj.tools)
  7098. geo_obj.source_file = deepcopy(obj.source_file)
  7099. del obj
  7100. if not geo_obj.solid_geometry:
  7101. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7102. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7103. return "fail"
  7104. App.log.debug("open_hpgl2()")
  7105. with self.proc_container.new(_("Opening HPGL2")):
  7106. # Object name
  7107. name = outname or filename.split('/')[-1].split('\\')[-1]
  7108. # # ## Object creation # ##
  7109. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7110. if ret == 'fail':
  7111. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7112. return 'fail'
  7113. # Register recent file
  7114. self.file_opened.emit("geometry", filename)
  7115. # AppGUI feedback
  7116. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7117. def open_script(self, filename, outname=None, silent=False):
  7118. """
  7119. Opens a Script file, parses it and creates a new object for
  7120. it in the program. Thread-safe.
  7121. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7122. :param filename: Script file filename
  7123. :param silent: If True there will be no messages printed to StatusBar
  7124. :return: None
  7125. """
  7126. def obj_init(script_obj, app_obj):
  7127. assert isinstance(script_obj, ScriptObject), \
  7128. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7129. if silent is False:
  7130. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7131. try:
  7132. script_obj.parse_file(filename)
  7133. except IOError:
  7134. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7135. return "fail"
  7136. except ParseError as err:
  7137. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7138. app_obj.log.error(str(err))
  7139. return "fail"
  7140. except Exception as e:
  7141. log.debug("App.open_script() -> %s" % str(e))
  7142. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7143. msg += traceback.format_exc()
  7144. app_obj.inform.emit(msg)
  7145. return "fail"
  7146. App.log.debug("open_script()")
  7147. with self.proc_container.new(_("Opening TCL Script...")):
  7148. # Object name
  7149. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7150. # Object creation
  7151. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7152. if ret_val == 'fail':
  7153. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7154. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7155. if ret_val == 'fail':
  7156. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7157. return 'fail'
  7158. # Register recent file
  7159. self.file_opened.emit("script", filename)
  7160. # AppGUI feedback
  7161. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7162. def open_config_file(self, filename, run_from_arg=None):
  7163. """
  7164. Loads a config file from the specified file.
  7165. :param filename: Name of the file from which to load.
  7166. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7167. :return: None
  7168. """
  7169. App.log.debug("Opening config file: " + filename)
  7170. if run_from_arg:
  7171. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7172. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7173. _("Opening FlatCAM Config file.")),
  7174. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7175. color=QtGui.QColor("gray"))
  7176. # # add the tab if it was closed
  7177. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7178. # # first clear previous text in text editor (if any)
  7179. # self.ui.text_editor_tab.code_editor.clear()
  7180. #
  7181. # # Switch plot_area to CNCJob tab
  7182. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7183. # close the Code editor if already open
  7184. if self.toggle_codeeditor:
  7185. self.on_toggle_code_editor()
  7186. self.on_toggle_code_editor()
  7187. try:
  7188. if filename:
  7189. f = QtCore.QFile(filename)
  7190. if f.open(QtCore.QIODevice.ReadOnly):
  7191. stream = QtCore.QTextStream(f)
  7192. code_edited = stream.readAll()
  7193. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7194. f.close()
  7195. except IOError:
  7196. App.log.error("Failed to open config file: %s" % filename)
  7197. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7198. (_("Failed to open config file"), filename))
  7199. return
  7200. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7201. """
  7202. Loads a project from the specified file.
  7203. 1) Loads and parses file
  7204. 2) Registers the file as recently opened.
  7205. 3) Calls on_file_new()
  7206. 4) Updates options
  7207. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7208. 6) Calls plot_all() if plot=True
  7209. :param filename: Name of the file from which to load.
  7210. :param run_from_arg: True if run for arguments
  7211. :param plot: If True plot all objects in the project
  7212. :param cli: Run from command line
  7213. :param from_tcl: True if run from Tcl Sehll
  7214. :return: None
  7215. """
  7216. App.log.debug("Opening project: " + filename)
  7217. # block autosaving while a project is loaded
  7218. self.block_autosave = True
  7219. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7220. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7221. if cli is None:
  7222. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7223. if run_from_arg:
  7224. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7225. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7226. _("Opening FlatCAM Project file.")),
  7227. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7228. color=QtGui.QColor("gray"))
  7229. # Open and parse an uncompressed Project file
  7230. try:
  7231. f = open(filename, 'r')
  7232. except IOError:
  7233. if from_tcl:
  7234. name = filename.split('/')[-1].split('\\')[-1]
  7235. filename = self.defaults['global_tcl_path'] + '/' + name
  7236. try:
  7237. f = open(filename, 'r')
  7238. except IOError:
  7239. log.error("Failed to open project file: %s" % filename)
  7240. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7241. return
  7242. else:
  7243. log.error("Failed to open project file: %s" % filename)
  7244. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7245. return
  7246. try:
  7247. d = json.load(f, object_hook=dict2obj)
  7248. except Exception as e:
  7249. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7250. (filename, str(e)))
  7251. f.close()
  7252. # Open and parse a compressed Project file
  7253. try:
  7254. with lzma.open(filename) as f:
  7255. file_content = f.read().decode('utf-8')
  7256. d = json.loads(file_content, object_hook=dict2obj)
  7257. except Exception as e:
  7258. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7259. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7260. return
  7261. # Clear the current project
  7262. # # NOT THREAD SAFE # ##
  7263. if run_from_arg is True:
  7264. pass
  7265. elif cli is True:
  7266. self.delete_selection_shape()
  7267. else:
  7268. self.on_file_new()
  7269. # Project options
  7270. self.options.update(d['options'])
  7271. self.project_filename = filename
  7272. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7273. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7274. if cli is None:
  7275. self.set_screen_units(self.options["units"])
  7276. # Re create objects
  7277. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7278. for obj in d['objs']:
  7279. try:
  7280. def obj_init(obj_inst, app_inst):
  7281. obj_inst.from_dict(obj)
  7282. App.log.debug("Recreating from opened project an %s object: %s" %
  7283. (obj['kind'].capitalize(), obj['options']['name']))
  7284. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7285. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7286. if cli is None:
  7287. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7288. obj['kind'].upper(),
  7289. obj['options']['name']
  7290. )
  7291. )
  7292. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7293. except Exception as e:
  7294. print('App.open_project() --> ' + str(e))
  7295. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7296. self.should_we_save = False
  7297. self.file_opened.emit("project", filename)
  7298. # restore autosaving after a project was loaded
  7299. self.block_autosave = False
  7300. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7301. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7302. if cli is None:
  7303. self.set_ui_title(name=self.project_filename)
  7304. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7305. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7306. """
  7307. Re-generates all plots from all objects.
  7308. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7309. :param muted: if True don't print messages
  7310. :param use_thread: if True will use threading for plotting the objects
  7311. :return: None
  7312. """
  7313. self.log.debug("Plot_all()")
  7314. if muted is not True:
  7315. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7316. for plot_obj in self.collection.get_list():
  7317. def worker_task(obj):
  7318. with self.proc_container.new("Plotting"):
  7319. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7320. if fit_view is True:
  7321. self.app_obj.object_plotted.emit(obj)
  7322. if use_thread is True:
  7323. # Send to worker
  7324. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7325. else:
  7326. worker_task(plot_obj)
  7327. def register_folder(self, filename):
  7328. """
  7329. Register the last folder used by the app to open something
  7330. :param filename: the last folder is extracted from the filename
  7331. :return: None
  7332. """
  7333. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7334. def register_save_folder(self, filename):
  7335. """
  7336. Register the last folder used by the app to save something
  7337. :param filename: the last folder is extracted from the filename
  7338. :return: None
  7339. """
  7340. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7341. # def set_progress_bar(self, percentage, text=""):
  7342. # """
  7343. # Set a progress bar to a value (percentage)
  7344. #
  7345. # :param percentage: Value set to the progressbar
  7346. # :param text: Not used
  7347. # :return: None
  7348. # """
  7349. # self.ui.progress_bar.setValue(int(percentage))
  7350. def setup_recent_items(self):
  7351. """
  7352. Setup a dictionary with the recent files accessed, organized by type
  7353. :return:
  7354. """
  7355. icons = {
  7356. "gerber": self.resource_location + "/flatcam_icon16.png",
  7357. "excellon": self.resource_location + "/drill16.png",
  7358. 'geometry': self.resource_location + "/geometry16.png",
  7359. "cncjob": self.resource_location + "/cnc16.png",
  7360. "script": self.resource_location + "/script_new24.png",
  7361. "document": self.resource_location + "/notes16_1.png",
  7362. "project": self.resource_location + "/project16.png",
  7363. "svg": self.resource_location + "/geometry16.png",
  7364. "dxf": self.resource_location + "/dxf16.png",
  7365. "pdf": self.resource_location + "/pdf32.png",
  7366. "image": self.resource_location + "/image16.png"
  7367. }
  7368. try:
  7369. image_opener = self.image_tool.import_image
  7370. except AttributeError:
  7371. image_opener = None
  7372. openers = {
  7373. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7374. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7375. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7376. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7377. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7378. "document": None,
  7379. 'project': self.open_project,
  7380. 'svg': self.import_svg,
  7381. 'dxf': self.import_dxf,
  7382. 'image': image_opener,
  7383. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7384. }
  7385. # Open recent file for files
  7386. try:
  7387. f = open(self.data_path + '/recent.json')
  7388. except IOError:
  7389. App.log.error("Failed to load recent item list.")
  7390. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7391. return
  7392. try:
  7393. self.recent = json.load(f)
  7394. except json.errors.JSONDecodeError:
  7395. App.log.error("Failed to parse recent item list.")
  7396. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7397. f.close()
  7398. return
  7399. f.close()
  7400. # Open recent file for projects
  7401. try:
  7402. fp = open(self.data_path + '/recent_projects.json')
  7403. except IOError:
  7404. App.log.error("Failed to load recent project item list.")
  7405. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7406. return
  7407. try:
  7408. self.recent_projects = json.load(fp)
  7409. except json.errors.JSONDecodeError:
  7410. App.log.error("Failed to parse recent project item list.")
  7411. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7412. fp.close()
  7413. return
  7414. fp.close()
  7415. # Closure needed to create callbacks in a loop.
  7416. # Otherwise late binding occurs.
  7417. def make_callback(func, fname):
  7418. def opener():
  7419. func(fname)
  7420. return opener
  7421. def reset_recent_files():
  7422. # Reset menu
  7423. self.ui.recent.clear()
  7424. self.recent = []
  7425. try:
  7426. ff = open(self.data_path + '/recent.json', 'w')
  7427. except IOError:
  7428. App.log.error("Failed to open recent items file for writing.")
  7429. return
  7430. json.dump(self.recent, ff)
  7431. def reset_recent_projects():
  7432. # Reset menu
  7433. self.ui.recent_projects.clear()
  7434. self.recent_projects = []
  7435. try:
  7436. frp = open(self.data_path + '/recent_projects.json', 'w')
  7437. except IOError:
  7438. App.log.error("Failed to open recent projects items file for writing.")
  7439. return
  7440. json.dump(self.recent, frp)
  7441. # Reset menu
  7442. self.ui.recent.clear()
  7443. self.ui.recent_projects.clear()
  7444. # Create menu items for projects
  7445. for recent in self.recent_projects:
  7446. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7447. if recent['kind'] == 'project':
  7448. try:
  7449. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7450. # Attach callback
  7451. o = make_callback(openers[recent["kind"]], recent['filename'])
  7452. action.triggered.connect(o)
  7453. self.ui.recent_projects.addAction(action)
  7454. except KeyError:
  7455. App.log.error("Unsupported file type: %s" % recent["kind"])
  7456. # Last action in Recent Files menu is one that Clear the content
  7457. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7458. (_("Clear Recent projects")), self)
  7459. clear_action_proj.triggered.connect(reset_recent_projects)
  7460. self.ui.recent_projects.addSeparator()
  7461. self.ui.recent_projects.addAction(clear_action_proj)
  7462. # Create menu items for files
  7463. for recent in self.recent:
  7464. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7465. if recent['kind'] != 'project':
  7466. try:
  7467. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7468. # Attach callback
  7469. o = make_callback(openers[recent["kind"]], recent['filename'])
  7470. action.triggered.connect(o)
  7471. self.ui.recent.addAction(action)
  7472. except KeyError:
  7473. App.log.error("Unsupported file type: %s" % recent["kind"])
  7474. # Last action in Recent Files menu is one that Clear the content
  7475. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7476. (_("Clear Recent files")), self)
  7477. clear_action.triggered.connect(reset_recent_files)
  7478. self.ui.recent.addSeparator()
  7479. self.ui.recent.addAction(clear_action)
  7480. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7481. # self.ui.menufilerecent.set_submenu(recent_menu)
  7482. # recent_menu.show_all()
  7483. # self.ui.recent.show()
  7484. self.log.debug("Recent items list has been populated.")
  7485. def setup_component_editor(self):
  7486. """
  7487. Default text for the Selected tab when is not taken by the Object UI.
  7488. :return:
  7489. """
  7490. # label = QtWidgets.QLabel("Choose an item from Project")
  7491. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7492. sel_title = QtWidgets.QTextEdit(
  7493. _('<b>Shortcut Key List</b>'))
  7494. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7495. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7496. f_settings = QSettings("Open Source", "FlatCAM")
  7497. if f_settings.contains("notebook_font_size"):
  7498. fsize = f_settings.value('notebook_font_size', type=int)
  7499. else:
  7500. fsize = 12
  7501. tsize = fsize + int(fsize / 2)
  7502. # selected_text = (_('''
  7503. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7504. # </p>
  7505. #
  7506. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7507. # The normal flow when working in FlatCAM is the following:</span></p>
  7508. #
  7509. # <ol>
  7510. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7511. # file into
  7512. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7513. # even dragging and dropping the files on the AppGUI.<br />
  7514. # <br />
  7515. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7516. # drop of the
  7517. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7518. # &nbsp;</li>
  7519. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7520. # and then
  7521. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7522. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7523. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7524. # <br />
  7525. # If the selection of the object is done on the canvas by single click instead, and the
  7526. # <strong>SELECTED TAB</strong>
  7527. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7528. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7529. # it even if it was out of focus.<br />
  7530. # <br />
  7531. # You can change the parameters in this screen and the flow direction is like this:<br />
  7532. # <br />
  7533. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7534. # <strong> Geometry Object
  7535. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7536. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7537. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7538. # </ol>
  7539. #
  7540. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7541. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7542. # <strong>F3</strong>.</span></p>
  7543. #
  7544. # ''').format(fsize=fsize, tsize=tsize))
  7545. selected_text = '''
  7546. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7547. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7548. {s1}</span></p>
  7549. <ol>
  7550. <li><span style="font-size:{fsize}px">{s2}<br />
  7551. <br />
  7552. {s3}</span><br />
  7553. &nbsp;</li>
  7554. <li><span style="font-size:{fsize}px">{s4}<br />
  7555. &nbsp;</li>
  7556. <br />
  7557. <li><span style="font-size:{fsize}px">{s5}<br />
  7558. &nbsp;</li>
  7559. <br />
  7560. <li><span style="font-size:{fsize}px">{s6}<br />
  7561. <br />
  7562. {s7}</span></li>
  7563. </ol>
  7564. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7565. '''.format(
  7566. title=_("Selected Tab - Choose an Item from Project Tab"),
  7567. subtitle=_("Details"),
  7568. s1=_("The normal flow when working in FlatCAM is the following:"),
  7569. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  7570. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7571. "files on the AppGUI."),
  7572. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  7573. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  7574. "actions offered within the app."),
  7575. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7576. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7577. "SELECTED TAB will be updated with the object properties according to its kind: "
  7578. "Gerber, Excellon, Geometry or CNCJob object."),
  7579. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7580. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7581. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7582. "the SELECTED TAB and populate it even if it was out of focus."),
  7583. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7584. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7585. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7586. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7587. "(again, done in SELECTED TAB) --> Save GCode."),
  7588. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7589. "or through its own key shortcut: <b>F3</b>."),
  7590. tsize=tsize,
  7591. fsize=fsize
  7592. )
  7593. sel_title.setText(selected_text)
  7594. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7595. self.ui.selected_scroll_area.setWidget(sel_title)
  7596. def setup_obj_classes(self):
  7597. """
  7598. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7599. class.
  7600. :return: None
  7601. """
  7602. FlatCAMObj.app = self
  7603. ObjectCollection.app = self
  7604. Gerber.app = self
  7605. Excellon.app = self
  7606. Geometry.app = self
  7607. CNCjob.app = self
  7608. FCProcess.app = self
  7609. FCProcessContainer.app = self
  7610. OptionsGroupUI.app = self
  7611. def version_check(self):
  7612. """
  7613. Checks for the latest version of the program. Alerts the
  7614. user if theirs is outdated. This method is meant to be run
  7615. in a separate thread.
  7616. :return: None
  7617. """
  7618. self.log.debug("version_check()")
  7619. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7620. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7621. App.version_url,
  7622. str(self.defaults['global_serial']),
  7623. str(self.version),
  7624. str(self.os),
  7625. urllib.parse.urlencode(self.defaults["global_stats"])
  7626. )
  7627. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7628. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7629. # urllib.parse.urlencode(self.defaults["global_stats"])
  7630. else:
  7631. # no_stats dict; just so it won't break things on website
  7632. no_ststs_dict = {}
  7633. no_ststs_dict["global_ststs"] = {}
  7634. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7635. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7636. App.log.debug("Checking for updates @ %s" % full_url)
  7637. # ## Get the data
  7638. try:
  7639. f = urllib.request.urlopen(full_url)
  7640. except Exception:
  7641. # App.log.warning("Failed checking for latest version. Could not connect.")
  7642. self.log.warning("Failed checking for latest version. Could not connect.")
  7643. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7644. return
  7645. try:
  7646. data = json.load(f)
  7647. except Exception as e:
  7648. App.log.error("Could not parse information about latest version.")
  7649. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7650. App.log.debug("json.load(): %s" % str(e))
  7651. f.close()
  7652. return
  7653. f.close()
  7654. # ## Latest version?
  7655. if self.version >= data["version"]:
  7656. App.log.debug("FlatCAM is up to date!")
  7657. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7658. return
  7659. App.log.debug("Newer version available.")
  7660. self.message.emit(
  7661. _("Newer Version Available"),
  7662. '%s<br><br>><b>%s</b><br>%s' % (
  7663. _("There is a newer version of FlatCAM available for download:"),
  7664. str(data["name"]),
  7665. str(data["message"])
  7666. ),
  7667. _("info")
  7668. )
  7669. def on_plotcanvas_setup(self, container=None):
  7670. """
  7671. This is doing the setup for the plot area (canvas).
  7672. :param container: QT Widget where to install the canvas
  7673. :return: None
  7674. """
  7675. if container:
  7676. plot_container = container
  7677. else:
  7678. plot_container = self.ui.right_layout
  7679. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7680. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7681. self.is_legacy = True
  7682. self.defaults["global_graphic_engine"] = "2D"
  7683. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7684. else:
  7685. try:
  7686. self.plotcanvas = PlotCanvas(plot_container, self)
  7687. except Exception as er:
  7688. msg_txt = traceback.format_exc()
  7689. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7690. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7691. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7692. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7693. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7694. msg += msg_txt
  7695. self.inform.emit(msg)
  7696. return 'fail'
  7697. # So it can receive key presses
  7698. self.plotcanvas.native.setFocus()
  7699. if self.is_legacy is False:
  7700. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7701. # Set the mouse button for panning
  7702. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7703. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7704. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7705. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7706. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7707. # Keys over plot enabled
  7708. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7709. if self.defaults['global_cursor_type'] == 'small':
  7710. self.app_cursor = self.plotcanvas.new_cursor()
  7711. else:
  7712. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7713. if self.ui.grid_snap_btn.isChecked():
  7714. self.app_cursor.enabled = True
  7715. else:
  7716. self.app_cursor.enabled = False
  7717. if self.is_legacy is False:
  7718. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7719. else:
  7720. # will use the default Matplotlib axes
  7721. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7722. def on_zoom_fit(self):
  7723. """
  7724. Callback for zoom-fit request. This can be either from the corresponding
  7725. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7726. with axes limits from the geometry bounds of all objects.
  7727. :return: None
  7728. """
  7729. if self.is_legacy is False:
  7730. self.plotcanvas.fit_view()
  7731. else:
  7732. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7733. width = xmax - xmin
  7734. height = ymax - ymin
  7735. xmin -= 0.05 * width
  7736. xmax += 0.05 * width
  7737. ymin -= 0.05 * height
  7738. ymax += 0.05 * height
  7739. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7740. def on_zoom_in(self):
  7741. """
  7742. Callback for zoom-in request.
  7743. :return:
  7744. """
  7745. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7746. def on_zoom_out(self):
  7747. """
  7748. Callback for zoom-out request.
  7749. :return:
  7750. """
  7751. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7752. def disable_all_plots(self):
  7753. self.defaults.report_usage("disable_all_plots()")
  7754. self.disable_plots(self.collection.get_list())
  7755. self.inform.emit('[success] %s' %
  7756. _("All plots disabled."))
  7757. def disable_other_plots(self):
  7758. self.defaults.report_usage("disable_other_plots()")
  7759. self.disable_plots(self.collection.get_non_selected())
  7760. self.inform.emit('[success] %s' %
  7761. _("All non selected plots disabled."))
  7762. def enable_all_plots(self):
  7763. self.defaults.report_usage("enable_all_plots()")
  7764. self.enable_plots(self.collection.get_list())
  7765. self.inform.emit('[success] %s' %
  7766. _("All plots enabled."))
  7767. def on_enable_sel_plots(self):
  7768. log.debug("App.on_enable_sel_plot()")
  7769. object_list = self.collection.get_selected()
  7770. self.enable_plots(objects=object_list)
  7771. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7772. def on_disable_sel_plots(self):
  7773. log.debug("App.on_disable_sel_plot()")
  7774. # self.inform.emit(_("Disabling plots ..."))
  7775. object_list = self.collection.get_selected()
  7776. self.disable_plots(objects=object_list)
  7777. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7778. def enable_plots(self, objects):
  7779. """
  7780. Enable plots
  7781. :param objects: list of Objects to be enabled
  7782. :return:
  7783. """
  7784. log.debug("Enabling plots ...")
  7785. # self.inform.emit(_("Working ..."))
  7786. for obj in objects:
  7787. if obj.options['plot'] is False:
  7788. obj.options.set_change_callback(lambda x: None)
  7789. obj.options['plot'] = True
  7790. try:
  7791. # only the Gerber obj has on_plot_cb_click() method
  7792. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7793. # disable this cb while disconnected,
  7794. # in case the operation takes time the user is not allowed to change it
  7795. obj.ui.plot_cb.setDisabled(True)
  7796. except AttributeError:
  7797. pass
  7798. obj.set_form_item("plot")
  7799. try:
  7800. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7801. obj.ui.plot_cb.setDisabled(False)
  7802. except AttributeError:
  7803. pass
  7804. obj.options.set_change_callback(obj.on_options_change)
  7805. def worker_task(objs):
  7806. with self.proc_container.new(_("Enabling plots ...")):
  7807. for plot_obj in objs:
  7808. # obj.options['plot'] = True
  7809. if isinstance(plot_obj, CNCJobObject):
  7810. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7811. else:
  7812. plot_obj.plot(visible=True)
  7813. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7814. def disable_plots(self, objects):
  7815. """
  7816. Disables plots
  7817. :param objects: list of Objects to be disabled
  7818. :return:
  7819. """
  7820. # if no objects selected then do nothing
  7821. if not self.collection.get_selected():
  7822. return
  7823. log.debug("Disabling plots ...")
  7824. # self.inform.emit(_("Working ..."))
  7825. for obj in objects:
  7826. if obj.options['plot'] is True:
  7827. obj.options.set_change_callback(lambda x: None)
  7828. obj.options['plot'] = False
  7829. try:
  7830. # only the Gerber obj has on_plot_cb_click() method
  7831. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7832. obj.ui.plot_cb.setDisabled(True)
  7833. except AttributeError:
  7834. pass
  7835. obj.set_form_item("plot")
  7836. try:
  7837. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7838. obj.ui.plot_cb.setDisabled(False)
  7839. except AttributeError:
  7840. pass
  7841. obj.options.set_change_callback(obj.on_options_change)
  7842. try:
  7843. self.delete_selection_shape()
  7844. except Exception as e:
  7845. log.debug("App.disable_plots() --> %s" % str(e))
  7846. def worker_task(objs):
  7847. with self.proc_container.new(_("Disabling plots ...")):
  7848. for plot_obj in objs:
  7849. # obj.options['plot'] = True
  7850. if isinstance(plot_obj, CNCJobObject):
  7851. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7852. else:
  7853. plot_obj.plot(visible=False)
  7854. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7855. def toggle_plots(self, objects):
  7856. """
  7857. Toggle plots visibility
  7858. :param objects: list of Objects for which to be toggled the visibility
  7859. :return: None
  7860. """
  7861. # if no objects selected then do nothing
  7862. if not self.collection.get_selected():
  7863. return
  7864. log.debug("Toggling plots ...")
  7865. self.inform.emit(_("Working ..."))
  7866. for obj in objects:
  7867. if obj.options['plot'] is False:
  7868. obj.options['plot'] = True
  7869. else:
  7870. obj.options['plot'] = False
  7871. self.app_obj.plots_updated.emit()
  7872. def clear_plots(self):
  7873. """
  7874. Clear the plots
  7875. :return: None
  7876. """
  7877. objects = self.collection.get_list()
  7878. for obj in objects:
  7879. obj.clear(obj == objects[-1])
  7880. # Clear pool to free memory
  7881. self.clear_pool()
  7882. def on_set_color_action_triggered(self):
  7883. """
  7884. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  7885. :return:
  7886. """
  7887. new_color = self.defaults['gerber_plot_fill']
  7888. clicked_action = self.sender()
  7889. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  7890. act_name = clicked_action.text()
  7891. sel_obj_list = self.collection.get_selected()
  7892. if not sel_obj_list:
  7893. return
  7894. # a default value, I just chose this one
  7895. alpha_level = 'BF'
  7896. for sel_obj in sel_obj_list:
  7897. if sel_obj.kind == 'excellon':
  7898. alpha_level = str(hex(
  7899. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  7900. elif sel_obj.kind == 'gerber':
  7901. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  7902. elif sel_obj.kind == 'geometry':
  7903. alpha_level = 'FF'
  7904. else:
  7905. log.debug(
  7906. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  7907. continue
  7908. sel_obj.alpha_level = alpha_level
  7909. if act_name == _('Red'):
  7910. new_color = '#FF0000' + alpha_level
  7911. if act_name == _('Blue'):
  7912. new_color = '#0000FF' + alpha_level
  7913. if act_name == _('Yellow'):
  7914. new_color = '#FFDF00' + alpha_level
  7915. if act_name == _('Green'):
  7916. new_color = '#00FF00' + alpha_level
  7917. if act_name == _('Purple'):
  7918. new_color = '#FF00FF' + alpha_level
  7919. if act_name == _('Brown'):
  7920. new_color = '#A52A2A' + alpha_level
  7921. if act_name == _('White'):
  7922. new_color = '#FFFFFF' + alpha_level
  7923. if act_name == _('Black'):
  7924. new_color = '#000000' + alpha_level
  7925. if act_name == _('Custom'):
  7926. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  7927. c_dialog = QtWidgets.QColorDialog()
  7928. plot_fill_color = c_dialog.getColor(initial=new_color)
  7929. if plot_fill_color.isValid() is False:
  7930. return
  7931. new_color = str(plot_fill_color.name()) + alpha_level
  7932. if act_name == _("Default"):
  7933. for sel_obj in sel_obj_list:
  7934. if sel_obj.kind == 'excellon':
  7935. new_color = self.defaults['excellon_plot_fill']
  7936. new_line_color = self.defaults['excellon_plot_line']
  7937. elif sel_obj.kind == 'gerber':
  7938. new_color = self.defaults['gerber_plot_fill']
  7939. new_line_color = self.defaults['gerber_plot_line']
  7940. elif sel_obj.kind == 'geometry':
  7941. new_color = self.defaults['geometry_plot_line']
  7942. new_line_color = self.defaults['geometry_plot_line']
  7943. else:
  7944. log.debug(
  7945. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  7946. continue
  7947. sel_obj.fill_color = new_color
  7948. sel_obj.outline_color = new_line_color
  7949. sel_obj.shapes.redraw(
  7950. update_colors=(new_color, new_line_color)
  7951. )
  7952. return
  7953. if act_name == _("Opacity"):
  7954. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  7955. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  7956. if ok_button:
  7957. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  7958. for sel_obj in sel_obj_list:
  7959. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  7960. sel_obj.shapes.redraw(
  7961. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  7962. )
  7963. return
  7964. new_line_color = color_variant(new_color[:7], 0.7)
  7965. if act_name == _("White"):
  7966. new_line_color = color_variant("#dedede", 0.7)
  7967. for sel_obj in sel_obj_list:
  7968. sel_obj.fill_color = new_color
  7969. sel_obj.outline_color = new_line_color
  7970. sel_obj.shapes.redraw(
  7971. update_colors=(new_color, new_line_color)
  7972. )
  7973. def generate_cnc_job(self, objects):
  7974. """
  7975. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  7976. :param objects: Selected objects in the Project Tab
  7977. :return:
  7978. """
  7979. self.defaults.report_usage("generate_cnc_job()")
  7980. # for obj in objects:
  7981. # obj.generatecncjob()
  7982. for obj in objects:
  7983. obj.on_generatecnc_button_click()
  7984. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  7985. """
  7986. Saves the current project to the specified file.
  7987. :param filename: Name of the file in which to save.
  7988. :type filename: str
  7989. :param quit_action: if the project saving will be followed by an app quit; boolean
  7990. :param silent: if True will not display status messages
  7991. :param from_tcl True is run from Tcl Shell
  7992. :return: None
  7993. """
  7994. self.log.debug("save_project()")
  7995. self.save_in_progress = True
  7996. with self.proc_container.new(_("Saving FlatCAM Project")):
  7997. # Capture the latest changes
  7998. # Current object
  7999. try:
  8000. current_object = self.collection.get_active()
  8001. if current_object:
  8002. current_object.read_form()
  8003. except Exception as e:
  8004. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8005. pass
  8006. # Serialize the whole project
  8007. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8008. "options": self.options,
  8009. "version": self.version}
  8010. if self.defaults["global_save_compressed"] is True:
  8011. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8012. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8013. # # Write
  8014. f.write(g)
  8015. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8016. else:
  8017. # Open file
  8018. try:
  8019. f = open(filename, 'w')
  8020. except IOError:
  8021. App.log.error("Failed to open file for saving: %s", filename)
  8022. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8023. return
  8024. # Write
  8025. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8026. f.close()
  8027. # verification of the saved project
  8028. # Open and parse
  8029. try:
  8030. saved_f = open(filename, 'r')
  8031. except IOError:
  8032. if silent is False:
  8033. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8034. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8035. return
  8036. try:
  8037. saved_d = json.load(saved_f, object_hook=dict2obj)
  8038. except Exception:
  8039. if silent is False:
  8040. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8041. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8042. f.close()
  8043. return
  8044. saved_f.close()
  8045. if silent is False:
  8046. if 'version' in saved_d:
  8047. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8048. else:
  8049. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8050. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8051. tb_settings = QSettings("Open Source", "FlatCAM")
  8052. lock_state = self.ui.lock_action.isChecked()
  8053. tb_settings.setValue('toolbar_lock', lock_state)
  8054. # This will write the setting to the platform specific storage.
  8055. del tb_settings
  8056. # if quit:
  8057. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8058. # t.start()
  8059. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8060. def start_delayed_quit(self, delay, filename, should_quit=None):
  8061. """
  8062. :param delay: period of checking if project file size is more than zero; in seconds
  8063. :param filename: the name of the project file to be checked periodically for size more than zero
  8064. :param should_quit: if the task finished will be followed by an app quit; boolean
  8065. :return:
  8066. """
  8067. to_quit = should_quit
  8068. self.save_timer = QtCore.QTimer()
  8069. self.save_timer.setInterval(delay)
  8070. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8071. self.save_timer.start()
  8072. def check_project_file_size(self, filename, should_quit=None):
  8073. """
  8074. :param filename: the name of the project file to be checked periodically for size more than zero
  8075. :param should_quit: will quit the app if True; boolean
  8076. :return:
  8077. """
  8078. try:
  8079. if os.stat(filename).st_size > 0:
  8080. self.save_in_progress = False
  8081. self.save_timer.stop()
  8082. if should_quit:
  8083. self.app_quit.emit()
  8084. except Exception:
  8085. traceback.print_exc()
  8086. def save_project_auto(self):
  8087. """
  8088. Called periodically to save the project.
  8089. 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
  8090. # progress.
  8091. :return:
  8092. """
  8093. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8094. self.on_file_saveproject()
  8095. def save_project_auto_update(self):
  8096. """
  8097. Update the auto save time interval value.
  8098. :return:
  8099. """
  8100. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8101. try:
  8102. if self.autosave_timer.isActive():
  8103. self.autosave_timer.stop()
  8104. except Exception:
  8105. pass
  8106. if self.defaults['global_autosave'] is True:
  8107. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8108. self.autosave_timer.start()
  8109. def on_options_app2project(self):
  8110. """
  8111. Callback for Options->Transfer Options->App=>Project. Copies options
  8112. from application defaults to project defaults.
  8113. :return: None
  8114. """
  8115. self.defaults.report_usage("on_options_app2project")
  8116. self.preferencesUiManager.defaults_read_form()
  8117. self.options.update(self.defaults)
  8118. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8119. """
  8120. Shows a message on the FlatCAM Shell
  8121. :param msg: Message to display.
  8122. :param show: Opens the shell.
  8123. :param error: Shows the message as an error.
  8124. :param warning: Shows the message as an warning.
  8125. :param success: Shows the message as an success.
  8126. :param selected: Indicate that something was selected on canvas
  8127. :return: None
  8128. """
  8129. if show:
  8130. self.ui.shell_dock.show()
  8131. try:
  8132. if error:
  8133. self.shell.append_error(msg + "\n")
  8134. elif warning:
  8135. self.shell.append_warning(msg + "\n")
  8136. elif success:
  8137. self.shell.append_success(msg + "\n")
  8138. elif selected:
  8139. self.shell.append_selected(msg + "\n")
  8140. else:
  8141. self.shell.append_output(msg + "\n")
  8142. except AttributeError:
  8143. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8144. class ArgsThread(QtCore.QObject):
  8145. open_signal = pyqtSignal(list)
  8146. start = pyqtSignal()
  8147. stop = pyqtSignal()
  8148. if sys.platform == 'win32':
  8149. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8150. else:
  8151. address = ('/tmp/testipc', 'AF_UNIX')
  8152. def __init__(self):
  8153. super(ArgsThread, self).__init__()
  8154. self.listener = None
  8155. self.thread_exit = False
  8156. self.start.connect(self.run)
  8157. self.stop.connect(self.close_listener)
  8158. def my_loop(self, address):
  8159. try:
  8160. self.listener = Listener(*address)
  8161. while self.thread_exit is False:
  8162. conn = self.listener.accept()
  8163. self.serve(conn)
  8164. except socket.error:
  8165. try:
  8166. conn = Client(*address)
  8167. conn.send(sys.argv)
  8168. conn.send('close')
  8169. # close the current instance only if there are args
  8170. if len(sys.argv) > 1:
  8171. try:
  8172. self.listener.close()
  8173. except Exception:
  8174. pass
  8175. sys.exit()
  8176. except ConnectionRefusedError:
  8177. if sys.platform == 'win32':
  8178. pass
  8179. else:
  8180. os.system('rm /tmp/testipc')
  8181. self.listener = Listener(*address)
  8182. while True:
  8183. conn = self.listener.accept()
  8184. self.serve(conn)
  8185. def serve(self, conn):
  8186. while self.thread_exit is False:
  8187. msg = conn.recv()
  8188. if msg == 'close':
  8189. break
  8190. self.open_signal.emit(msg)
  8191. conn.close()
  8192. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8193. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8194. @pyqtSlot()
  8195. def run(self):
  8196. self.my_loop(self.address)
  8197. @pyqtSlot()
  8198. def close_listener(self):
  8199. self.thread_exit = True
  8200. self.listener.close()
  8201. # end of file