App_Main.py 448 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015
  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"))
  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_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  694. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  695. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  696. self.ui.menuview_toggle_hud.triggered.connect(self.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. # connect the abort_all_tasks related slots to the related signals
  812. self.proc_container.idle_flag.connect(self.app_is_idle)
  813. # signal emitted when a tab is closed in the Plot Area
  814. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  815. # signal to close the application
  816. self.close_app_signal.connect(self.kill_app)
  817. # ################################# FINISHED CONNECTING SIGNALS #############################################
  818. # ###########################################################################################################
  819. # ###########################################################################################################
  820. # ###########################################################################################################
  821. self.log.debug("Finished connecting Signals.")
  822. # ###########################################################################################################
  823. # ########################################## Other setups ###################################################
  824. # ###########################################################################################################
  825. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  826. # depending on from where those tools are called different actions can be done
  827. self.call_source = 'app'
  828. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  829. self.tool_tab_locked = False
  830. # decide if to show or hide the Notebook side of the screen at startup
  831. if self.defaults["global_project_at_startup"] is True:
  832. self.ui.splitter.setSizes([1, 1])
  833. else:
  834. self.ui.splitter.setSizes([0, 1])
  835. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  836. self.setup_component_editor()
  837. # ###########################################################################################################
  838. # ####################################### Auto-complete KEYWORDS ############################################
  839. # ###########################################################################################################
  840. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  841. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  842. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  843. 'export_exc',
  844. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  845. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  846. 'interiors', 'isolate', 'join_excellon',
  847. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  848. 'mirror', 'ncc',
  849. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  850. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  851. 'options', 'origin',
  852. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  853. 'save', 'save_project',
  854. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  855. 'skew', 'subtract_poly', 'subtract_rectangle',
  856. 'version', 'write_gcode'
  857. ]
  858. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  859. 'Paste_1',
  860. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  861. 'Toolchange_manual', 'True', 'Users',
  862. 'all', 'auto', 'axis',
  863. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  864. 'contour', 'default',
  865. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  866. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  867. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  868. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  869. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  870. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  871. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  872. 'spacing_columns',
  873. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  874. 'toolchange_xy', 'toolchangez', 'travelz',
  875. 'tooldia', 'use_threads', 'value',
  876. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  877. ]
  878. self.tcl_keywords = [
  879. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  880. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  881. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  882. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  883. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  884. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  885. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  886. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  887. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  888. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  889. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  890. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  891. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  892. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  893. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  894. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  895. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  896. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  897. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  898. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  899. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  900. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  901. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  902. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  903. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  904. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  905. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  906. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  907. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  908. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  909. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  910. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  911. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  912. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  913. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  914. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  915. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  916. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  917. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  918. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  919. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  920. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  921. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  922. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  923. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  924. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  925. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  926. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  927. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  928. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  929. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  930. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  931. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  932. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  933. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  934. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  935. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  936. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  937. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  938. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  939. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  940. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  941. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  942. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  943. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  944. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  945. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  946. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  947. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  948. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  949. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  950. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  951. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  952. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  953. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  954. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  955. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  956. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  957. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  958. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  959. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  960. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  961. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  962. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  963. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  964. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  965. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  966. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  967. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  968. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  969. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  970. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  971. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  972. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  973. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  974. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  975. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  976. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  977. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  978. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  979. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  980. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  981. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  982. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  983. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  984. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  985. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  986. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  987. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  988. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  989. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  990. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  991. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  992. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  993. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  994. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  995. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  996. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  997. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  998. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  999. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1000. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1001. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1002. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1003. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1004. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1005. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1006. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1007. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1008. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1009. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1010. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1011. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1012. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1013. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1014. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1015. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1016. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1017. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1018. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1019. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1020. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1021. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1022. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1023. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1024. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1025. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1026. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1027. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1028. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1029. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1030. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1031. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1032. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1033. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1034. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1035. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1036. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1037. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1038. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1039. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1040. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1041. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1042. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1043. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1044. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1045. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1046. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1047. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1048. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1049. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1050. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1051. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1052. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1053. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1054. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1055. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1056. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1057. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1058. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1059. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1060. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1061. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1062. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1063. ]
  1064. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1065. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1066. # ###########################################################################################################
  1067. # ############################################## Shell SETUP ################################################
  1068. # ###########################################################################################################
  1069. self.shell = FCShell(app=self, version=self.version)
  1070. self.ui.shell_dock.setWidget(self.shell)
  1071. self.log.debug("TCL Shell has been initialized.")
  1072. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1073. if self.defaults["global_shell_at_startup"]:
  1074. self.ui.shell_dock.show()
  1075. else:
  1076. self.ui.shell_dock.hide()
  1077. # ###########################################################################################################
  1078. # ########################################## Tools and Plugins ##############################################
  1079. # ###########################################################################################################
  1080. self.dblsidedtool = None
  1081. self.distance_tool = None
  1082. self.distance_min_tool = None
  1083. self.panelize_tool = None
  1084. self.film_tool = None
  1085. self.paste_tool = None
  1086. self.calculator_tool = None
  1087. self.rules_tool = None
  1088. self.sub_tool = None
  1089. self.move_tool = None
  1090. self.cutout_tool = None
  1091. self.ncclear_tool = None
  1092. self.paint_tool = None
  1093. self.isolation_tool = None
  1094. self.optimal_tool = None
  1095. self.transform_tool = None
  1096. self.properties_tool = None
  1097. self.pdf_tool = None
  1098. self.image_tool = None
  1099. self.pcb_wizard_tool = None
  1100. self.cal_exc_tool = None
  1101. self.qrcode_tool = None
  1102. self.copper_thieving_tool = None
  1103. self.fiducial_tool = None
  1104. self.edrills_tool = None
  1105. self.align_objects_tool = None
  1106. self.punch_tool = None
  1107. self.invert_tool = None
  1108. self.corners_tool = None
  1109. self.etch_tool = None
  1110. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1111. try:
  1112. self.install_tools()
  1113. except AttributeError as e:
  1114. log.debug("App.__init__() install tools() --> %s" % str(e))
  1115. # ###########################################################################################################
  1116. # ############################################ SETUP RECENT ITEMS ###########################################
  1117. # ###########################################################################################################
  1118. self.setup_recent_items()
  1119. # ###########################################################################################################
  1120. # ######################################### BookMarks Manager ###############################################
  1121. # ###########################################################################################################
  1122. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1123. self.install_bookmarks()
  1124. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1125. # ###########################################################################################################
  1126. # ########################################### Tools Database ################################################
  1127. # ###########################################################################################################
  1128. self.tools_db_tab = None
  1129. # ### System Font Parsing ###
  1130. # self.f_parse = ParseFont(self)
  1131. # self.parse_system_fonts()
  1132. # ###########################################################################################################
  1133. # ######################################### Check for updates ###############################################
  1134. # ###########################################################################################################
  1135. # Separate thread (Not worker)
  1136. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1137. if (self.beta is False or self.beta is None) and \
  1138. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1139. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1140. # self.thr2 = QtCore.QThread()
  1141. self.worker_task.emit({'fcn': self.version_check,
  1142. 'params': []})
  1143. # self.thr2.start(QtCore.QThread.LowPriority)
  1144. # ###########################################################################################################
  1145. # ##################################### Register files with FlatCAM; #######################################
  1146. # ################################### It works only for Windows for now ####################################
  1147. # ###########################################################################################################
  1148. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1149. self.on_register_files()
  1150. # ###########################################################################################################
  1151. # ######################################## Variables for global usage #######################################
  1152. # ###########################################################################################################
  1153. # hold the App units
  1154. self.units = 'MM'
  1155. # coordinates for relative position display
  1156. self.rel_point1 = (0, 0)
  1157. self.rel_point2 = (0, 0)
  1158. # variable to store coordinates
  1159. self.pos = (0, 0)
  1160. self.pos_canvas = (0, 0)
  1161. self.pos_jump = (0, 0)
  1162. # variable to store mouse coordinates
  1163. self.mouse = [0, 0]
  1164. # variable to store the delta positions on cavnas
  1165. self.dx = 0
  1166. self.dy = 0
  1167. # decide if we have a double click or single click
  1168. self.doubleclick = False
  1169. # store here the is_dragging value
  1170. self.event_is_dragging = False
  1171. # variable to store if a command is active (then the var is not None) and which one it is
  1172. self.command_active = None
  1173. # variable to store the status of moving selection action
  1174. # None value means that it's not an selection action
  1175. # True value = a selection from left to right
  1176. # False value = a selection from right to left
  1177. self.selection_type = None
  1178. # List to store the objects that are currently loaded in FlatCAM
  1179. # This list is updated on each object creation or object delete
  1180. self.all_objects_list = []
  1181. self.objects_under_the_click_list = []
  1182. # List to store the objects that are selected
  1183. self.sel_objects_list = []
  1184. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1185. self.key_modifiers = None
  1186. # Variable to hold the status of the axis
  1187. self.toggle_axis = True
  1188. # Variable to hold the status of the grid lines
  1189. self.toggle_grid_lines = True
  1190. # Variable to store the status of the code editor
  1191. self.toggle_codeeditor = False
  1192. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1193. self.click_noproject = False
  1194. self.cursor = None
  1195. # Variable to store the GCODE that was edited
  1196. self.gcode_edited = ""
  1197. self.text_editor_tab = None
  1198. # reference for the self.ui.code_editor
  1199. self.reference_code_editor = None
  1200. self.script_code = ''
  1201. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1202. self.tools_db_changed_flag = False
  1203. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1204. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1205. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1206. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1207. 'tsm']
  1208. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1209. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1210. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1211. 'sbp', 'tap', 'xpi']
  1212. self.svg_list = ['svg']
  1213. self.dxf_list = ['dxf']
  1214. self.pdf_list = ['pdf']
  1215. self.prj_list = ['flatprj']
  1216. self.conf_list = ['flatconfig']
  1217. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1218. # flag for polygons not cleared
  1219. self.poly_not_cleared = False
  1220. # VisPy visuals
  1221. self.isHovering = False
  1222. self.notHovering = True
  1223. # Window geometry
  1224. self.x_pos = None
  1225. self.y_pos = None
  1226. self.width = None
  1227. self.height = None
  1228. # when True, the app has to return from any thread
  1229. self.abort_flag = False
  1230. # set the value used in the Windows Title
  1231. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1232. # this holds a widget that is installed in the Plot Area when View Source option is used
  1233. self.source_editor_tab = None
  1234. self.pagesize = {}
  1235. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1236. # VisPy visuals
  1237. if self.is_legacy is False:
  1238. try:
  1239. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1240. except AttributeError:
  1241. self.tool_shapes = None
  1242. else:
  1243. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1244. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1245. # used in the delayed shutdown self.start_delayed_quit() method
  1246. self.save_timer = None
  1247. # ###########################################################################################################
  1248. # ################################## ADDING FlatCAM EDITORS section #########################################
  1249. # ###########################################################################################################
  1250. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1251. # at the first launch of the App , the editors will not be functional.
  1252. try:
  1253. self.geo_editor = FlatCAMGeoEditor(self)
  1254. except AttributeError:
  1255. pass
  1256. try:
  1257. self.exc_editor = FlatCAMExcEditor(self)
  1258. except AttributeError:
  1259. pass
  1260. try:
  1261. self.grb_editor = FlatCAMGrbEditor(self)
  1262. except AttributeError:
  1263. pass
  1264. self.log.debug("Finished adding FlatCAM Editor's.")
  1265. self.set_ui_title(name=_("New Project - Not saved"))
  1266. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1267. current_platform = platform.architecture()[0]
  1268. if current_platform != '64bit':
  1269. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1270. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1271. # ###########################################################################################################
  1272. # ########################################### EXCLUSION AREAS ###############################################
  1273. # ###########################################################################################################
  1274. self.exc_areas = ExclusionAreas(app=self)
  1275. # ###########################################################################################################
  1276. # ##################################### Finished the CONSTRUCTOR ############################################
  1277. # ###########################################################################################################
  1278. App.log.debug("END of constructor. Releasing control.")
  1279. # ###########################################################################################################
  1280. # ########################################## SHOW GUI #######################################################
  1281. # ###########################################################################################################
  1282. # if the app is not started as headless, show it
  1283. if self.cmd_line_headless != 1:
  1284. if show_splash:
  1285. # finish the splash
  1286. self.splash.finish(self.ui)
  1287. mgui_settings = QSettings("Open Source", "FlatCAM")
  1288. if mgui_settings.contains("maximized_gui"):
  1289. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1290. if maximized_ui is True:
  1291. self.ui.showMaximized()
  1292. else:
  1293. self.ui.show()
  1294. else:
  1295. self.ui.show()
  1296. if self.defaults["global_systray_icon"]:
  1297. self.trayIcon.show()
  1298. else:
  1299. log.warning("******************* RUNNING HEADLESS *******************")
  1300. # ###########################################################################################################
  1301. # ######################################## START-UP ARGUMENTS ###############################################
  1302. # ###########################################################################################################
  1303. # test if the program was started with a script as parameter
  1304. if self.cmd_line_shellvar:
  1305. try:
  1306. cnt = 0
  1307. command_tcl = 0
  1308. for i in self.cmd_line_shellvar.split(','):
  1309. if i is not None:
  1310. # noinspection PyBroadException
  1311. try:
  1312. command_tcl = eval(i)
  1313. except Exception:
  1314. command_tcl = i
  1315. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1316. cnt += 1
  1317. # if there are Windows paths then replace the path separator with a Unix like one
  1318. if sys.platform == 'win32':
  1319. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1320. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1321. except Exception as ext:
  1322. print("ERROR: ", ext)
  1323. sys.exit(2)
  1324. if self.cmd_line_shellfile:
  1325. if self.cmd_line_headless != 1:
  1326. if self.ui.shell_dock.isHidden():
  1327. self.ui.shell_dock.show()
  1328. try:
  1329. with open(self.cmd_line_shellfile, "r") as myfile:
  1330. # if show_splash:
  1331. # self.splash.showMessage('%s: %ssec\n%s' % (
  1332. # _("Canvas initialization started.\n"
  1333. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1334. # _("Executing Tcl Script ...")),
  1335. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1336. # color=QtGui.QColor("gray"))
  1337. cmd_line_shellfile_text = myfile.read()
  1338. if self.cmd_line_headless != 1:
  1339. self.shell.exec_command(cmd_line_shellfile_text)
  1340. else:
  1341. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1342. except Exception as ext:
  1343. print("ERROR: ", ext)
  1344. sys.exit(2)
  1345. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1346. # the path/file_name must be enclosed in quotes if it contain spaces
  1347. if App.args:
  1348. self.args_at_startup.emit(App.args)
  1349. if self.defaults.old_defaults_found is True:
  1350. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1351. "Please reboot the application to update."))
  1352. self.defaults.old_defaults_found = False
  1353. # ######################################### INIT FINISHED #######################################################
  1354. # #################################################################################################################
  1355. # #################################################################################################################
  1356. # #################################################################################################################
  1357. # #################################################################################################################
  1358. # #################################################################################################################
  1359. @staticmethod
  1360. def copy_and_overwrite(from_path, to_path):
  1361. """
  1362. From here:
  1363. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1364. :param from_path: source path
  1365. :param to_path: destination path
  1366. :return: None
  1367. """
  1368. if os.path.exists(to_path):
  1369. shutil.rmtree(to_path)
  1370. try:
  1371. shutil.copytree(from_path, to_path)
  1372. except FileNotFoundError:
  1373. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1374. shutil.copytree(from_new_path, to_path)
  1375. def on_startup_args(self, args, silent=False):
  1376. """
  1377. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1378. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1379. :param args: a list containing the application args at startup
  1380. :return: None
  1381. """
  1382. if args is not None:
  1383. args_to_process = args
  1384. else:
  1385. args_to_process = App.args
  1386. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1387. for argument in args_to_process:
  1388. if '.FlatPrj'.lower() in argument.lower():
  1389. try:
  1390. project_name = str(argument)
  1391. if project_name == "":
  1392. if silent is False:
  1393. self.inform.emit(_("Cancelled."))
  1394. else:
  1395. # self.open_project(project_name)
  1396. run_from_arg = True
  1397. # self.worker_task.emit({'fcn': self.open_project,
  1398. # 'params': [project_name, run_from_arg]})
  1399. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1400. except Exception as e:
  1401. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1402. elif '.FlatConfig'.lower() in argument.lower():
  1403. try:
  1404. file_name = str(argument)
  1405. if file_name == "":
  1406. if silent is False:
  1407. self.inform.emit(_("Open Config file failed."))
  1408. else:
  1409. run_from_arg = True
  1410. # self.worker_task.emit({'fcn': self.open_config_file,
  1411. # 'params': [file_name, run_from_arg]})
  1412. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1413. except Exception as e:
  1414. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1415. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1416. try:
  1417. file_name = str(argument)
  1418. if file_name == "":
  1419. if silent is False:
  1420. self.inform.emit(_("Open Script file failed."))
  1421. else:
  1422. if silent is False:
  1423. self.on_fileopenscript(name=file_name)
  1424. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1425. self.on_filerunscript(name=file_name)
  1426. except Exception as e:
  1427. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1428. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1429. log.debug("App.on_startup_args() --> Quit event.")
  1430. sys.exit()
  1431. elif 'save'.lower() in argument.lower():
  1432. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1433. self.preferencesUiManager.save_defaults()
  1434. else:
  1435. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1436. proc_arg = argument.lower()
  1437. for ext in exc_list:
  1438. proc_ext = ext.replace(' ', '')
  1439. proc_ext = '.%s' % proc_ext
  1440. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1441. file_name = str(argument)
  1442. if file_name == "":
  1443. if silent is False:
  1444. self.inform.emit(_("Open Excellon file failed."))
  1445. else:
  1446. self.on_fileopenexcellon(name=file_name, signal=None)
  1447. return
  1448. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1449. for ext in gco_list:
  1450. proc_ext = ext.replace(' ', '')
  1451. proc_ext = '.%s' % proc_ext
  1452. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1453. file_name = str(argument)
  1454. if file_name == "":
  1455. if silent is False:
  1456. self.inform.emit(_("Open GCode file failed."))
  1457. else:
  1458. self.on_fileopengcode(name=file_name, signal=None)
  1459. return
  1460. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1461. for ext in grb_list:
  1462. proc_ext = ext.replace(' ', '')
  1463. proc_ext = '.%s' % proc_ext
  1464. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1465. file_name = str(argument)
  1466. if file_name == "":
  1467. if silent is False:
  1468. self.inform.emit(_("Open Gerber file failed."))
  1469. else:
  1470. self.on_fileopengerber(name=file_name, signal=None)
  1471. return
  1472. # if it reached here without already returning then the app was registered with a file that it does not
  1473. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1474. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1475. # for arg in args_to_process:
  1476. # if 'FlatCAM.exe' in arg:
  1477. # continue
  1478. # else:
  1479. # sys.exit(2)
  1480. def set_ui_title(self, name):
  1481. """
  1482. Sets the title of the main window.
  1483. :param name: String that store the project path and project name
  1484. :return: None
  1485. """
  1486. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1487. (self.version,
  1488. ('BETA' if self.beta else ''),
  1489. platform.architecture()[0],
  1490. self.engine,
  1491. name)
  1492. )
  1493. def on_app_restart(self):
  1494. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1495. # be left in the SySTray
  1496. try:
  1497. self.trayIcon.hide()
  1498. except Exception:
  1499. pass
  1500. fcTranslate.restart_program(app=self)
  1501. def clear_pool(self):
  1502. """
  1503. Clear the multiprocessing pool and calls garbage collector.
  1504. :return: None
  1505. """
  1506. self.pool.close()
  1507. self.pool = Pool()
  1508. self.pool_recreated.emit(self.pool)
  1509. gc.collect()
  1510. def install_tools(self):
  1511. """
  1512. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1513. Instantiation of the Tools classes.
  1514. The order that the tools are installed is important as they can depend on each other install position.
  1515. :return: None
  1516. """
  1517. self.distance_tool = Distance(self)
  1518. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1519. before=self.ui.menueditorigin,
  1520. separator=False)
  1521. self.distance_min_tool = DistanceMin(self)
  1522. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1523. pos=self.ui.menuedit,
  1524. before=self.ui.menueditorigin,
  1525. separator=True)
  1526. self.dblsidedtool = DblSidedTool(self)
  1527. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1528. self.cal_exc_tool = ToolCalibration(self)
  1529. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1530. before=self.dblsidedtool.menuAction,
  1531. separator=False)
  1532. self.align_objects_tool = AlignObjects(self)
  1533. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1534. self.edrills_tool = ToolExtractDrills(self)
  1535. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1536. self.panelize_tool = Panelize(self)
  1537. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1538. self.film_tool = Film(self)
  1539. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1540. self.paste_tool = SolderPaste(self)
  1541. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1542. self.calculator_tool = ToolCalculator(self)
  1543. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1544. self.sub_tool = ToolSub(self)
  1545. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1546. pos=self.ui.menutool, separator=True)
  1547. self.rules_tool = RulesCheck(self)
  1548. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1549. pos=self.ui.menutool, separator=False)
  1550. self.optimal_tool = ToolOptimal(self)
  1551. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1552. pos=self.ui.menutool, separator=True)
  1553. self.move_tool = ToolMove(self)
  1554. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1555. before=self.ui.menueditorigin, separator=True)
  1556. self.cutout_tool = CutOut(self)
  1557. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1558. before=self.sub_tool.menuAction)
  1559. self.ncclear_tool = NonCopperClear(self)
  1560. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1561. before=self.sub_tool.menuAction, separator=True)
  1562. self.paint_tool = ToolPaint(self)
  1563. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1564. before=self.sub_tool.menuAction, separator=True)
  1565. self.isolation_tool = ToolIsolation(self)
  1566. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1567. before=self.sub_tool.menuAction, separator=True)
  1568. self.copper_thieving_tool = ToolCopperThieving(self)
  1569. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1570. pos=self.ui.menutool)
  1571. self.fiducial_tool = ToolFiducials(self)
  1572. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1573. pos=self.ui.menutool)
  1574. self.qrcode_tool = QRCode(self)
  1575. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1576. pos=self.ui.menutool)
  1577. self.punch_tool = ToolPunchGerber(self)
  1578. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1579. self.invert_tool = ToolInvertGerber(self)
  1580. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1581. self.corners_tool = ToolCorners(self)
  1582. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1583. self.etch_tool = ToolEtchCompensation(self)
  1584. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1585. self.transform_tool = ToolTransform(self)
  1586. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1587. pos=self.ui.menuoptions, separator=True)
  1588. self.properties_tool = Properties(self)
  1589. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1590. pos=self.ui.menuoptions)
  1591. self.pdf_tool = ToolPDF(self)
  1592. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1593. pos=self.ui.menufileimport,
  1594. separator=True)
  1595. self.image_tool = ToolImage(self)
  1596. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1597. pos=self.ui.menufileimport,
  1598. separator=True)
  1599. self.pcb_wizard_tool = PcbWizard(self)
  1600. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1601. pos=self.ui.menufileimport)
  1602. self.log.debug("Tools are installed.")
  1603. def remove_tools(self):
  1604. """
  1605. Will remove all the actions in the Tool menu.
  1606. :return: None
  1607. """
  1608. for act in self.ui.menutool.actions():
  1609. self.ui.menutool.removeAction(act)
  1610. def init_tools(self):
  1611. """
  1612. Initialize the Tool tab in the notebook side of the central widget.
  1613. Remove the actions in the Tools menu.
  1614. Instantiate again the FlatCAM tools (plugins).
  1615. All this is required when changing the layout: standard, compact etc.
  1616. :return: None
  1617. """
  1618. log.debug("init_tools()")
  1619. # delete the data currently in the Tools Tab and the Tab itself
  1620. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1621. if widget is not None:
  1622. widget.deleteLater()
  1623. self.ui.notebook.removeTab(2)
  1624. # rebuild the Tools Tab
  1625. self.ui.tool_tab = QtWidgets.QWidget()
  1626. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1627. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1628. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1629. self.ui.tool_scroll_area = VerticalScrollArea()
  1630. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1631. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1632. # first remove all of them
  1633. self.remove_tools()
  1634. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1635. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1636. '&Command Line\tS')
  1637. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1638. # third install all of them
  1639. try:
  1640. self.install_tools()
  1641. except AttributeError:
  1642. pass
  1643. self.log.debug("Tools are initialized.")
  1644. # def parse_system_fonts(self):
  1645. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1646. # 'params': []})
  1647. def connect_toolbar_signals(self):
  1648. """
  1649. Reconnect the signals to the actions in the toolbar.
  1650. This has to be done each time after the FlatCAM tools are removed/installed.
  1651. :return: None
  1652. """
  1653. # Toolbar
  1654. # File Toolbar Signals
  1655. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1656. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1657. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1658. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1659. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1660. # View Toolbar Signals
  1661. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1662. self.ui.replot_btn.triggered.connect(self.plot_all)
  1663. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1664. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1665. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1666. # Edit Toolbar Signals
  1667. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1668. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1669. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1670. self.ui.delete_btn.triggered.connect(self.on_delete)
  1671. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1672. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1673. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1674. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1675. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1676. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1677. # Scripting Toolbar Signals
  1678. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1679. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1680. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1681. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1682. # Tools Toolbar Signals
  1683. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1684. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1685. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1686. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1687. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1688. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1689. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1690. self.ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1691. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1692. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1693. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1694. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1695. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1696. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1697. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1698. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1699. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1700. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1701. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1702. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1703. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1704. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1705. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1706. def object2editor(self):
  1707. """
  1708. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1709. :return: None
  1710. """
  1711. self.defaults.report_usage("object2editor()")
  1712. # disable the objects menu as it may interfere with the AppEditors
  1713. self.ui.menuobjects.setDisabled(True)
  1714. edited_object = self.collection.get_active()
  1715. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1716. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1717. pass
  1718. else:
  1719. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1720. return
  1721. if isinstance(edited_object, GeometryObject):
  1722. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1723. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1724. # we set the notebook to hidden
  1725. # self.ui.splitter.setSizes([0, 1])
  1726. if edited_object.multigeo is True:
  1727. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1728. if len(sel_rows) > 1:
  1729. self.inform.emit('[WARNING_NOTCL] %s' %
  1730. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1731. "is not possible.\n"
  1732. "Edit only one geometry at a time."))
  1733. # determine the tool dia of the selected tool
  1734. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1735. # now find the key in the edited_object.tools that has this tooldia
  1736. multi_tool = 1
  1737. for tool in edited_object.tools:
  1738. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1739. multi_tool = tool
  1740. break
  1741. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1742. else:
  1743. self.geo_editor.edit_fcgeometry(edited_object)
  1744. # set call source to the Editor we go into
  1745. self.call_source = 'geo_editor'
  1746. elif isinstance(edited_object, ExcellonObject):
  1747. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1748. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1749. if self.ui.splitter.sizes()[0] == 0:
  1750. self.ui.splitter.setSizes([1, 1])
  1751. self.exc_editor.edit_fcexcellon(edited_object)
  1752. # set call source to the Editor we go into
  1753. self.call_source = 'exc_editor'
  1754. elif isinstance(edited_object, GerberObject):
  1755. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1756. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1757. if self.ui.splitter.sizes()[0] == 0:
  1758. self.ui.splitter.setSizes([1, 1])
  1759. self.grb_editor.edit_fcgerber(edited_object)
  1760. # set call source to the Editor we go into
  1761. self.call_source = 'grb_editor'
  1762. # reset the following variables so the UI is built again after edit
  1763. edited_object.ui_build = False
  1764. edited_object.build_aperture_storage = False
  1765. elif isinstance(edited_object, CNCJobObject):
  1766. if self.ui.splitter.sizes()[0] == 0:
  1767. self.ui.splitter.setSizes([1, 1])
  1768. edited_object.on_edit_code_click()
  1769. return
  1770. # make sure that we can't select another object while in Editor Mode:
  1771. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1772. self.ui.project_frame.setDisabled(True)
  1773. # delete any selection shape that might be active as they are not relevant in Editor
  1774. self.delete_selection_shape()
  1775. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1776. self.ui.plot_tab_area.protectTab(0)
  1777. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1778. self.should_we_save = True
  1779. def editor2object(self, cleanup=None):
  1780. """
  1781. Transfers the Geometry or Excellon from it's editor to the current object.
  1782. :return: None
  1783. """
  1784. self.defaults.report_usage("editor2object()")
  1785. # re-enable the objects menu that was disabled on entry in Editor mode
  1786. self.ui.menuobjects.setDisabled(False)
  1787. # do not update a geometry or excellon object unless it comes out of an editor
  1788. if self.call_source != 'app':
  1789. edited_obj = self.collection.get_active()
  1790. if cleanup is None:
  1791. msgbox = QtWidgets.QMessageBox()
  1792. msgbox.setText(_("Do you want to save the edited object?"))
  1793. msgbox.setWindowTitle(_("Close Editor"))
  1794. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1795. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1796. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1797. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1798. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1799. msgbox.setDefaultButton(bt_yes)
  1800. msgbox.exec_()
  1801. response = msgbox.clickedButton()
  1802. if response == bt_yes:
  1803. # clean the Tools Tab
  1804. self.ui.tool_scroll_area.takeWidget()
  1805. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1806. self.ui.notebook.setTabText(2, "Tool")
  1807. if isinstance(edited_obj, GeometryObject):
  1808. obj_type = "Geometry"
  1809. self.geo_editor.update_fcgeometry(edited_obj)
  1810. # self.geo_editor.update_options(edited_obj)
  1811. # restore GUI to the Selected TAB
  1812. # Remove anything else in the AppGUI
  1813. self.ui.tool_scroll_area.takeWidget()
  1814. # update the geo object options so it is including the bounding box values
  1815. try:
  1816. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1817. edited_obj.options['xmin'] = xmin
  1818. edited_obj.options['ymin'] = ymin
  1819. edited_obj.options['xmax'] = xmax
  1820. edited_obj.options['ymax'] = ymax
  1821. except AttributeError as e:
  1822. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1823. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1824. edited_obj.build_ui()
  1825. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1826. elif isinstance(edited_obj, GerberObject):
  1827. obj_type = "Gerber"
  1828. self.grb_editor.update_fcgerber()
  1829. # self.grb_editor.update_options(edited_obj)
  1830. # delete the old object (the source object) if it was an empty one
  1831. try:
  1832. if len(edited_obj.solid_geometry) == 0:
  1833. old_name = edited_obj.options['name']
  1834. self.collection.delete_by_name(old_name)
  1835. except TypeError:
  1836. # if the solid_geometry is a single Polygon the len() will not work
  1837. # in any case, falling here means that we have something in the solid_geometry, even if only
  1838. # a single Polygon, therefore we pass this
  1839. pass
  1840. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1841. # restore GUI to the Selected TAB
  1842. # Remove anything else in the AppGUI
  1843. self.ui.selected_scroll_area.takeWidget()
  1844. elif isinstance(edited_obj, ExcellonObject):
  1845. obj_type = "Excellon"
  1846. self.exc_editor.update_fcexcellon(edited_obj)
  1847. # self.exc_editor.update_options(edited_obj)
  1848. # restore GUI to the Selected TAB
  1849. # Remove anything else in the AppGUI
  1850. self.ui.tool_scroll_area.takeWidget()
  1851. # delete the old object (the source object) if it was an empty one
  1852. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1853. old_name = edited_obj.options['name']
  1854. self.collection.delete_by_name(name=old_name)
  1855. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1856. else:
  1857. self.inform.emit('[WARNING_NOTCL] %s' %
  1858. _("Select a Gerber, Geometry or Excellon Object to update."))
  1859. return
  1860. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1861. elif response == bt_no:
  1862. # clean the Tools Tab
  1863. self.ui.tool_scroll_area.takeWidget()
  1864. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1865. self.ui.notebook.setTabText(2, "Tool")
  1866. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1867. if isinstance(edited_obj, GeometryObject):
  1868. self.geo_editor.deactivate()
  1869. edited_obj.build_ui()
  1870. elif isinstance(edited_obj, GerberObject):
  1871. self.grb_editor.deactivate_grb_editor()
  1872. edited_obj.build_ui()
  1873. elif isinstance(edited_obj, ExcellonObject):
  1874. self.exc_editor.deactivate()
  1875. edited_obj.build_ui()
  1876. else:
  1877. self.inform.emit('[WARNING_NOTCL] %s' %
  1878. _("Select a Gerber, Geometry or Excellon Object to update."))
  1879. return
  1880. elif response == bt_cancel:
  1881. return
  1882. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1883. # edited_obj.build_ui()
  1884. # Switch notebook to Selected page
  1885. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1886. else:
  1887. if isinstance(edited_obj, GeometryObject):
  1888. self.geo_editor.deactivate()
  1889. elif isinstance(edited_obj, GerberObject):
  1890. self.grb_editor.deactivate_grb_editor()
  1891. elif isinstance(edited_obj, ExcellonObject):
  1892. self.exc_editor.deactivate()
  1893. else:
  1894. self.inform.emit('[WARNING_NOTCL] %s' %
  1895. _("Select a Gerber, Geometry or Excellon Object to update."))
  1896. return
  1897. # if notebook is hidden we show it
  1898. if self.ui.splitter.sizes()[0] == 0:
  1899. self.ui.splitter.setSizes([1, 1])
  1900. # restore the call_source to app
  1901. self.call_source = 'app'
  1902. # edited_obj.plot()
  1903. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1904. self.ui.plot_tab_area.protectTab(0)
  1905. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1906. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1907. self.ui.project_frame.setDisabled(False)
  1908. def get_last_folder(self):
  1909. """
  1910. Get the folder path from where the last file was opened.
  1911. :return: String, last opened folder path
  1912. """
  1913. return self.defaults["global_last_folder"]
  1914. def get_last_save_folder(self):
  1915. """
  1916. Get the folder path from where the last file was saved.
  1917. :return: String, last saved folder path
  1918. """
  1919. loc = self.defaults["global_last_save_folder"]
  1920. if loc is None:
  1921. loc = self.defaults["global_last_folder"]
  1922. if loc is None:
  1923. loc = os.path.dirname(__file__)
  1924. return loc
  1925. @QtCore.pyqtSlot(str)
  1926. @QtCore.pyqtSlot(str, bool)
  1927. def info(self, msg, shell_echo=True):
  1928. """
  1929. Informs the user. Normally on the status bar, optionally
  1930. also on the shell.
  1931. :param msg: Text to write.
  1932. :return: None
  1933. """
  1934. # Type of message in brackets at the beginning of the message.
  1935. match = re.search(r"\[(.*)\](.*)", msg)
  1936. if match:
  1937. level = match.group(1)
  1938. msg_ = match.group(2)
  1939. self.ui.fcinfo.set_status(str(msg_), level=level)
  1940. if shell_echo is True:
  1941. if level.lower() == "error":
  1942. self.shell_message(msg, error=True, show=True)
  1943. elif level.lower() == "warning":
  1944. self.shell_message(msg, warning=True, show=True)
  1945. elif level.lower() == "error_notcl":
  1946. self.shell_message(msg, error=True, show=False)
  1947. elif level.lower() == "warning_notcl":
  1948. self.shell_message(msg, warning=True, show=False)
  1949. elif level.lower() == "success":
  1950. self.shell_message(msg, success=True, show=False)
  1951. elif level.lower() == "selected":
  1952. self.shell_message(msg, selected=True, show=False)
  1953. else:
  1954. self.shell_message(msg, show=False)
  1955. else:
  1956. self.ui.fcinfo.set_status(str(msg), level="info")
  1957. # make sure that if the message is to clear the infobar with a space
  1958. # is not printed over and over on the shell
  1959. if msg != '' and shell_echo is True:
  1960. self.shell_message(msg)
  1961. def on_import_preferences(self):
  1962. """
  1963. Loads the application default settings from a saved file into
  1964. ``self.defaults`` dictionary.
  1965. :return: None
  1966. """
  1967. self.defaults.report_usage("on_import_preferences")
  1968. App.log.debug("App.on_import_preferences()")
  1969. # Show file chooser
  1970. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1971. try:
  1972. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1973. directory=self.data_path,
  1974. filter=filter_)
  1975. except TypeError:
  1976. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1977. filter=filter_)
  1978. filename = str(filename)
  1979. if filename == "":
  1980. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1981. return
  1982. # Load in the defaults from the chosen file
  1983. self.defaults.load(filename=filename)
  1984. self.preferencesUiManager.on_preferences_edited()
  1985. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  1986. def on_export_preferences(self):
  1987. """
  1988. Save the defaults dictionary to a file.
  1989. :return: None
  1990. """
  1991. self.defaults.report_usage("on_export_preferences")
  1992. App.log.debug("on_export_preferences()")
  1993. # defaults_file_content = None
  1994. # Show file chooser
  1995. date = str(datetime.today()).rpartition('.')[0]
  1996. date = ''.join(c for c in date if c not in ':-')
  1997. date = date.replace(' ', '_')
  1998. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  1999. try:
  2000. filename, _f = FCFileSaveDialog.get_saved_filename(
  2001. caption=_("Export FlatCAM Preferences"),
  2002. directory=self.data_path + '/preferences_' + date,
  2003. filter=filter__
  2004. )
  2005. except TypeError:
  2006. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2007. filename = str(filename)
  2008. if filename == "":
  2009. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2010. return
  2011. # Update options
  2012. self.preferencesUiManager.defaults_read_form()
  2013. self.defaults.propagate_defaults()
  2014. # Save update options
  2015. try:
  2016. self.defaults.write(filename=filename)
  2017. except Exception:
  2018. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2019. return
  2020. if self.defaults["global_open_style"] is False:
  2021. self.file_opened.emit("preferences", filename)
  2022. self.file_saved.emit("preferences", filename)
  2023. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2024. def save_to_file(self, content_to_save, txt_content):
  2025. """
  2026. Save something to a file.
  2027. :return: None
  2028. """
  2029. self.defaults.report_usage("save_to_file")
  2030. App.log.debug("save_to_file()")
  2031. self.date = str(datetime.today()).rpartition('.')[0]
  2032. self.date = ''.join(c for c in self.date if c not in ':-')
  2033. self.date = self.date.replace(' ', '_')
  2034. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2035. path_to_save = self.defaults["global_last_save_folder"] if \
  2036. self.defaults["global_last_save_folder"] is not None else self.data_path
  2037. try:
  2038. filename, _f = FCFileSaveDialog.get_saved_filename(
  2039. caption=_("Save to file"),
  2040. directory=path_to_save + '/file_' + self.date,
  2041. filter=filter__
  2042. )
  2043. except TypeError:
  2044. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2045. filename = str(filename)
  2046. if filename == "":
  2047. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2048. return
  2049. else:
  2050. try:
  2051. with open(filename, 'w') as f:
  2052. ___ = f.read()
  2053. except PermissionError:
  2054. self.inform.emit('[WARNING] %s' %
  2055. _("Permission denied, saving not possible.\n"
  2056. "Most likely another app is holding the file open and not accessible."))
  2057. return
  2058. except IOError:
  2059. App.log.debug('Creating a new file ...')
  2060. f = open(filename, 'w')
  2061. f.close()
  2062. except Exception:
  2063. e = sys.exc_info()[0]
  2064. App.log.error("Could not load the file.")
  2065. App.log.error(str(e))
  2066. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2067. return
  2068. # Save content
  2069. if filename.rpartition('.')[2].lower() == 'html':
  2070. file_content = content_to_save
  2071. else:
  2072. file_content = txt_content
  2073. try:
  2074. with open(filename, "w") as f:
  2075. f.write(file_content)
  2076. except Exception:
  2077. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2078. return
  2079. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2080. def register_recent(self, kind, filename):
  2081. """
  2082. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2083. dictionary.
  2084. :param kind: type of file that was opened
  2085. :param filename: the path and file name for the file that was opened
  2086. :return:
  2087. """
  2088. self.log.debug("register_recent()")
  2089. self.log.debug(" %s" % kind)
  2090. self.log.debug(" %s" % filename)
  2091. record = {'kind': str(kind), 'filename': str(filename)}
  2092. if record in self.recent:
  2093. return
  2094. if record in self.recent_projects:
  2095. return
  2096. if record['kind'] == 'project':
  2097. self.recent_projects.insert(0, record)
  2098. else:
  2099. self.recent.insert(0, record)
  2100. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2101. self.recent.pop()
  2102. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2103. self.recent_projects.pop()
  2104. try:
  2105. f = open(self.data_path + '/recent.json', 'w')
  2106. except IOError:
  2107. App.log.error("Failed to open recent items file for writing.")
  2108. self.inform.emit('[ERROR_NOTCL] %s' %
  2109. _('Failed to open recent files file for writing.'))
  2110. return
  2111. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2112. f.close()
  2113. try:
  2114. fp = open(self.data_path + '/recent_projects.json', 'w')
  2115. except IOError:
  2116. App.log.error("Failed to open recent items file for writing.")
  2117. self.inform.emit('[ERROR_NOTCL] %s' %
  2118. _('Failed to open recent projects file for writing.'))
  2119. return
  2120. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2121. fp.close()
  2122. # Re-build the recent items menu
  2123. self.setup_recent_items()
  2124. def on_about(self):
  2125. """
  2126. Displays the "about" dialog found in the Menu --> Help.
  2127. :return: None
  2128. """
  2129. self.defaults.report_usage("on_about")
  2130. version = self.version
  2131. version_date = self.version_date
  2132. beta = self.beta
  2133. class AboutDialog(QtWidgets.QDialog):
  2134. def __init__(self, app, parent=None):
  2135. QtWidgets.QDialog.__init__(self, parent)
  2136. self.app = app
  2137. # Icon and title
  2138. self.setWindowIcon(parent.app_icon)
  2139. self.setWindowTitle(_("About FlatCAM"))
  2140. self.resize(600, 200)
  2141. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2142. # self.setStyleSheet(
  2143. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2144. # "background-attachment: fixed"
  2145. # )
  2146. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2147. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2148. # palette = QtGui.QPalette()
  2149. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2150. # self.setPalette(palette)
  2151. logo = QtWidgets.QLabel()
  2152. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2153. title = QtWidgets.QLabel(
  2154. "<font size=8><B>FlatCAM</B></font><BR>"
  2155. "{title}<BR>"
  2156. "<BR>"
  2157. "<BR>"
  2158. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2159. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2160. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2161. "<B>{issue}</B></a><BR>".format(
  2162. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2163. devel=_("Development"),
  2164. down=_("DOWNLOAD"),
  2165. issue=_("Issue tracker"))
  2166. )
  2167. title.setOpenExternalLinks(True)
  2168. closebtn = QtWidgets.QPushButton(_("Close"))
  2169. tab_widget = QtWidgets.QTabWidget()
  2170. description_label = QtWidgets.QLabel(
  2171. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2172. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2173. version=version,
  2174. beta=('BETA' if beta else ''),
  2175. date=version_date,
  2176. arch=platform.architecture()[0])
  2177. )
  2178. description_label.setOpenExternalLinks(True)
  2179. lic_lbl_header = QtWidgets.QLabel(
  2180. '%s:<br>%s<br>' % (
  2181. _('Licensed under the MIT license'),
  2182. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2183. "http://www.opensource.org/licenses/mit-license.php</a>"
  2184. )
  2185. )
  2186. lic_lbl_header.setOpenExternalLinks(True)
  2187. lic_lbl_body = QtWidgets.QLabel(
  2188. _(
  2189. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2190. 'of this software and associated documentation files (the "Software"), to deal\n'
  2191. 'in the Software without restriction, including without limitation the rights\n'
  2192. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2193. 'copies of the Software, and to permit persons to whom the Software is\n'
  2194. 'furnished to do so, subject to the following conditions:\n\n'
  2195. 'The above copyright notice and this permission notice shall be included in\n'
  2196. 'all copies or substantial portions of the Software.\n\n'
  2197. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2198. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2199. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2200. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2201. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2202. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2203. 'THE SOFTWARE.'
  2204. )
  2205. )
  2206. attributions_label = QtWidgets.QLabel(
  2207. _(
  2208. 'Some of the icons used are from the following sources:<br>'
  2209. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2210. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2211. 'title="Flaticon">www.flaticon.com</a></div>'
  2212. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2213. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2214. )
  2215. )
  2216. attributions_label.setOpenExternalLinks(True)
  2217. # layouts
  2218. layout1 = QtWidgets.QVBoxLayout()
  2219. layout1_1 = QtWidgets.QHBoxLayout()
  2220. layout1_2 = QtWidgets.QHBoxLayout()
  2221. layout2 = QtWidgets.QHBoxLayout()
  2222. layout3 = QtWidgets.QHBoxLayout()
  2223. self.setLayout(layout1)
  2224. layout1.addLayout(layout1_1)
  2225. layout1.addLayout(layout1_2)
  2226. layout1.addLayout(layout2)
  2227. layout1.addLayout(layout3)
  2228. layout1_1.addStretch()
  2229. layout1_1.addWidget(description_label)
  2230. layout1_2.addWidget(tab_widget)
  2231. self.splash_tab = QtWidgets.QWidget()
  2232. self.splash_tab.setObjectName("splash_about")
  2233. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2234. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2235. tab_widget.addTab(self.splash_tab, _("Splash"))
  2236. self.programmmers_tab = QtWidgets.QWidget()
  2237. self.programmmers_tab.setObjectName("programmers_about")
  2238. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2239. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2240. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2241. self.translators_tab = QtWidgets.QWidget()
  2242. self.translators_tab.setObjectName("translators_about")
  2243. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2244. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2245. tab_widget.addTab(self.translators_tab, _("Translators"))
  2246. self.license_tab = QtWidgets.QWidget()
  2247. self.license_tab.setObjectName("license_about")
  2248. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2249. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2250. tab_widget.addTab(self.license_tab, _("License"))
  2251. self.attributions_tab = QtWidgets.QWidget()
  2252. self.attributions_tab.setObjectName("attributions_about")
  2253. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2254. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2255. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2256. self.splash_tab_layout.addWidget(logo, stretch=0)
  2257. self.splash_tab_layout.addWidget(title, stretch=1)
  2258. pal = QtGui.QPalette()
  2259. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2260. self.prog_grid_lay = QtWidgets.QGridLayout()
  2261. self.prog_grid_lay.setHorizontalSpacing(20)
  2262. self.prog_grid_lay.setColumnStretch(0, 0)
  2263. self.prog_grid_lay.setColumnStretch(2, 1)
  2264. prog_widget = QtWidgets.QWidget()
  2265. prog_widget.setLayout(self.prog_grid_lay)
  2266. prog_scroll = QtWidgets.QScrollArea()
  2267. prog_scroll.setWidget(prog_widget)
  2268. prog_scroll.setWidgetResizable(True)
  2269. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2270. prog_scroll.setPalette(pal)
  2271. self.programmmers_tab_layout.addWidget(prog_scroll)
  2272. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2273. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2274. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2275. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2276. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2277. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2278. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2279. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2280. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2281. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2282. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2283. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2284. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2285. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2286. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2287. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2288. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2289. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2290. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2291. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2292. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2293. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2294. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2295. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2296. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2297. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2298. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2299. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2300. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2301. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2302. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2303. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2304. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2315. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2317. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2318. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2319. self.translator_grid_lay = QtWidgets.QGridLayout()
  2320. self.translator_grid_lay.setColumnStretch(0, 0)
  2321. self.translator_grid_lay.setColumnStretch(1, 0)
  2322. self.translator_grid_lay.setColumnStretch(2, 1)
  2323. self.translator_grid_lay.setColumnStretch(3, 0)
  2324. # trans_widget = QtWidgets.QWidget()
  2325. # trans_widget.setLayout(self.translator_grid_lay)
  2326. # self.translators_tab_layout.addWidget(trans_widget)
  2327. # self.translators_tab_layout.addStretch()
  2328. trans_widget = QtWidgets.QWidget()
  2329. trans_widget.setLayout(self.translator_grid_lay)
  2330. trans_scroll = QtWidgets.QScrollArea()
  2331. trans_scroll.setWidget(trans_widget)
  2332. trans_scroll.setWidgetResizable(True)
  2333. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2334. trans_scroll.setPalette(pal)
  2335. self.translators_tab_layout.addWidget(trans_scroll)
  2336. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2337. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2338. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2339. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2340. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2341. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2342. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2343. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2344. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2345. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2346. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2347. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2348. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2349. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2350. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2351. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2352. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2353. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2354. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2355. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2356. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2357. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2358. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2359. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2360. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2361. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2362. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2363. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2364. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2365. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2366. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2367. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2368. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2369. self.translator_grid_lay.setColumnStretch(0, 0)
  2370. self.translators_tab_layout.addStretch()
  2371. self.license_tab_layout.addWidget(lic_lbl_header)
  2372. self.license_tab_layout.addWidget(lic_lbl_body)
  2373. self.license_tab_layout.addStretch()
  2374. self.attributions_tab_layout.addWidget(attributions_label)
  2375. self.attributions_tab_layout.addStretch()
  2376. layout3.addStretch()
  2377. layout3.addWidget(closebtn)
  2378. closebtn.clicked.connect(self.accept)
  2379. AboutDialog(app=self, parent=self.ui).exec_()
  2380. def on_readme(self):
  2381. class AboutDialog(QtWidgets.QDialog):
  2382. def __init__(self, app, parent=None):
  2383. QtWidgets.QDialog.__init__(self, parent)
  2384. self.app = app
  2385. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2386. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2387. "<b>new features</b></a>"
  2388. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>report bugs</b></a>"
  2389. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2390. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>donation</b></a>"
  2391. # Icon and title
  2392. self.setWindowIcon(parent.app_icon)
  2393. self.setWindowTitle(_("Important Information's"))
  2394. self.resize(720, 330)
  2395. logo = QtWidgets.QLabel()
  2396. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2397. content = QtWidgets.QLabel(
  2398. "This program is %s and free in a very wide meaning of the word.<br>"
  2399. "Yet it cannot evolve without <b>contributions</b>.<br><br>"
  2400. "If you want to see this application evolve and grow, or if you make money with it,<br>"
  2401. "you can <b>contribute</b> to the development yourself by:<br>"
  2402. "<ul>"
  2403. "<li>adding %s through a Pull Request on the Bitbucket repository</li>"
  2404. "<li>%s by providing the steps required to reproduce the bug</li>"
  2405. "<li>or by making a %s.</li>"
  2406. "</ul>"
  2407. "There are no strings attached.<br>"
  2408. "You don't have to make a %s, and it is totally optional but:"
  2409. "<ul>"
  2410. "<li>it will be welcomed with joy &#128077;</li>"
  2411. "<li>it will give me a reason to continue &#128513;</li>"
  2412. "</ul>" %
  2413. (open_source_link, new_features_link, bugs_link, donation_link, donation_link)
  2414. )
  2415. content.setOpenExternalLinks(True)
  2416. closebtn = QtWidgets.QPushButton(_("Close"))
  2417. # layouts
  2418. layout1 = QtWidgets.QVBoxLayout()
  2419. self.setLayout(layout1)
  2420. pal = QtGui.QPalette()
  2421. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2422. self.grid_lay = QtWidgets.QGridLayout()
  2423. self.grid_lay.setHorizontalSpacing(20)
  2424. self.grid_lay.setColumnStretch(0, 0)
  2425. self.grid_lay.setColumnStretch(1, 1)
  2426. content_widget = QtWidgets.QWidget()
  2427. content_widget.setLayout(self.grid_lay)
  2428. scroll_area = QtWidgets.QScrollArea()
  2429. scroll_area.setWidget(content_widget)
  2430. scroll_area.setWidgetResizable(True)
  2431. scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2432. scroll_area.setPalette(pal)
  2433. self.grid_lay.addWidget(logo, 0, 0)
  2434. self.grid_lay.addWidget(content, 0, 1)
  2435. layout1.addWidget(scroll_area)
  2436. layout2 = QtWidgets.QHBoxLayout()
  2437. layout1.addLayout(layout2)
  2438. layout2.addStretch()
  2439. layout2.addWidget(closebtn)
  2440. closebtn.clicked.connect(self.accept)
  2441. AboutDialog(app=self, parent=self.ui).exec_()
  2442. def install_bookmarks(self, book_dict=None):
  2443. """
  2444. Install the bookmarks actions in the Help menu -> Bookmarks
  2445. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2446. :return: None
  2447. """
  2448. if book_dict is None:
  2449. self.defaults["global_bookmarks"].update(
  2450. {
  2451. '1': ['FlatCAM', "http://flatcam.org"],
  2452. '2': ['Backup Site', ""]
  2453. }
  2454. )
  2455. else:
  2456. self.defaults["global_bookmarks"].clear()
  2457. self.defaults["global_bookmarks"].update(book_dict)
  2458. # first try to disconnect if somehow they get connected from elsewhere
  2459. for act in self.ui.menuhelp_bookmarks.actions():
  2460. try:
  2461. act.triggered.disconnect()
  2462. except TypeError:
  2463. pass
  2464. # clear all actions except the last one who is the Bookmark manager
  2465. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2466. pass
  2467. else:
  2468. self.ui.menuhelp_bookmarks.removeAction(act)
  2469. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2470. if self.defaults["global_bookmarks"]:
  2471. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2472. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2473. # the JSON is first making the keys as strings (therefore I have to use strings too
  2474. # or do the conversion :(
  2475. # )
  2476. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2477. # the '10' entry jsut after '1' therefore ordering as strings
  2478. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2479. key=lambda x: int(x[0]))
  2480. for entry, bookmark in sorted_bookmarks:
  2481. title = bookmark[0]
  2482. weblink = bookmark[1]
  2483. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2484. act.setText(title)
  2485. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2486. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2487. if title == 'Backup Site' and weblink == "":
  2488. act.triggered.connect(self.on_backup_site)
  2489. else:
  2490. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2491. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2492. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2493. def on_bookmarks_manager(self):
  2494. """
  2495. Adds the bookmark manager in a Tab in Plot Area
  2496. :return:
  2497. """
  2498. for idx in range(self.ui.plot_tab_area.count()):
  2499. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2500. # there can be only one instance of Bookmark Manager at one time
  2501. return
  2502. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2503. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2504. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2505. # add the tab if it was closed
  2506. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2507. # delete the absolute and relative position and messages in the infobar
  2508. self.ui.position_label.setText("")
  2509. # self.ui.rel_position_label.setText("")
  2510. # Switch plot_area to preferences page
  2511. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2512. def on_backup_site(self):
  2513. msgbox = QtWidgets.QMessageBox()
  2514. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2515. "1. FlatCAM.org website is down\n"
  2516. "2. Someone forked FlatCAM project and wants to point\n"
  2517. "to his own website\n\n"
  2518. "If you can't get any informations about FlatCAM beta\n"
  2519. "use the YouTube channel link from the Help menu."))
  2520. msgbox.setWindowTitle(_("Alternative website"))
  2521. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2522. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2523. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2524. msgbox.setDefaultButton(bt_yes)
  2525. msgbox.exec_()
  2526. # response = msgbox.clickedButton()
  2527. def on_file_savedefaults(self):
  2528. """
  2529. Callback for menu item File->Save Defaults. Saves application default options
  2530. ``self.defaults`` to current_defaults.FlatConfig.
  2531. :return: None
  2532. """
  2533. self.preferencesUiManager.save_defaults()
  2534. def final_save(self):
  2535. """
  2536. Callback for doing a preferences save to file whenever the application is about to quit.
  2537. If the project has changes, it will ask the user to save the project.
  2538. :return: None
  2539. """
  2540. if self.save_in_progress:
  2541. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2542. return
  2543. if self.should_we_save and self.collection.get_list():
  2544. msgbox = QtWidgets.QMessageBox()
  2545. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2546. "\n"
  2547. "Do you want to Save the project?"))
  2548. msgbox.setWindowTitle(_("Save changes"))
  2549. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2550. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2551. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2552. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2553. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2554. msgbox.setDefaultButton(bt_yes)
  2555. msgbox.exec_()
  2556. response = msgbox.clickedButton()
  2557. if response == bt_yes:
  2558. try:
  2559. self.trayIcon.hide()
  2560. except Exception:
  2561. pass
  2562. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2563. elif response == bt_no:
  2564. try:
  2565. self.trayIcon.hide()
  2566. except Exception:
  2567. pass
  2568. self.quit_application()
  2569. elif response == bt_cancel:
  2570. return
  2571. else:
  2572. try:
  2573. self.trayIcon.hide()
  2574. except Exception:
  2575. pass
  2576. self.quit_application()
  2577. def quit_application(self):
  2578. """
  2579. Called (as a pyslot or not) when the application is quit.
  2580. :return: None
  2581. """
  2582. self.preferencesUiManager.save_defaults(silent=True)
  2583. log.debug("App.quit_application() --> App Defaults saved.")
  2584. if self.cmd_line_headless != 1:
  2585. # save app state to file
  2586. stgs = QSettings("Open Source", "FlatCAM")
  2587. stgs.setValue('saved_gui_state', self.ui.saveState())
  2588. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2589. stgs.setValue(
  2590. 'language',
  2591. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2592. )
  2593. stgs.setValue(
  2594. 'notebook_font_size',
  2595. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2596. )
  2597. stgs.setValue(
  2598. 'axis_font_size',
  2599. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2600. )
  2601. stgs.setValue(
  2602. 'textbox_font_size',
  2603. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2604. )
  2605. stgs.setValue(
  2606. 'hud_font_size',
  2607. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2608. )
  2609. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2610. stgs.setValue(
  2611. 'machinist',
  2612. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2613. )
  2614. # This will write the setting to the platform specific storage.
  2615. del stgs
  2616. log.debug("App.quit_application() --> App UI state saved.")
  2617. # try to quit the Socket opened by ArgsThread class
  2618. try:
  2619. self.new_launch.stop.emit()
  2620. except Exception as err:
  2621. log.debug("App.quit_application() --> %s" % str(err))
  2622. # try to quit the QThread that run ArgsThread class
  2623. try:
  2624. self.th.quit()
  2625. except Exception as e:
  2626. log.debug("App.quit_application() --> %s" % str(e))
  2627. # terminate workers
  2628. self.workers.__del__()
  2629. # quit app by signalling for self.kill_app() method
  2630. # self.close_app_signal.emit()
  2631. QtWidgets.qApp.quit()
  2632. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2633. # we use the following command
  2634. minor_v = sys.version_info.minor
  2635. if minor_v < 8:
  2636. sys.exit(0)
  2637. else:
  2638. os._exit(0) # fix to work with Python 3.8
  2639. @staticmethod
  2640. def kill_app():
  2641. QtWidgets.qApp.quit()
  2642. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2643. # we use the following command
  2644. sys.exit(0)
  2645. def on_portable_checked(self, state):
  2646. """
  2647. Callback called when the checkbox in Preferences GUI is checked.
  2648. It will set the application as portable by creating the preferences and recent files in the
  2649. 'config' folder found in the FlatCAM installation folder.
  2650. :param state: boolean, the state of the checkbox when clicked/checked
  2651. :return:
  2652. """
  2653. line_no = 0
  2654. data = None
  2655. if sys.platform != 'win32':
  2656. # this won't work in Linux or MacOS
  2657. return
  2658. # test if the app was frozen and choose the path for the configuration file
  2659. if getattr(sys, "frozen", False) is True:
  2660. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2661. else:
  2662. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2663. config_file = current_data_path + '\\configuration.txt'
  2664. try:
  2665. with open(config_file, 'r') as f:
  2666. try:
  2667. data = f.readlines()
  2668. except Exception as e:
  2669. log.debug('App.__init__() -->%s' % str(e))
  2670. return
  2671. except FileNotFoundError:
  2672. pass
  2673. for line in data:
  2674. line = line.strip('\n')
  2675. param = str(line).rpartition('=')
  2676. if param[0] == 'portable':
  2677. break
  2678. line_no += 1
  2679. if state:
  2680. data[line_no] = 'portable=True\n'
  2681. # create the new defauults files
  2682. # create current_defaults.FlatConfig file if there is none
  2683. try:
  2684. f = open(current_data_path + '/current_defaults.FlatConfig')
  2685. f.close()
  2686. except IOError:
  2687. App.log.debug('Creating empty current_defaults.FlatConfig')
  2688. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2689. json.dump({}, f)
  2690. f.close()
  2691. # create factory_defaults.FlatConfig file if there is none
  2692. try:
  2693. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2694. f.close()
  2695. except IOError:
  2696. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2697. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2698. json.dump({}, f)
  2699. f.close()
  2700. try:
  2701. f = open(current_data_path + '/recent.json')
  2702. f.close()
  2703. except IOError:
  2704. App.log.debug('Creating empty recent.json')
  2705. f = open(current_data_path + '/recent.json', 'w')
  2706. json.dump([], f)
  2707. f.close()
  2708. try:
  2709. fp = open(current_data_path + '/recent_projects.json')
  2710. fp.close()
  2711. except IOError:
  2712. App.log.debug('Creating empty recent_projects.json')
  2713. fp = open(current_data_path + '/recent_projects.json', 'w')
  2714. json.dump([], fp)
  2715. fp.close()
  2716. # save the current defaults to the new defaults file
  2717. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2718. else:
  2719. data[line_no] = 'portable=False\n'
  2720. with open(config_file, 'w') as f:
  2721. f.writelines(data)
  2722. def on_register_files(self, obj_type=None):
  2723. """
  2724. Called whenever there is a need to register file extensions with FlatCAM.
  2725. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2726. :param obj_type: the type of object to be register for.
  2727. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2728. :return: None
  2729. """
  2730. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2731. new_reg_path = 'Software\\Classes\\'
  2732. # find if the current user is admin
  2733. try:
  2734. is_admin = os.getuid() == 0
  2735. except AttributeError:
  2736. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2737. if is_admin is True:
  2738. root_path = winreg.HKEY_LOCAL_MACHINE
  2739. else:
  2740. root_path = winreg.HKEY_CURRENT_USER
  2741. # create the keys
  2742. def set_reg(name, root_pth, new_reg_path, value):
  2743. try:
  2744. winreg.CreateKey(root_pth, new_reg_path)
  2745. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2746. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2747. return True
  2748. except WindowsError:
  2749. return False
  2750. # delete key in registry
  2751. def delete_reg(root_pth, reg_path, key_to_del):
  2752. key_to_del_path = reg_path + key_to_del
  2753. try:
  2754. winreg.DeleteKey(root_pth, key_to_del_path)
  2755. return True
  2756. except WindowsError:
  2757. return False
  2758. if obj_type is None or obj_type == 'excellon':
  2759. exc_list = \
  2760. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2761. exc_list = [x for x in exc_list if x != '']
  2762. # register all keys in the Preferences window
  2763. for ext in exc_list:
  2764. new_k = new_reg_path + '.%s' % ext
  2765. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2766. # and unregister those that are no longer in the Preferences windows but are in the file
  2767. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2768. if ext not in exc_list:
  2769. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2770. # now write the updated extensions to the self.defaults
  2771. # new_ext = ''
  2772. # for ext in exc_list:
  2773. # new_ext = new_ext + ext + ', '
  2774. # self.defaults["fa_excellon"] = new_ext
  2775. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2776. if obj_type is None or obj_type == 'gcode':
  2777. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2778. gco_list = [x for x in gco_list if x != '']
  2779. # register all keys in the Preferences window
  2780. for ext in gco_list:
  2781. new_k = new_reg_path + '.%s' % ext
  2782. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2783. # and unregister those that are no longer in the Preferences windows but are in the file
  2784. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2785. if ext not in gco_list:
  2786. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2787. # now write the updated extensions to the self.defaults
  2788. # new_ext = ''
  2789. # for ext in gco_list:
  2790. # new_ext = new_ext + ext + ', '
  2791. # self.defaults["fa_gcode"] = new_ext
  2792. self.inform.emit('[success] %s' %
  2793. _("Selected GCode file extensions registered with FlatCAM."))
  2794. if obj_type is None or obj_type == 'gerber':
  2795. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2796. grb_list = [x for x in grb_list if x != '']
  2797. # register all keys in the Preferences window
  2798. for ext in grb_list:
  2799. new_k = new_reg_path + '.%s' % ext
  2800. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2801. # and unregister those that are no longer in the Preferences windows but are in the file
  2802. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2803. if ext not in grb_list:
  2804. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2805. # now write the updated extensions to the self.defaults
  2806. # new_ext = ''
  2807. # for ext in grb_list:
  2808. # new_ext = new_ext + ext + ', '
  2809. # self.defaults["fa_gerber"] = new_ext
  2810. self.inform.emit('[success] %s' %
  2811. _("Selected Gerber file extensions registered with FlatCAM."))
  2812. def add_extension(self, ext_type):
  2813. """
  2814. Add a file extension to the list for a specific object
  2815. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2816. :return:
  2817. """
  2818. if ext_type == 'excellon':
  2819. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2820. if new_ext == '':
  2821. return
  2822. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2823. if new_ext in old_val:
  2824. return
  2825. old_val.append(new_ext)
  2826. old_val.sort()
  2827. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2828. if ext_type == 'gcode':
  2829. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2830. if new_ext == '':
  2831. return
  2832. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2833. if new_ext in old_val:
  2834. return
  2835. old_val.append(new_ext)
  2836. old_val.sort()
  2837. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2838. if ext_type == 'gerber':
  2839. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2840. if new_ext == '':
  2841. return
  2842. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2843. if new_ext in old_val:
  2844. return
  2845. old_val.append(new_ext)
  2846. old_val.sort()
  2847. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2848. if ext_type == 'keyword':
  2849. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2850. if new_kw == '':
  2851. return
  2852. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2853. if new_kw in old_val:
  2854. return
  2855. old_val.append(new_kw)
  2856. old_val.sort()
  2857. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2858. # update the self.myKeywords so the model is updated
  2859. self.autocomplete_kw_list = \
  2860. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2861. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2862. self.shell._edit.set_model_data(self.myKeywords)
  2863. def del_extension(self, ext_type):
  2864. """
  2865. Remove a file extension from the list for a specific object
  2866. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2867. :return:
  2868. """
  2869. if ext_type == 'excellon':
  2870. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2871. if new_ext == '':
  2872. return
  2873. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2874. if new_ext not in old_val:
  2875. return
  2876. old_val.remove(new_ext)
  2877. old_val.sort()
  2878. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2879. if ext_type == 'gcode':
  2880. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2881. if new_ext == '':
  2882. return
  2883. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2884. if new_ext not in old_val:
  2885. return
  2886. old_val.remove(new_ext)
  2887. old_val.sort()
  2888. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2889. if ext_type == 'gerber':
  2890. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2891. if new_ext == '':
  2892. return
  2893. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2894. if new_ext not in old_val:
  2895. return
  2896. old_val.remove(new_ext)
  2897. old_val.sort()
  2898. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2899. if ext_type == 'keyword':
  2900. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2901. if new_kw == '':
  2902. return
  2903. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2904. if new_kw not in old_val:
  2905. return
  2906. old_val.remove(new_kw)
  2907. old_val.sort()
  2908. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2909. # update the self.myKeywords so the model is updated
  2910. self.autocomplete_kw_list = \
  2911. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2912. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2913. self.shell._edit.set_model_data(self.myKeywords)
  2914. def restore_extensions(self, ext_type):
  2915. """
  2916. Restore all file extensions associations with FlatCAM, for a specific object
  2917. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2918. :return:
  2919. """
  2920. if ext_type == 'excellon':
  2921. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  2922. # for the ability to open Excellon files with .txt extension
  2923. new_exc_list = deepcopy(self.exc_list)
  2924. try:
  2925. new_exc_list.remove('txt')
  2926. except ValueError:
  2927. pass
  2928. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  2929. if ext_type == 'gcode':
  2930. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  2931. if ext_type == 'gerber':
  2932. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  2933. if ext_type == 'keyword':
  2934. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  2935. # update the self.myKeywords so the model is updated
  2936. self.autocomplete_kw_list = self.default_keywords
  2937. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2938. self.shell._edit.set_model_data(self.myKeywords)
  2939. def delete_all_extensions(self, ext_type):
  2940. """
  2941. Delete all file extensions associations with FlatCAM, for a specific object
  2942. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2943. :return:
  2944. """
  2945. if ext_type == 'excellon':
  2946. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  2947. if ext_type == 'gcode':
  2948. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  2949. if ext_type == 'gerber':
  2950. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  2951. if ext_type == 'keyword':
  2952. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  2953. # update the self.myKeywords so the model is updated
  2954. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  2955. self.shell._edit.set_model_data(self.myKeywords)
  2956. def on_edit_join(self, name=None):
  2957. """
  2958. Callback for Edit->Join. Joins the selected geometry objects into
  2959. a new one.
  2960. :return: None
  2961. """
  2962. self.defaults.report_usage("on_edit_join()")
  2963. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2964. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2965. geo_type_set = set()
  2966. objs = self.collection.get_selected()
  2967. if len(objs) < 2:
  2968. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2969. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2970. return 'fail'
  2971. for obj in objs:
  2972. geo_type_set.add(obj.multigeo)
  2973. # if len(geo_type_list) == 1 means that all list elements are the same
  2974. if len(geo_type_set) != 1:
  2975. self.inform.emit('[ERROR] %s' %
  2976. _("Failed join. The Geometry objects are of different types.\n"
  2977. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2978. "convert from one to another and retry joining \n"
  2979. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2980. "the result may not be what was expected. \n"
  2981. "Check the generated GCODE."))
  2982. return
  2983. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2984. if True in geo_type_set:
  2985. def initialize(geo_obj, app):
  2986. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  2987. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2988. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2989. for v in geo_obj.tools.values():
  2990. v['data']['name'] = obj_name_multi
  2991. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  2992. else:
  2993. def initialize(geo_obj, app):
  2994. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  2995. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2996. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2997. for v in geo_obj.tools.values():
  2998. v['data']['name'] = obj_name_single
  2999. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3000. self.should_we_save = True
  3001. def on_edit_join_exc(self):
  3002. """
  3003. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3004. a new Excellon.
  3005. :return: None
  3006. """
  3007. self.defaults.report_usage("on_edit_join_exc()")
  3008. objs = self.collection.get_selected()
  3009. for obj in objs:
  3010. if not isinstance(obj, ExcellonObject):
  3011. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3012. return
  3013. if len(objs) < 2:
  3014. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3015. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3016. return 'fail'
  3017. def initialize(exc_obj, app):
  3018. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3019. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3020. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3021. self.should_we_save = True
  3022. def on_edit_join_grb(self):
  3023. """
  3024. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3025. a new Gerber object.
  3026. :return: None
  3027. """
  3028. self.defaults.report_usage("on_edit_join_grb()")
  3029. objs = self.collection.get_selected()
  3030. for obj in objs:
  3031. if not isinstance(obj, GerberObject):
  3032. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3033. return
  3034. if len(objs) < 2:
  3035. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3036. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3037. return 'fail'
  3038. def initialize(grb_obj, app):
  3039. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3040. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3041. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3042. self.should_we_save = True
  3043. def on_convert_singlegeo_to_multigeo(self):
  3044. """
  3045. Called for converting a Geometry object from single-geo to multi-geo.
  3046. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3047. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3048. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3049. the solid-geometry of that tool.
  3050. :return: None
  3051. """
  3052. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3053. obj = self.collection.get_active()
  3054. if obj is None:
  3055. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3056. return
  3057. if not isinstance(obj, GeometryObject):
  3058. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3059. return
  3060. obj.multigeo = True
  3061. for tooluid, dict_value in obj.tools.items():
  3062. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3063. if not isinstance(obj.solid_geometry, list):
  3064. obj.solid_geometry = [obj.solid_geometry]
  3065. # obj.solid_geometry[:] = []
  3066. obj.plot()
  3067. self.should_we_save = True
  3068. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3069. def on_convert_multigeo_to_singlegeo(self):
  3070. """
  3071. Called for converting a Geometry object from multi-geo to single-geo.
  3072. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3073. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3074. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3075. the solid-geometry of that tool.
  3076. :return: None
  3077. """
  3078. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3079. obj = self.collection.get_active()
  3080. if obj is None:
  3081. self.inform.emit('[ERROR_NOTCL] %s' %
  3082. _("Failed. Select a Geometry Object and try again."))
  3083. return
  3084. if not isinstance(obj, GeometryObject):
  3085. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3086. (_("Expected a GeometryObject, got"), type(obj)))
  3087. return
  3088. obj.multigeo = False
  3089. total_solid_geometry = []
  3090. for tooluid, dict_value in obj.tools.items():
  3091. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3092. # clear the original geometry
  3093. dict_value['solid_geometry'][:] = []
  3094. obj.solid_geometry = deepcopy(total_solid_geometry)
  3095. obj.plot()
  3096. self.should_we_save = True
  3097. self.inform.emit('[success] %s' %
  3098. _("A Geometry object was converted to SingleGeo type."))
  3099. def on_defaults_dict_change(self, field):
  3100. """
  3101. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3102. Edit -> Preferences tab window.
  3103. :param field: the key of the self.defaults dictionary that was changed.
  3104. :return: None
  3105. """
  3106. self.preferencesUiManager.defaults_write_form_field(field=field)
  3107. if field == "units":
  3108. self.set_screen_units(self.defaults['units'])
  3109. def set_screen_units(self, units):
  3110. """
  3111. Set the FlatCAM units on the status bar.
  3112. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3113. :return: None
  3114. """
  3115. self.ui.units_label.setText("[" + units.lower() + "]")
  3116. def on_toggle_units_click(self):
  3117. try:
  3118. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3119. except (TypeError, AttributeError):
  3120. pass
  3121. if self.defaults["units"] == 'MM':
  3122. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3123. else:
  3124. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3125. self.on_toggle_units(no_pref=True)
  3126. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3127. lambda: self.on_toggle_units(no_pref=False))
  3128. def on_toggle_units(self, no_pref=False):
  3129. """
  3130. Callback for the Units radio-button change in the Preferences tab.
  3131. Changes the application's default units adn for the project too.
  3132. If changing the project's units, the change propagates to all of
  3133. the objects in the project.
  3134. :return: None
  3135. """
  3136. self.defaults.report_usage("on_toggle_units")
  3137. if self.toggle_units_ignore:
  3138. return
  3139. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3140. # If option is the same, then ignore
  3141. if new_units == self.defaults["units"].upper():
  3142. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3143. return
  3144. # Keys in self.defaults for which to scale their values
  3145. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3146. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "tools_iso_tool_vtipdia",
  3147. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3148. "gerber_editor_ma_high",
  3149. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3150. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3151. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3152. "excellon_feedrate_probe", "excellon_milling_dia",
  3153. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3154. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3155. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3156. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3157. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3158. "geometry_extracut_length", "geometry_z_pdepth",
  3159. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3160. 'cncjob_tooldia',
  3161. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3162. "tools_paintnewdia",
  3163. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3164. "tools_nccnewdia", "tools_ncc_offset_value",
  3165. "tools_2sided_drilldia",
  3166. "tools_film_boundary", "tools_film_scale_stroke",
  3167. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3168. "tools_cutout_depthperpass",
  3169. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3170. "tools_panelize_spacing_rows",
  3171. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3172. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3173. "tools_transform_buffer_dis",
  3174. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3175. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3176. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3177. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3178. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3179. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3180. "tools_cr_h2h_val", "tools_cr_dh_val",
  3181. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3182. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3183. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3184. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3185. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3186. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3187. "tools_copper_thieving_mask_clearance",
  3188. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3189. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3190. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3191. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3192. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3193. "tools_invert_margin",
  3194. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3195. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3196. def scale_defaults(sfactor):
  3197. for dim in dimensions:
  3198. if dim in [
  3199. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3200. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3201. 'tools_transform_mirror_point'
  3202. ]:
  3203. if self.defaults[dim] is None or self.defaults[dim] == '':
  3204. continue
  3205. try:
  3206. coordinates = self.defaults[dim].split(",")
  3207. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3208. coords_xy[0] *= sfactor
  3209. coords_xy[1] *= sfactor
  3210. self.defaults[dim] = "%.*f, %.*f" % (
  3211. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3212. except Exception as e:
  3213. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3214. elif dim in [
  3215. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3216. ]:
  3217. if self.defaults[dim] is None or self.defaults[dim] == '':
  3218. continue
  3219. try:
  3220. self.defaults[dim] = float(self.defaults[dim])
  3221. tools_diameters = [self.defaults[dim]]
  3222. except ValueError:
  3223. try:
  3224. tools_string = self.defaults[dim].split(",")
  3225. tools_diameters = [eval(a) for a in tools_string if a != '']
  3226. except Exception as e:
  3227. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3228. continue
  3229. self.defaults[dim] = ''
  3230. td_len = len(tools_diameters)
  3231. if td_len > 1:
  3232. for t in range(td_len):
  3233. tools_diameters[t] *= sfactor
  3234. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3235. else:
  3236. tools_diameters[0] *= sfactor
  3237. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3238. elif dim in ['global_gridx', 'global_gridy']:
  3239. # format the number of decimals to the one specified in self.decimals
  3240. try:
  3241. val = float(self.defaults[dim]) * sfactor
  3242. except Exception as e:
  3243. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3244. continue
  3245. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3246. else:
  3247. # the number of decimals for the rest is kept unchanged
  3248. if self.defaults[dim]:
  3249. try:
  3250. val = float(self.defaults[dim]) * sfactor
  3251. except Exception as e:
  3252. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3253. continue
  3254. self.defaults[dim] = val
  3255. # The scaling factor depending on choice of units.
  3256. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3257. # Changing project units. Warn user.
  3258. msgbox = QtWidgets.QMessageBox()
  3259. msgbox.setWindowTitle(_("Toggle Units"))
  3260. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3261. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3262. msgbox.setText(_("Changing the units of the project\n"
  3263. "will scale all objects.\n\n"
  3264. "Do you want to continue?"))
  3265. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3266. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3267. msgbox.setDefaultButton(bt_ok)
  3268. msgbox.exec_()
  3269. response = msgbox.clickedButton()
  3270. if response == bt_ok:
  3271. if no_pref is False:
  3272. self.preferencesUiManager.defaults_read_form()
  3273. scale_defaults(factor)
  3274. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3275. self.defaults["units"] = new_units
  3276. # update the defaults from form, some may assume that the conversion is enough and it's not
  3277. self.on_options_app2project()
  3278. # update the objects
  3279. for obj in self.collection.get_list():
  3280. obj.convert_units(new_units)
  3281. # make that the properties stored in the object are also updated
  3282. self.app_obj.object_changed.emit(obj)
  3283. # rebuild the object UI
  3284. obj.build_ui()
  3285. # change this only if the workspace is active
  3286. if self.defaults['global_workspace'] is True:
  3287. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3288. # adjust the grid values on the main toolbar
  3289. val_x = float(self.defaults['global_gridx']) * factor
  3290. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3291. current = self.collection.get_active()
  3292. if current is not None:
  3293. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3294. if not isinstance(current, GeometryObject):
  3295. current.to_form()
  3296. # replot all objects
  3297. self.plot_all()
  3298. # set the status labels to reflect the current FlatCAM units
  3299. self.set_screen_units(new_units)
  3300. # signal to the app that we changed the object properties and it should save the project
  3301. self.should_we_save = True
  3302. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3303. else:
  3304. # Undo toggling
  3305. self.toggle_units_ignore = True
  3306. if self.defaults['units'].upper() == 'MM':
  3307. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3308. else:
  3309. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3310. self.toggle_units_ignore = False
  3311. # store the grid values so they are not changed in the next step
  3312. val_x = float(self.defaults['global_gridx'])
  3313. val_y = float(self.defaults['global_gridy'])
  3314. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3315. self.preferencesUiManager.defaults_read_form()
  3316. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3317. # in self.defaults from the GUI elements but
  3318. # I don't want it for the grid values, so I update them here
  3319. self.defaults['global_gridx'] = val_x
  3320. self.defaults['global_gridy'] = val_y
  3321. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3322. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3323. def on_toggle_axis(self):
  3324. self.defaults.report_usage("on_toggle_axis()")
  3325. if self.toggle_axis is False:
  3326. if self.is_legacy is False:
  3327. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3328. parent=self.plotcanvas.view.scene)
  3329. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3330. parent=self.plotcanvas.view.scene)
  3331. else:
  3332. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3333. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3334. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3335. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3336. self.plotcanvas.canvas.draw()
  3337. self.inform.emit(_("Axis enabled."))
  3338. self.toggle_axis = True
  3339. else:
  3340. if self.is_legacy is False:
  3341. self.plotcanvas.v_line.parent = None
  3342. self.plotcanvas.h_line.parent = None
  3343. else:
  3344. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3345. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3346. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3347. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3348. self.plotcanvas.canvas.draw()
  3349. self.inform.emit(_("Axis disabled."))
  3350. self.toggle_axis = False
  3351. def on_toggle_hud(self):
  3352. new_state = False if self.plotcanvas.hud_enabled else True
  3353. self.plotcanvas.on_toggle_hud(state=new_state)
  3354. if new_state is False:
  3355. self.inform[str, bool].emit(_("HUD disabled."), False)
  3356. else:
  3357. self.inform[str, bool].emit(_("HUD enabled."), False)
  3358. def on_toggle_grid_lines(self):
  3359. self.defaults.report_usage("on_toggle_grd_lines()")
  3360. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3361. if tt_settings.contains("theme"):
  3362. theme = tt_settings.value('theme', type=str)
  3363. else:
  3364. theme = 'white'
  3365. if self.toggle_grid_lines is False:
  3366. if self.is_legacy is False:
  3367. if theme == 'white':
  3368. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3369. else:
  3370. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3371. else:
  3372. self.plotcanvas.axes.grid(True)
  3373. try:
  3374. self.plotcanvas.canvas.draw()
  3375. except IndexError:
  3376. pass
  3377. pass
  3378. self.inform.emit(_("Grid enabled."))
  3379. self.toggle_grid_lines = True
  3380. else:
  3381. if self.is_legacy is False:
  3382. if theme == 'white':
  3383. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3384. else:
  3385. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3386. else:
  3387. self.plotcanvas.axes.grid(False)
  3388. try:
  3389. self.plotcanvas.canvas.draw()
  3390. except IndexError:
  3391. pass
  3392. self.toggle_grid_lines = False
  3393. self.inform.emit(_("Grid disabled."))
  3394. if self.is_legacy is False:
  3395. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3396. # - perhaps is a bug in VisPy implementation
  3397. if self.grid_status():
  3398. self.app_cursor.enabled = False
  3399. self.app_cursor.enabled = True
  3400. else:
  3401. self.app_cursor.enabled = True
  3402. self.app_cursor.enabled = False
  3403. def on_tab_rmb_click(self, checked):
  3404. self.ui.notebook.set_detachable(val=checked)
  3405. self.defaults["global_tabs_detachable"] = checked
  3406. self.ui.plot_tab_area.set_detachable(val=checked)
  3407. self.defaults["global_tabs_detachable"] = checked
  3408. def on_tab_setup_context_menu(self):
  3409. initial_checked = self.defaults["global_tabs_detachable"]
  3410. action_name = str(_("Detachable Tabs"))
  3411. action = QtWidgets.QAction(self)
  3412. action.setCheckable(True)
  3413. action.setText(action_name)
  3414. action.setChecked(initial_checked)
  3415. self.ui.notebook.tabBar.addAction(action)
  3416. self.ui.plot_tab_area.tabBar.addAction(action)
  3417. try:
  3418. action.triggered.disconnect()
  3419. except TypeError:
  3420. pass
  3421. action.triggered.connect(self.on_tab_rmb_click)
  3422. def on_deselect_all(self):
  3423. self.collection.set_all_inactive()
  3424. self.delete_selection_shape()
  3425. def on_workspace_modified(self):
  3426. # self.save_defaults(silent=True)
  3427. self.plotcanvas.delete_workspace()
  3428. self.preferencesUiManager.defaults_read_form()
  3429. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3430. def on_workspace(self):
  3431. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3432. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3433. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3434. else:
  3435. self.plotcanvas.delete_workspace()
  3436. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3437. self.preferencesUiManager.defaults_read_form()
  3438. # self.save_defaults(silent=True)
  3439. def on_workspace_toggle(self):
  3440. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3441. try:
  3442. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3443. except TypeError:
  3444. pass
  3445. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3446. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3447. self.on_workspace()
  3448. def on_cursor_type(self, val):
  3449. """
  3450. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3451. :return: None
  3452. """
  3453. self.app_cursor.enabled = False
  3454. if val == 'small':
  3455. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3456. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3457. self.app_cursor = self.plotcanvas.new_cursor()
  3458. else:
  3459. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3460. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3461. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3462. if self.ui.grid_snap_btn.isChecked():
  3463. self.app_cursor.enabled = True
  3464. else:
  3465. self.app_cursor.enabled = False
  3466. def on_tool_add_keypress(self):
  3467. # ## Current application units in Upper Case
  3468. self.units = self.defaults['units'].upper()
  3469. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3470. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3471. if notebook_widget_name == 'selected_tab':
  3472. if self.collection.get_active().kind == 'geometry':
  3473. # Tool add works for Geometry only if Advanced is True in Preferences
  3474. if self.defaults["global_app_level"] == 'a':
  3475. tool_add_popup = FCInputDialog(title="New Tool ...",
  3476. text='Enter a Tool Diameter:',
  3477. min=0.0000, max=99.9999, decimals=4)
  3478. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3479. val, ok = tool_add_popup.get_value()
  3480. if ok:
  3481. if float(val) == 0:
  3482. self.inform.emit('[WARNING_NOTCL] %s' %
  3483. _("Please enter a tool diameter with non-zero value, in Float format."))
  3484. return
  3485. self.collection.get_active().on_tool_add(dia=float(val))
  3486. else:
  3487. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3488. else:
  3489. msgbox = QtWidgets.QMessageBox()
  3490. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3491. "Go to Preferences -> General - Show Advanced Options."))
  3492. msgbox.setWindowTitle("Tool adding ...")
  3493. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3494. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3495. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3496. msgbox.setDefaultButton(bt_ok)
  3497. msgbox.exec_()
  3498. # work only if the notebook tab on focus is the Tools_Tab
  3499. if notebook_widget_name == 'tool_tab':
  3500. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3501. # and only if the tool is NCC Tool
  3502. if tool_widget == self.ncclear_tool.toolName:
  3503. self.ncclear_tool.on_add_tool_by_key()
  3504. # and only if the tool is Paint Area Tool
  3505. elif tool_widget == self.paint_tool.toolName:
  3506. self.paint_tool.on_add_tool_by_key()
  3507. # and only if the tool is Solder Paste Dispensing Tool
  3508. elif tool_widget == self.paste_tool.toolName:
  3509. self.paste_tool.on_add_tool_by_key()
  3510. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3511. # See description below.
  3512. def on_delete_keypress(self):
  3513. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3514. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3515. if notebook_widget_name == 'selected_tab':
  3516. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3517. self.collection.get_active().on_tool_delete()
  3518. # work only if the notebook tab on focus is the Tools_Tab
  3519. elif notebook_widget_name == 'tool_tab':
  3520. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3521. # and only if the tool is NCC Tool
  3522. if tool_widget == self.ncclear_tool.toolName:
  3523. self.ncclear_tool.on_tool_delete()
  3524. # and only if the tool is Paint Tool
  3525. elif tool_widget == self.paint_tool.toolName:
  3526. self.paint_tool.on_tool_delete()
  3527. # and only if the tool is Solder Paste Dispensing Tool
  3528. elif tool_widget == self.paste_tool.toolName:
  3529. self.paste_tool.on_tool_delete()
  3530. else:
  3531. self.on_delete()
  3532. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3533. # some screens you have to be careful where you hover with your mouse.
  3534. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3535. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3536. # Complicated, I know :)
  3537. def on_delete(self, force_deletion=False):
  3538. """
  3539. Delete the currently selected FlatCAMObjs.
  3540. :param force_deletion: used by Tcl command
  3541. :return: None
  3542. """
  3543. self.defaults.report_usage("on_delete()")
  3544. response = None
  3545. bt_ok = None
  3546. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3547. # a geometry object before we update it.
  3548. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3549. and self.grb_editor.editor_active is False:
  3550. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3551. msgbox = QtWidgets.QMessageBox()
  3552. msgbox.setWindowTitle(_("Delete objects"))
  3553. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3554. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3555. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3556. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3557. "the selected objects?"))
  3558. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3559. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3560. msgbox.setDefaultButton(bt_ok)
  3561. msgbox.exec_()
  3562. response = msgbox.clickedButton()
  3563. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3564. response = bt_ok
  3565. if response == bt_ok:
  3566. if self.collection.get_active():
  3567. self.log.debug("App.on_delete()")
  3568. for obj_active in self.collection.get_selected():
  3569. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3570. if obj_active.kind == 'gerber':
  3571. for el in obj_active.mark_shapes:
  3572. obj_active.mark_shapes[el].clear(update=True)
  3573. obj_active.mark_shapes[el].enabled = False
  3574. # obj_active.mark_shapes[el] = None
  3575. del el
  3576. elif isinstance(obj_active, CNCJobObject):
  3577. try:
  3578. obj_active.text_col.enabled = False
  3579. del obj_active.text_col
  3580. obj_active.annotation.clear(update=True)
  3581. del obj_active.annotation
  3582. except AttributeError as e:
  3583. log.debug(
  3584. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3585. )
  3586. while self.collection.get_selected():
  3587. self.delete_first_selected()
  3588. # make sure that the selection shape is deleted, too
  3589. self.delete_selection_shape()
  3590. # if there are no longer objects delete also the exclusion areas shapes
  3591. if not self.collection.get_list():
  3592. self.exc_areas.clear_shapes()
  3593. self.inform.emit('%s...' % _("Object(s) deleted"))
  3594. else:
  3595. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3596. else:
  3597. self.inform.emit(_("Save the work in Editor and try again ..."))
  3598. def delete_first_selected(self):
  3599. # Keep this for later
  3600. try:
  3601. sel_obj = self.collection.get_active()
  3602. name = sel_obj.options["name"]
  3603. isPlotted = sel_obj.options["plot"]
  3604. except AttributeError:
  3605. self.log.debug("Nothing selected for deletion")
  3606. return
  3607. if self.is_legacy is True:
  3608. # Remove plot only if the object was plotted otherwise delaxes will fail
  3609. if isPlotted:
  3610. try:
  3611. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3612. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3613. except Exception as e:
  3614. log.debug("App.delete_first_selected() --> %s" % str(e))
  3615. self.plotcanvas.auto_adjust_axes()
  3616. # Remove from dictionary
  3617. self.collection.delete_active()
  3618. # Clear form
  3619. self.setup_component_editor()
  3620. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3621. def on_set_origin(self):
  3622. """
  3623. Set the origin to the left mouse click position
  3624. :return: None
  3625. """
  3626. # display the message for the user
  3627. # and ask him to click on the desired position
  3628. self.defaults.report_usage("on_set_origin()")
  3629. def origin_replot():
  3630. def worker_task():
  3631. with self.proc_container.new('%s...' % _("Plotting")):
  3632. for obj in self.collection.get_list():
  3633. obj.plot()
  3634. self.plotcanvas.fit_view()
  3635. if self.is_legacy:
  3636. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3637. else:
  3638. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3639. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3640. self.inform.emit(_('Click to set the origin ...'))
  3641. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3642. # first disconnect it as it may have been used by something else
  3643. try:
  3644. self.replot_signal.disconnect()
  3645. except TypeError:
  3646. pass
  3647. self.replot_signal[list].connect(origin_replot)
  3648. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3649. """
  3650. :param event:
  3651. :param location:
  3652. :param noplot:
  3653. :param use_thread:
  3654. :return:
  3655. """
  3656. noplot_sig = noplot
  3657. def worker_task():
  3658. with self.proc_container.new(_("Setting Origin...")):
  3659. obj_list = self.collection.get_list()
  3660. for obj in obj_list:
  3661. obj.offset((x, y))
  3662. self.app_obj.object_changed.emit(obj)
  3663. # Update the object bounding box options
  3664. a, b, c, d = obj.bounds()
  3665. obj.options['xmin'] = a
  3666. obj.options['ymin'] = b
  3667. obj.options['xmax'] = c
  3668. obj.options['ymax'] = d
  3669. self.inform.emit('[success] %s...' % _('Origin set'))
  3670. for obj in obj_list:
  3671. out_name = obj.options["name"]
  3672. if obj.kind == 'gerber':
  3673. obj.source_file = self.export_gerber(
  3674. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3675. elif obj.kind == 'excellon':
  3676. obj.source_file = self.export_excellon(
  3677. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3678. if noplot_sig is False:
  3679. self.replot_signal.emit([])
  3680. if location is not None:
  3681. if len(location) != 2:
  3682. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3683. return 'fail'
  3684. x, y = location
  3685. if use_thread is True:
  3686. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3687. else:
  3688. worker_task()
  3689. self.should_we_save = True
  3690. return
  3691. if event is not None and event.button == 1:
  3692. if self.is_legacy is False:
  3693. event_pos = event.pos
  3694. else:
  3695. event_pos = (event.xdata, event.ydata)
  3696. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3697. if self.grid_status():
  3698. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3699. else:
  3700. pos = pos_canvas
  3701. x = 0 - pos[0]
  3702. y = 0 - pos[1]
  3703. if use_thread is True:
  3704. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3705. else:
  3706. worker_task()
  3707. self.should_we_save = True
  3708. def on_move2origin(self, use_thread=True):
  3709. """
  3710. Move selected objects to origin.
  3711. :param use_thread: Control if to use threaded operation. Boolean.
  3712. :return:
  3713. """
  3714. def worker_task():
  3715. with self.proc_container.new(_("Moving to Origin...")):
  3716. obj_list = self.collection.get_selected()
  3717. if not obj_list:
  3718. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3719. return
  3720. xminlist = []
  3721. yminlist = []
  3722. # first get a bounding box to fit all
  3723. for obj in obj_list:
  3724. xmin, ymin, xmax, ymax = obj.bounds()
  3725. xminlist.append(xmin)
  3726. yminlist.append(ymin)
  3727. # get the minimum x,y for all objects selected
  3728. x = min(xminlist)
  3729. y = min(yminlist)
  3730. for obj in obj_list:
  3731. obj.offset((-x, -y))
  3732. self.app_obj.object_changed.emit(obj)
  3733. # Update the object bounding box options
  3734. a, b, c, d = obj.bounds()
  3735. obj.options['xmin'] = a
  3736. obj.options['ymin'] = b
  3737. obj.options['xmax'] = c
  3738. obj.options['ymax'] = d
  3739. for obj in obj_list:
  3740. obj.plot()
  3741. for obj in obj_list:
  3742. out_name = obj.options["name"]
  3743. if obj.kind == 'gerber':
  3744. obj.source_file = self.export_gerber(
  3745. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3746. elif obj.kind == 'excellon':
  3747. obj.source_file = self.export_excellon(
  3748. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3749. self.inform.emit('[success] %s...' % _('Origin set'))
  3750. if use_thread is True:
  3751. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3752. else:
  3753. worker_task()
  3754. self.should_we_save = True
  3755. def on_jump_to(self, custom_location=None, fit_center=True):
  3756. """
  3757. Jump to a location by setting the mouse cursor location.
  3758. :param custom_location: Jump to a specified point. (x, y) tuple.
  3759. :param fit_center: If to fit view. Boolean.
  3760. :return:
  3761. """
  3762. self.defaults.report_usage("on_jump_to()")
  3763. if not custom_location:
  3764. dia_box_location = None
  3765. try:
  3766. dia_box_location = eval(self.clipboard.text())
  3767. except Exception:
  3768. pass
  3769. if type(dia_box_location) == tuple:
  3770. dia_box_location = str(dia_box_location)
  3771. else:
  3772. dia_box_location = None
  3773. # dia_box = Dialog_box(title=_("Jump to ..."),
  3774. # label=_("Enter the coordinates in format X,Y:"),
  3775. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3776. # initial_text=dia_box_location)
  3777. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3778. label=_("Enter the coordinates in format X,Y:"),
  3779. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3780. initial_text=dia_box_location,
  3781. reference=self.defaults['global_jump_ref'])
  3782. if dia_box.ok is True:
  3783. try:
  3784. location = eval(dia_box.location)
  3785. if not isinstance(location, tuple):
  3786. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3787. return
  3788. if dia_box.reference == 'rel':
  3789. rel_x = self.mouse[0] + location[0]
  3790. rel_y = self.mouse[1] + location[1]
  3791. location = (rel_x, rel_y)
  3792. self.defaults['global_jump_ref'] = dia_box.reference
  3793. except Exception:
  3794. return
  3795. else:
  3796. return
  3797. else:
  3798. location = custom_location
  3799. self.jump_signal.emit(location)
  3800. if fit_center:
  3801. self.plotcanvas.fit_center(loc=location)
  3802. cursor = QtGui.QCursor()
  3803. if self.is_legacy is False:
  3804. # I don't know where those differences come from but they are constant for the current
  3805. # execution of the application and they are multiples of a value around 0.0263mm.
  3806. # In a random way sometimes they are more sometimes they are less
  3807. # if units == 'MM':
  3808. # cal_factor = 0.0263
  3809. # else:
  3810. # cal_factor = 0.0263 / 25.4
  3811. cal_location = (location[0], location[1])
  3812. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3813. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3814. j_pos = (
  3815. int(canvas_origin.x() + round(jump_loc[0])),
  3816. int(canvas_origin.y() + round(jump_loc[1]))
  3817. )
  3818. cursor.setPos(j_pos[0], j_pos[1])
  3819. else:
  3820. # find the canvas origin which is in the top left corner
  3821. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3822. # determine the coordinates for the lowest left point of the canvas
  3823. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3824. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3825. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3826. # canvas) and the point (width, height) is in the top-right location
  3827. loc = self.plotcanvas.axes.transData.transform_point(location)
  3828. j_pos = (
  3829. int(x0 + loc[0]),
  3830. int(y0 - loc[1])
  3831. )
  3832. cursor.setPos(j_pos[0], j_pos[1])
  3833. self.plotcanvas.mouse = [location[0], location[1]]
  3834. if self.defaults["global_cursor_color_enabled"] is True:
  3835. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3836. else:
  3837. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3838. if self.grid_status():
  3839. # Update cursor
  3840. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3841. symbol='++', edge_color=self.cursor_color_3D,
  3842. edge_width=self.defaults["global_cursor_width"],
  3843. size=self.defaults["global_cursor_size"])
  3844. # Set the relative position label
  3845. dx = location[0] - float(self.rel_point1[0])
  3846. dy = location[1] - float(self.rel_point1[1])
  3847. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3848. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3849. # # Set the position label
  3850. #
  3851. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3852. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3853. units = self.defaults["units"].lower()
  3854. self.plotcanvas.text_hud.text = \
  3855. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3856. dx, units, dy, units, location[0], units, location[1], units)
  3857. self.inform.emit('[success] %s' % _("Done."))
  3858. return location
  3859. def on_locate(self, obj, fit_center=True):
  3860. """
  3861. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3862. :param obj: The object on which to locate certain points
  3863. :param fit_center: If to fit view. Boolean.
  3864. :return: A point location. (x, y) tuple.
  3865. """
  3866. self.defaults.report_usage("on_locate()")
  3867. if obj is None:
  3868. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3869. return 'fail'
  3870. class DialogBoxChoice(QtWidgets.QDialog):
  3871. def __init__(self, title=None, icon=None, choice='bl'):
  3872. """
  3873. :param title: string with the window title
  3874. """
  3875. super(DialogBoxChoice, self).__init__()
  3876. self.ok = False
  3877. self.setWindowIcon(icon)
  3878. self.setWindowTitle(str(title))
  3879. self.form = QtWidgets.QFormLayout(self)
  3880. self.ref_radio = RadioSet([
  3881. {"label": _("Bottom-Left"), "value": "bl"},
  3882. {"label": _("Top-Left"), "value": "tl"},
  3883. {"label": _("Bottom-Right"), "value": "br"},
  3884. {"label": _("Top-Right"), "value": "tr"},
  3885. {"label": _("Center"), "value": "c"}
  3886. ], orientation='vertical', stretch=False)
  3887. self.ref_radio.set_value(choice)
  3888. self.form.addRow(self.ref_radio)
  3889. self.button_box = QtWidgets.QDialogButtonBox(
  3890. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3891. Qt.Horizontal, parent=self)
  3892. self.form.addRow(self.button_box)
  3893. self.button_box.accepted.connect(self.accept)
  3894. self.button_box.rejected.connect(self.reject)
  3895. if self.exec_() == QtWidgets.QDialog.Accepted:
  3896. self.ok = True
  3897. self.location_point = self.ref_radio.get_value()
  3898. else:
  3899. self.ok = False
  3900. self.location_point = None
  3901. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3902. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3903. choice=self.defaults['global_locate_pt'])
  3904. if dia_box.ok is True:
  3905. try:
  3906. location_point = dia_box.location_point
  3907. self.defaults['global_locate_pt'] = dia_box.location_point
  3908. except Exception:
  3909. return
  3910. else:
  3911. return
  3912. loc_b = obj.bounds()
  3913. if location_point == 'bl':
  3914. location = (loc_b[0], loc_b[1])
  3915. elif location_point == 'tl':
  3916. location = (loc_b[0], loc_b[3])
  3917. elif location_point == 'br':
  3918. location = (loc_b[2], loc_b[1])
  3919. elif location_point == 'tr':
  3920. location = (loc_b[2], loc_b[3])
  3921. else:
  3922. # center
  3923. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3924. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3925. location = (cx, cy)
  3926. self.locate_signal.emit(location, location_point)
  3927. if fit_center:
  3928. self.plotcanvas.fit_center(loc=location)
  3929. cursor = QtGui.QCursor()
  3930. if self.is_legacy is False:
  3931. # I don't know where those differences come from but they are constant for the current
  3932. # execution of the application and they are multiples of a value around 0.0263mm.
  3933. # In a random way sometimes they are more sometimes they are less
  3934. # if units == 'MM':
  3935. # cal_factor = 0.0263
  3936. # else:
  3937. # cal_factor = 0.0263 / 25.4
  3938. cal_location = (location[0], location[1])
  3939. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3940. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3941. j_pos = (
  3942. int(canvas_origin.x() + round(jump_loc[0])),
  3943. int(canvas_origin.y() + round(jump_loc[1]))
  3944. )
  3945. cursor.setPos(j_pos[0], j_pos[1])
  3946. else:
  3947. # find the canvas origin which is in the top left corner
  3948. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3949. # determine the coordinates for the lowest left point of the canvas
  3950. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3951. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3952. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3953. # canvas) and the point (width, height) is in the top-right location
  3954. loc = self.plotcanvas.axes.transData.transform_point(location)
  3955. j_pos = (
  3956. int(x0 + loc[0]),
  3957. int(y0 - loc[1])
  3958. )
  3959. cursor.setPos(j_pos[0], j_pos[1])
  3960. self.plotcanvas.mouse = [location[0], location[1]]
  3961. if self.defaults["global_cursor_color_enabled"] is True:
  3962. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3963. else:
  3964. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3965. if self.grid_status():
  3966. # Update cursor
  3967. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3968. symbol='++', edge_color=self.cursor_color_3D,
  3969. edge_width=self.defaults["global_cursor_width"],
  3970. size=self.defaults["global_cursor_size"])
  3971. # Set the relative position label
  3972. self.dx = location[0] - float(self.rel_point1[0])
  3973. self.dy = location[1] - float(self.rel_point1[1])
  3974. # Set the position label
  3975. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3976. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3977. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3978. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  3979. units = self.defaults["units"].lower()
  3980. self.plotcanvas.text_hud.text = \
  3981. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3982. self.dx, units, self.dy, units, location[0], units, location[1], units)
  3983. self.inform.emit('[success] %s' % _("Done."))
  3984. return location
  3985. def on_copy_command(self):
  3986. """
  3987. Will copy a selection of objects, creating new objects.
  3988. :return:
  3989. """
  3990. self.defaults.report_usage("on_copy_command()")
  3991. def initialize(obj_init, app):
  3992. """
  3993. :param obj_init: the new object
  3994. :type obj_init: class
  3995. :param app: An instance of the App class
  3996. :type app: App
  3997. :return: None
  3998. :rtype:
  3999. """
  4000. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4001. try:
  4002. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4003. except AttributeError:
  4004. pass
  4005. try:
  4006. obj_init.apertures = deepcopy(obj.apertures)
  4007. except AttributeError:
  4008. pass
  4009. try:
  4010. if obj.tools:
  4011. obj_init.tools = deepcopy(obj.tools)
  4012. except Exception as err:
  4013. log.debug("App.on_copy_command() --> %s" % str(err))
  4014. try:
  4015. obj_init.source_file = deepcopy(obj.source_file)
  4016. except (AttributeError, TypeError):
  4017. pass
  4018. def initialize_excellon(obj_init, app):
  4019. obj_init.source_file = deepcopy(obj.source_file)
  4020. obj_init.tools = deepcopy(obj.tools)
  4021. # drills are offset, so they need to be deep copied
  4022. obj_init.drills = deepcopy(obj.drills)
  4023. # slots are offset, so they need to be deep copied
  4024. obj_init.slots = deepcopy(obj.slots)
  4025. obj_init.create_geometry()
  4026. def initialize_script(obj_init, app_obj):
  4027. obj_init.source_file = deepcopy(obj.source_file)
  4028. def initialize_document(obj_init, app_obj):
  4029. obj_init.source_file = deepcopy(obj.source_file)
  4030. for obj in self.collection.get_selected():
  4031. obj_name = obj.options["name"]
  4032. try:
  4033. if isinstance(obj, ExcellonObject):
  4034. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4035. elif isinstance(obj, GerberObject):
  4036. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4037. elif isinstance(obj, GeometryObject):
  4038. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4039. elif isinstance(obj, ScriptObject):
  4040. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4041. elif isinstance(obj, DocumentObject):
  4042. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4043. except Exception as e:
  4044. return "Operation failed: %s" % str(e)
  4045. def on_copy_object2(self, custom_name):
  4046. def initialize_geometry(obj_init, app):
  4047. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4048. try:
  4049. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4050. except AttributeError:
  4051. pass
  4052. try:
  4053. obj_init.apertures = deepcopy(obj.apertures)
  4054. except AttributeError:
  4055. pass
  4056. try:
  4057. if obj.tools:
  4058. obj_init.tools = deepcopy(obj.tools)
  4059. except Exception as ee:
  4060. log.debug("on_copy_object2() --> %s" % str(ee))
  4061. def initialize_gerber(obj_init, app):
  4062. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4063. obj_init.apertures = deepcopy(obj.apertures)
  4064. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4065. def initialize_excellon(obj_init, app):
  4066. obj_init.tools = deepcopy(obj.tools)
  4067. # drills are offset, so they need to be deep copied
  4068. obj_init.drills = deepcopy(obj.drills)
  4069. # slots are offset, so they need to be deep copied
  4070. obj_init.slots = deepcopy(obj.slots)
  4071. obj_init.create_geometry()
  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("excellon", str(obj_name) + custom_name, initialize_excellon)
  4077. elif isinstance(obj, GerberObject):
  4078. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4079. elif isinstance(obj, GeometryObject):
  4080. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4081. except Exception as er:
  4082. return "Operation failed: %s" % str(er)
  4083. def on_rename_object(self, text):
  4084. """
  4085. Will rename an object.
  4086. :param text: New name for the object.
  4087. :return:
  4088. """
  4089. self.defaults.report_usage("on_rename_object()")
  4090. named_obj = self.collection.get_active()
  4091. for obj in named_obj:
  4092. if obj is list:
  4093. self.on_rename_object(text)
  4094. else:
  4095. try:
  4096. obj.options['name'] = text
  4097. except Exception as e:
  4098. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4099. def convert_any2geo(self):
  4100. """
  4101. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4102. :return:
  4103. """
  4104. self.defaults.report_usage("convert_any2geo()")
  4105. def initialize(obj_init, app):
  4106. obj_init.solid_geometry = obj.solid_geometry
  4107. try:
  4108. obj_init.follow_geometry = obj.follow_geometry
  4109. except AttributeError:
  4110. pass
  4111. try:
  4112. obj_init.apertures = obj.apertures
  4113. except AttributeError:
  4114. pass
  4115. try:
  4116. if obj.tools:
  4117. obj_init.tools = obj.tools
  4118. except AttributeError:
  4119. pass
  4120. def initialize_excellon(obj_init, app):
  4121. # objs = self.collection.get_selected()
  4122. # GeometryObject.merge(objs, obj)
  4123. solid_geo = []
  4124. for tool in obj.tools:
  4125. for geo in obj.tools[tool]['solid_geometry']:
  4126. solid_geo.append(geo)
  4127. obj_init.solid_geometry = deepcopy(solid_geo)
  4128. if not self.collection.get_selected():
  4129. log.warning("App.convert_any2geo --> No object selected")
  4130. self.inform.emit('[WARNING_NOTCL] %s' %
  4131. _("No object is selected. Select an object and try again."))
  4132. return
  4133. for obj in self.collection.get_selected():
  4134. obj_name = obj.options["name"]
  4135. try:
  4136. if isinstance(obj, ExcellonObject):
  4137. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4138. else:
  4139. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4140. except Exception as e:
  4141. return "Operation failed: %s" % str(e)
  4142. def convert_any2gerber(self):
  4143. """
  4144. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4145. :return:
  4146. """
  4147. self.defaults.report_usage("convert_any2gerber()")
  4148. def initialize_geometry(obj_init, app):
  4149. apertures = {}
  4150. apid = 0
  4151. apertures[str(apid)] = {}
  4152. apertures[str(apid)]['geometry'] = []
  4153. for obj_orig in obj.solid_geometry:
  4154. new_elem = {}
  4155. new_elem['solid'] = obj_orig
  4156. try:
  4157. new_elem['follow'] = obj_orig.exterior
  4158. except AttributeError:
  4159. pass
  4160. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4161. apertures[str(apid)]['size'] = 0.0
  4162. apertures[str(apid)]['type'] = 'C'
  4163. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4164. obj_init.apertures = deepcopy(apertures)
  4165. def initialize_excellon(obj_init, app):
  4166. apertures = {}
  4167. apid = 10
  4168. for tool in obj.tools:
  4169. apertures[str(apid)] = {}
  4170. apertures[str(apid)]['geometry'] = []
  4171. for geo in obj.tools[tool]['solid_geometry']:
  4172. new_el = {}
  4173. new_el['solid'] = geo
  4174. new_el['follow'] = geo.exterior
  4175. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4176. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4177. apertures[str(apid)]['type'] = 'C'
  4178. apid += 1
  4179. # create solid_geometry
  4180. solid_geometry = []
  4181. for apid in apertures:
  4182. for geo_el in apertures[apid]['geometry']:
  4183. solid_geometry.append(geo_el['solid'])
  4184. solid_geometry = MultiPolygon(solid_geometry)
  4185. solid_geometry = solid_geometry.buffer(0.0000001)
  4186. obj_init.solid_geometry = deepcopy(solid_geometry)
  4187. obj_init.apertures = deepcopy(apertures)
  4188. # clear the working objects (perhaps not necessary due of Python GC)
  4189. apertures.clear()
  4190. if not self.collection.get_selected():
  4191. log.warning("App.convert_any2gerber --> No object selected")
  4192. self.inform.emit('[WARNING_NOTCL] %s' %
  4193. _("No object is selected. Select an object and try again."))
  4194. return
  4195. for obj in self.collection.get_selected():
  4196. obj_name = obj.options["name"]
  4197. try:
  4198. if isinstance(obj, ExcellonObject):
  4199. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4200. elif isinstance(obj, GeometryObject):
  4201. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4202. else:
  4203. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4204. except Exception as e:
  4205. return "Operation failed: %s" % str(e)
  4206. def abort_all_tasks(self):
  4207. """
  4208. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4209. on the first possible occasion.
  4210. :return:
  4211. """
  4212. if self.abort_flag is False:
  4213. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4214. self.abort_flag = True
  4215. self.cleanup.emit()
  4216. def app_is_idle(self):
  4217. if self.abort_flag:
  4218. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4219. self.abort_flag = False
  4220. def on_selectall(self):
  4221. """
  4222. Will draw a selection box shape around the selected objects.
  4223. :return:
  4224. """
  4225. self.defaults.report_usage("on_selectall()")
  4226. # delete the possible selection box around a possible selected object
  4227. self.delete_selection_shape()
  4228. for name in self.collection.get_names():
  4229. self.collection.set_active(name)
  4230. curr_sel_obj = self.collection.get_by_name(name)
  4231. # create the selection box around the selected object
  4232. if self.defaults['global_selection_shape'] is True:
  4233. self.draw_selection_shape(curr_sel_obj)
  4234. def on_preferences(self):
  4235. """
  4236. Adds the Preferences in a Tab in Plot Area
  4237. :return:
  4238. """
  4239. # add the tab if it was closed
  4240. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4241. # delete the absolute and relative position and messages in the infobar
  4242. self.ui.position_label.setText("")
  4243. # self.ui.rel_position_label.setText("")
  4244. # Switch plot_area to preferences page
  4245. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4246. # self.ui.show()
  4247. # detect changes in the preferences
  4248. for idx in range(self.ui.pref_tab_area.count()):
  4249. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4250. try:
  4251. try:
  4252. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4253. except (TypeError, AttributeError):
  4254. pass
  4255. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4256. except AttributeError:
  4257. pass
  4258. try:
  4259. try:
  4260. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4261. except (TypeError, AttributeError):
  4262. pass
  4263. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4264. except AttributeError:
  4265. pass
  4266. try:
  4267. try:
  4268. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4269. except (TypeError, AttributeError):
  4270. pass
  4271. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4272. except AttributeError:
  4273. pass
  4274. try:
  4275. try:
  4276. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4277. except (TypeError, AttributeError):
  4278. pass
  4279. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4280. except AttributeError:
  4281. pass
  4282. try:
  4283. try:
  4284. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4285. except (TypeError, AttributeError):
  4286. pass
  4287. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4288. except AttributeError:
  4289. pass
  4290. def on_tools_database(self, source='app'):
  4291. """
  4292. Adds the Tools Database in a Tab in Plot Area.
  4293. :return:
  4294. """
  4295. for idx in range(self.ui.plot_tab_area.count()):
  4296. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4297. # there can be only one instance of Tools Database at one time
  4298. return
  4299. if source == 'app':
  4300. self.tools_db_tab = ToolsDB2(
  4301. app=self,
  4302. parent=self.ui,
  4303. callback_on_edited=self.on_tools_db_edited,
  4304. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4305. )
  4306. elif source == 'ncc':
  4307. self.tools_db_tab = ToolsDB2(
  4308. app=self,
  4309. parent=self.ui,
  4310. callback_on_edited=self.on_tools_db_edited,
  4311. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4312. )
  4313. elif source == 'paint':
  4314. self.tools_db_tab = ToolsDB2(
  4315. app=self,
  4316. parent=self.ui,
  4317. callback_on_edited=self.on_tools_db_edited,
  4318. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4319. )
  4320. elif source == 'iso':
  4321. self.tools_db_tab = ToolsDB2(
  4322. app=self,
  4323. parent=self.ui,
  4324. callback_on_edited=self.on_tools_db_edited,
  4325. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4326. )
  4327. # add the tab if it was closed
  4328. try:
  4329. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4330. self.tools_db_tab.setObjectName("database_tab")
  4331. except Exception as e:
  4332. log.debug("App.on_tools_database() --> %s" % str(e))
  4333. return
  4334. # delete the absolute and relative position and messages in the infobar
  4335. self.ui.position_label.setText("")
  4336. # self.ui.rel_position_label.setText("")
  4337. # Switch plot_area to preferences page
  4338. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4339. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4340. self.tools_db_tab.ui_connect()
  4341. def on_tools_db_edited(self):
  4342. """
  4343. Executed whenever a tool is edited in Tools Database.
  4344. Will color the text of the Tools Database tab to Red color.
  4345. :return:
  4346. """
  4347. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4348. for idx in range(self.ui.plot_tab_area.count()):
  4349. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4350. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4351. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4352. self.tools_db_changed_flag = True
  4353. def on_geometry_tool_add_from_db_executed(self, tool):
  4354. """
  4355. Here add the tool from DB in the selected geometry object.
  4356. :return:
  4357. """
  4358. tool_from_db = deepcopy(tool)
  4359. obj = self.collection.get_active()
  4360. if isinstance(obj, GeometryObject):
  4361. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4362. # close the tab and delete it
  4363. for idx in range(self.ui.plot_tab_area.count()):
  4364. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4365. wdg = self.ui.plot_tab_area.widget(idx)
  4366. wdg.deleteLater()
  4367. self.ui.plot_tab_area.removeTab(idx)
  4368. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4369. else:
  4370. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4371. def on_plot_area_tab_closed(self, tab_obj_name):
  4372. """
  4373. Executed whenever a QTab is closed in the Plot Area.
  4374. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4375. :return:
  4376. """
  4377. if tab_obj_name == "preferences_tab":
  4378. self.preferencesUiManager.on_close_preferences_tab()
  4379. elif tab_obj_name == "database_tab":
  4380. # disconnect the signals from the table widget in tab
  4381. self.tools_db_tab.ui_disconnect()
  4382. if self.tools_db_changed_flag is True:
  4383. msgbox = QtWidgets.QMessageBox()
  4384. msgbox.setText(_("One or more Tools are edited.\n"
  4385. "Do you want to update the Tools Database?"))
  4386. msgbox.setWindowTitle(_("Save Tools Database"))
  4387. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4388. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4389. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4390. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4391. msgbox.setDefaultButton(bt_yes)
  4392. msgbox.exec_()
  4393. response = msgbox.clickedButton()
  4394. if response == bt_yes:
  4395. self.tools_db_tab.on_save_tools_db()
  4396. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4397. else:
  4398. self.tools_db_changed_flag = False
  4399. self.inform.emit('')
  4400. return
  4401. self.tools_db_tab.deleteLater()
  4402. elif tab_obj_name == "text_editor_tab":
  4403. self.toggle_codeeditor = False
  4404. elif tab_obj_name == "bookmarks_tab":
  4405. self.book_dialog_tab.rebuild_actions()
  4406. self.book_dialog_tab.deleteLater()
  4407. else:
  4408. return
  4409. # def on_plotarea_tab_closed(self, tab_idx):
  4410. # """
  4411. #
  4412. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4413. # :return:
  4414. # """
  4415. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4416. #
  4417. # if widget is not None:
  4418. # widget.deleteLater()
  4419. # self.ui.plot_tab_area.removeTab(tab_idx)
  4420. def on_flipy(self):
  4421. """
  4422. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4423. :return:
  4424. """
  4425. self.defaults.report_usage("on_flipy()")
  4426. obj_list = self.collection.get_selected()
  4427. xminlist = []
  4428. yminlist = []
  4429. xmaxlist = []
  4430. ymaxlist = []
  4431. if not obj_list:
  4432. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4433. else:
  4434. try:
  4435. # first get a bounding box to fit all
  4436. for obj in obj_list:
  4437. xmin, ymin, xmax, ymax = obj.bounds()
  4438. xminlist.append(xmin)
  4439. yminlist.append(ymin)
  4440. xmaxlist.append(xmax)
  4441. ymaxlist.append(ymax)
  4442. # get the minimum x,y and maximum x,y for all objects selected
  4443. xminimal = min(xminlist)
  4444. yminimal = min(yminlist)
  4445. xmaximal = max(xmaxlist)
  4446. ymaximal = max(ymaxlist)
  4447. px = 0.5 * (xminimal + xmaximal)
  4448. py = 0.5 * (yminimal + ymaximal)
  4449. # execute mirroring
  4450. for obj in obj_list:
  4451. obj.mirror('X', [px, py])
  4452. obj.plot()
  4453. self.app_obj.object_changed.emit(obj)
  4454. self.inform.emit('[success] %s' %
  4455. _("Flip on Y axis done."))
  4456. except Exception as e:
  4457. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4458. return
  4459. def on_flipx(self):
  4460. """
  4461. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4462. :return:
  4463. """
  4464. self.defaults.report_usage("on_flipx()")
  4465. obj_list = self.collection.get_selected()
  4466. xminlist = []
  4467. yminlist = []
  4468. xmaxlist = []
  4469. ymaxlist = []
  4470. if not obj_list:
  4471. self.inform.emit('[WARNING_NOTCL] %s' %
  4472. _("No object selected to Flip on X axis."))
  4473. else:
  4474. try:
  4475. # first get a bounding box to fit all
  4476. for obj in obj_list:
  4477. xmin, ymin, xmax, ymax = obj.bounds()
  4478. xminlist.append(xmin)
  4479. yminlist.append(ymin)
  4480. xmaxlist.append(xmax)
  4481. ymaxlist.append(ymax)
  4482. # get the minimum x,y and maximum x,y for all objects selected
  4483. xminimal = min(xminlist)
  4484. yminimal = min(yminlist)
  4485. xmaximal = max(xmaxlist)
  4486. ymaximal = max(ymaxlist)
  4487. px = 0.5 * (xminimal + xmaximal)
  4488. py = 0.5 * (yminimal + ymaximal)
  4489. # execute mirroring
  4490. for obj in obj_list:
  4491. obj.mirror('Y', [px, py])
  4492. obj.plot()
  4493. self.app_obj.object_changed.emit(obj)
  4494. self.inform.emit('[success] %s' %
  4495. _("Flip on X axis done."))
  4496. except Exception as e:
  4497. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4498. return
  4499. def on_rotate(self, silent=False, preset=None):
  4500. """
  4501. Executed when Options -> Rotate Selection menu entry is clicked.
  4502. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4503. :param preset: A value to be used as predefined angle for rotation.
  4504. :return:
  4505. """
  4506. self.defaults.report_usage("on_rotate()")
  4507. obj_list = self.collection.get_selected()
  4508. xminlist = []
  4509. yminlist = []
  4510. xmaxlist = []
  4511. ymaxlist = []
  4512. if not obj_list:
  4513. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4514. else:
  4515. if silent is False:
  4516. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4517. min=-360, max=360, decimals=4,
  4518. init_val=float(self.defaults['tools_transform_rotate']))
  4519. num, ok = rotatebox.get_value()
  4520. else:
  4521. num = preset
  4522. ok = True
  4523. if ok:
  4524. try:
  4525. # first get a bounding box to fit all
  4526. for obj in obj_list:
  4527. xmin, ymin, xmax, ymax = obj.bounds()
  4528. xminlist.append(xmin)
  4529. yminlist.append(ymin)
  4530. xmaxlist.append(xmax)
  4531. ymaxlist.append(ymax)
  4532. # get the minimum x,y and maximum x,y for all objects selected
  4533. xminimal = min(xminlist)
  4534. yminimal = min(yminlist)
  4535. xmaximal = max(xmaxlist)
  4536. ymaximal = max(ymaxlist)
  4537. px = 0.5 * (xminimal + xmaximal)
  4538. py = 0.5 * (yminimal + ymaximal)
  4539. for sel_obj in obj_list:
  4540. sel_obj.rotate(-float(num), point=(px, py))
  4541. sel_obj.plot()
  4542. self.app_obj.object_changed.emit(sel_obj)
  4543. self.inform.emit('[success] %s' % _("Rotation done."))
  4544. except Exception as e:
  4545. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4546. return
  4547. def on_skewx(self):
  4548. """
  4549. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4550. :return:
  4551. """
  4552. self.defaults.report_usage("on_skewx()")
  4553. obj_list = self.collection.get_selected()
  4554. xminlist = []
  4555. yminlist = []
  4556. if not obj_list:
  4557. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4558. else:
  4559. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4560. min=-360, max=360, decimals=4,
  4561. init_val=float(self.defaults['tools_transform_skew_x']))
  4562. num, ok = skewxbox.get_value()
  4563. if ok:
  4564. # first get a bounding box to fit all
  4565. for obj in obj_list:
  4566. xmin, ymin, xmax, ymax = obj.bounds()
  4567. xminlist.append(xmin)
  4568. yminlist.append(ymin)
  4569. # get the minimum x,y and maximum x,y for all objects selected
  4570. xminimal = min(xminlist)
  4571. yminimal = min(yminlist)
  4572. for obj in obj_list:
  4573. obj.skew(num, 0, point=(xminimal, yminimal))
  4574. obj.plot()
  4575. self.app_obj.object_changed.emit(obj)
  4576. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4577. def on_skewy(self):
  4578. """
  4579. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4580. :return:
  4581. """
  4582. self.defaults.report_usage("on_skewy()")
  4583. obj_list = self.collection.get_selected()
  4584. xminlist = []
  4585. yminlist = []
  4586. if not obj_list:
  4587. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4588. else:
  4589. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4590. min=-360, max=360, decimals=4,
  4591. init_val=float(self.defaults['tools_transform_skew_y']))
  4592. num, ok = skewybox.get_value()
  4593. if ok:
  4594. # first get a bounding box to fit all
  4595. for obj in obj_list:
  4596. xmin, ymin, xmax, ymax = obj.bounds()
  4597. xminlist.append(xmin)
  4598. yminlist.append(ymin)
  4599. # get the minimum x,y and maximum x,y for all objects selected
  4600. xminimal = min(xminlist)
  4601. yminimal = min(yminlist)
  4602. for obj in obj_list:
  4603. obj.skew(0, num, point=(xminimal, yminimal))
  4604. obj.plot()
  4605. self.app_obj.object_changed.emit(obj)
  4606. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4607. def on_plots_updated(self):
  4608. """
  4609. Callback used to report when the plots have changed.
  4610. Adjust axes and zooms to fit.
  4611. :return: None
  4612. """
  4613. if self.is_legacy is False:
  4614. self.plotcanvas.update()
  4615. else:
  4616. self.plotcanvas.auto_adjust_axes()
  4617. self.on_zoom_fit()
  4618. self.collection.update_view()
  4619. # self.inform.emit(_("Plots updated ..."))
  4620. def on_toolbar_replot(self):
  4621. """
  4622. Callback for toolbar button. Re-plots all objects.
  4623. :return: None
  4624. """
  4625. self.log.debug("on_toolbar_replot()")
  4626. try:
  4627. self.collection.get_active().read_form()
  4628. except AttributeError:
  4629. self.log.debug("on_toolbar_replot(): AttributeError")
  4630. pass
  4631. self.plot_all()
  4632. def grid_status(self):
  4633. return True if self.ui.grid_snap_btn.isChecked() else False
  4634. def populate_cmenu_grids(self):
  4635. units = self.defaults['units'].lower()
  4636. # for act in self.ui.cmenu_gridmenu.actions():
  4637. # act.triggered.disconnect()
  4638. self.ui.cmenu_gridmenu.clear()
  4639. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4640. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4641. _("Grid On/Off"))
  4642. grid_toggle.setCheckable(True)
  4643. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4644. self.ui.cmenu_gridmenu.addSeparator()
  4645. for grid in sorted_list:
  4646. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4647. "%s" % str(grid))
  4648. action.triggered.connect(self.set_grid)
  4649. self.ui.cmenu_gridmenu.addSeparator()
  4650. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4651. _("Add"))
  4652. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4653. _("Delete"))
  4654. grid_add.triggered.connect(self.on_grid_add)
  4655. grid_delete.triggered.connect(self.on_grid_delete)
  4656. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4657. def set_grid(self):
  4658. menu_action = self.sender()
  4659. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4660. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4661. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4662. def on_grid_add(self):
  4663. # ## Current application units in lower Case
  4664. units = self.defaults['units'].lower()
  4665. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4666. text=_('Enter a Grid Value:'),
  4667. min=0.0000, max=99.9999, decimals=4)
  4668. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4669. val, ok = grid_add_popup.get_value()
  4670. if ok:
  4671. if float(val) == 0:
  4672. self.inform.emit('[WARNING_NOTCL] %s' %
  4673. _("Please enter a grid value with non-zero value, in Float format."))
  4674. return
  4675. else:
  4676. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4677. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4678. self.inform.emit('[success] %s...' % _("New Grid added"))
  4679. else:
  4680. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4681. else:
  4682. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4683. def on_grid_delete(self):
  4684. # ## Current application units in lower Case
  4685. units = self.defaults['units'].lower()
  4686. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4687. text='Enter a Grid Value:',
  4688. min=0.0000, max=99.9999, decimals=4)
  4689. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4690. val, ok = grid_del_popup.get_value()
  4691. if ok:
  4692. if float(val) == 0:
  4693. self.inform.emit('[WARNING_NOTCL] %s' %
  4694. _("Please enter a grid value with non-zero value, in Float format."))
  4695. return
  4696. else:
  4697. try:
  4698. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4699. except ValueError:
  4700. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4701. return
  4702. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4703. else:
  4704. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4705. def on_shortcut_list(self):
  4706. self.defaults.report_usage("on_shortcut_list()")
  4707. # add the tab if it was closed
  4708. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4709. # delete the absolute and relative position and messages in the infobar
  4710. self.ui.position_label.setText("")
  4711. # self.ui.rel_position_label.setText("")
  4712. # Switch plot_area to preferences page
  4713. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4714. # self.ui.show()
  4715. def on_select_tab(self, name):
  4716. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4717. if self.ui.splitter.sizes()[0] == 0:
  4718. self.ui.splitter.setSizes([1, 1])
  4719. else:
  4720. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4721. self.ui.splitter.setSizes([0, 1])
  4722. if name == 'project':
  4723. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4724. elif name == 'selected':
  4725. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4726. elif name == 'tool':
  4727. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4728. def on_copy_name(self):
  4729. self.defaults.report_usage("on_copy_name()")
  4730. obj = self.collection.get_active()
  4731. try:
  4732. name = obj.options["name"]
  4733. except AttributeError:
  4734. log.debug("on_copy_name() --> No object selected to copy it's name")
  4735. self.inform.emit('[WARNING_NOTCL]%s' %
  4736. _(" No object selected to copy it's name"))
  4737. return
  4738. self.clipboard.setText(name)
  4739. self.inform.emit(_("Name copied on clipboard ..."))
  4740. def on_mouse_click_over_plot(self, event):
  4741. """
  4742. Default actions are:
  4743. :param event: Contains information about the event, like which button
  4744. was clicked, the pixel coordinates and the axes coordinates.
  4745. :return: None
  4746. """
  4747. self.pos = []
  4748. if self.is_legacy is False:
  4749. event_pos = event.pos
  4750. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4751. # # Set the mouse button for panning
  4752. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4753. else:
  4754. event_pos = (event.xdata, event.ydata)
  4755. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4756. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4757. # So it can receive key presses
  4758. self.plotcanvas.native.setFocus()
  4759. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4760. if self.grid_status():
  4761. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4762. else:
  4763. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4764. try:
  4765. if event.button == 1:
  4766. # Reset here the relative coordinates so there is a new reference on the click position
  4767. if self.rel_point1 is None:
  4768. self.rel_point1 = self.pos
  4769. else:
  4770. self.rel_point2 = copy(self.rel_point1)
  4771. self.rel_point1 = self.pos
  4772. self.on_mouse_move_over_plot(event, origin_click=True)
  4773. except Exception as e:
  4774. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4775. def on_mouse_double_click_over_plot(self, event):
  4776. if event.button == 1:
  4777. self.doubleclick = True
  4778. def on_mouse_move_over_plot(self, event, origin_click=None):
  4779. """
  4780. Callback for the mouse motion event over the plot.
  4781. :param event: Contains information about the event.
  4782. :param origin_click
  4783. :return: None
  4784. """
  4785. if self.is_legacy is False:
  4786. event_pos = event.pos
  4787. if self.defaults["global_pan_button"] == '2':
  4788. pan_button = 2
  4789. else:
  4790. pan_button = 3
  4791. self.event_is_dragging = event.is_dragging
  4792. else:
  4793. event_pos = (event.xdata, event.ydata)
  4794. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4795. if self.defaults["global_pan_button"] == '2':
  4796. pan_button = 3
  4797. else:
  4798. pan_button = 2
  4799. self.event_is_dragging = self.plotcanvas.is_dragging
  4800. # So it can receive key presses but not when the Tcl Shell is active
  4801. if not self.ui.shell_dock.isVisible():
  4802. if not self.plotcanvas.native.hasFocus():
  4803. self.plotcanvas.native.setFocus()
  4804. self.pos_jump = event_pos
  4805. self.ui.popMenu.mouse_is_panning = False
  4806. if origin_click is None:
  4807. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4808. if event.button == pan_button and self.event_is_dragging == 1:
  4809. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4810. if self.ui.popMenu.popup_active:
  4811. self.ui.popMenu.popup_active = False
  4812. return
  4813. self.ui.popMenu.mouse_is_panning = True
  4814. return
  4815. if self.rel_point1 is not None:
  4816. try: # May fail in case mouse not within axes
  4817. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4818. if pos_canvas[0] is None or pos_canvas[1] is None:
  4819. return
  4820. if self.grid_status():
  4821. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4822. # Update cursor
  4823. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4824. symbol='++', edge_color=self.cursor_color_3D,
  4825. edge_width=self.defaults["global_cursor_width"],
  4826. size=self.defaults["global_cursor_size"])
  4827. else:
  4828. pos = (pos_canvas[0], pos_canvas[1])
  4829. self.dx = pos[0] - float(self.rel_point1[0])
  4830. self.dy = pos[1] - float(self.rel_point1[1])
  4831. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4832. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4833. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4834. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4835. units = self.defaults["units"].lower()
  4836. self.plotcanvas.text_hud.text = \
  4837. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4838. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4839. self.mouse = [pos[0], pos[1]]
  4840. # if the mouse is moved and the LMB is clicked then the action is a selection
  4841. if self.event_is_dragging == 1 and event.button == 1:
  4842. self.delete_selection_shape()
  4843. if self.dx < 0:
  4844. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4845. face_color=self.defaults['global_alt_sel_fill'])
  4846. self.selection_type = False
  4847. elif self.dx >= 0:
  4848. self.draw_moving_selection_shape(self.pos, pos)
  4849. self.selection_type = True
  4850. else:
  4851. self.selection_type = None
  4852. else:
  4853. self.selection_type = None
  4854. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  4855. if self.defaults['global_hover']:
  4856. for obj in self.collection.get_list():
  4857. try:
  4858. # select the object(s) only if it is enabled (plotted)
  4859. if obj.options['plot']:
  4860. if obj not in self.collection.get_selected():
  4861. poly_obj = Polygon(
  4862. [(obj.options['xmin'], obj.options['ymin']),
  4863. (obj.options['xmax'], obj.options['ymin']),
  4864. (obj.options['xmax'], obj.options['ymax']),
  4865. (obj.options['xmin'], obj.options['ymax'])]
  4866. )
  4867. if Point(pos).within(poly_obj):
  4868. if obj.isHovering is False:
  4869. obj.isHovering = True
  4870. obj.notHovering = True
  4871. # create the selection box around the selected object
  4872. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4873. else:
  4874. if obj.notHovering is True:
  4875. obj.notHovering = False
  4876. obj.isHovering = False
  4877. self.delete_hover_shape()
  4878. except Exception:
  4879. # the Exception here will happen if we try to select on screen and we have an
  4880. # newly (and empty) just created Geometry or Excellon object that do not have the
  4881. # xmin, xmax, ymin, ymax options.
  4882. # In this case poly_obj creation (see above) will fail
  4883. pass
  4884. except Exception as e:
  4885. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4886. self.ui.position_label.setText("")
  4887. # self.ui.rel_position_label.setText("")
  4888. self.mouse = None
  4889. def on_mouse_click_release_over_plot(self, event):
  4890. """
  4891. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4892. and has been registered in ''self.__init__()''.
  4893. :param event: contains information about the event.
  4894. :return:
  4895. """
  4896. if self.is_legacy is False:
  4897. event_pos = event.pos
  4898. right_button = 2
  4899. else:
  4900. event_pos = (event.xdata, event.ydata)
  4901. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4902. right_button = 3
  4903. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4904. if self.grid_status():
  4905. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4906. else:
  4907. pos = (pos_canvas[0], pos_canvas[1])
  4908. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4909. # canvas menu
  4910. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  4911. self.ui.popMenu.mouse_is_panning = False
  4912. self.cursor = QtGui.QCursor()
  4913. self.populate_cmenu_grids()
  4914. self.ui.popMenu.popup(self.cursor.pos())
  4915. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4916. # selection and then select a type of selection ("enclosing" or "touching")
  4917. if event.button == 1: # left click
  4918. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4919. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4920. if modifiers == QtCore.Qt.ShiftModifier:
  4921. # do not auto open the Project Tab
  4922. self.click_noproject = True
  4923. self.clipboard.setText(
  4924. self.defaults["global_point_clipboard_format"] %
  4925. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  4926. )
  4927. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  4928. return
  4929. if self.doubleclick is True:
  4930. self.doubleclick = False
  4931. if self.collection.get_selected():
  4932. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4933. if self.ui.splitter.sizes()[0] == 0:
  4934. self.ui.splitter.setSizes([1, 1])
  4935. try:
  4936. # delete the selection shape(S) as it may be in the way
  4937. self.delete_selection_shape()
  4938. self.delete_hover_shape()
  4939. except Exception as e:
  4940. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  4941. return
  4942. else:
  4943. # WORKAROUND for LEGACY MODE
  4944. if self.is_legacy is True:
  4945. # if there is no move on canvas then we have no dragging selection
  4946. if self.dx == 0 or self.dy == 0:
  4947. self.selection_type = None
  4948. if self.selection_type is not None:
  4949. try:
  4950. self.selection_area_handler(self.pos, pos, self.selection_type)
  4951. self.selection_type = None
  4952. except Exception as e:
  4953. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  4954. return
  4955. else:
  4956. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4957. if key_modifier == QtCore.Qt.ShiftModifier:
  4958. mod_key = 'Shift'
  4959. elif key_modifier == QtCore.Qt.ControlModifier:
  4960. mod_key = 'Control'
  4961. else:
  4962. mod_key = None
  4963. try:
  4964. if self.command_active is None:
  4965. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4966. # deselect, and if it's not selected then it will be selected
  4967. # If there is no active command (self.command_active is None) then we check if we clicked
  4968. # on a object by checking the bounding limits against mouse click position
  4969. if mod_key == self.defaults["global_mselect_key"]:
  4970. self.select_objects(key='multisel')
  4971. else:
  4972. # If there is no active command (self.command_active is None) then we check if
  4973. # we clicked on a object by checking the bounding limits against mouse click position
  4974. self.select_objects()
  4975. self.delete_hover_shape()
  4976. except Exception as e:
  4977. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  4978. return
  4979. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4980. """
  4981. :param start_pos: mouse position when the selection LMB click was done
  4982. :param end_pos: mouse position when the left mouse button is released
  4983. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4984. :return:
  4985. """
  4986. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4987. # delete previous selection shape
  4988. self.delete_selection_shape()
  4989. # make all objects inactive
  4990. self.collection.set_all_inactive()
  4991. for obj in self.collection.get_list():
  4992. try:
  4993. # select the object(s) only if it is enabled (plotted)
  4994. if obj.options['plot']:
  4995. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4996. (obj.options['xmax'], obj.options['ymin']),
  4997. (obj.options['xmax'], obj.options['ymax']),
  4998. (obj.options['xmin'], obj.options['ymax'])])
  4999. if sel_type is True:
  5000. if poly_obj.within(poly_selection):
  5001. # create the selection box around the selected object
  5002. if self.defaults['global_selection_shape'] is True:
  5003. self.draw_selection_shape(obj)
  5004. self.collection.set_active(obj.options['name'])
  5005. else:
  5006. if poly_selection.intersects(poly_obj):
  5007. # create the selection box around the selected object
  5008. if self.defaults['global_selection_shape'] is True:
  5009. self.draw_selection_shape(obj)
  5010. self.collection.set_active(obj.options['name'])
  5011. obj.selection_shape_drawn = True
  5012. except Exception as e:
  5013. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5014. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5015. # In this case poly_obj creation (see above) will fail
  5016. log.debug("App.selection_area_handler() --> %s" % str(e))
  5017. def select_objects(self, key=None):
  5018. """
  5019. Will select objects clicked on canvas
  5020. :param key: for future use in cumulative selection
  5021. :return:
  5022. """
  5023. # list where we store the overlapped objects under our mouse left click position
  5024. if key is None:
  5025. self.objects_under_the_click_list = []
  5026. # Populate the list with the overlapped objects on the click position
  5027. curr_x, curr_y = self.pos
  5028. for obj in self.all_objects_list:
  5029. # ScriptObject and DocumentObject objects can't be selected
  5030. if obj.kind == 'script' or obj.kind == 'document':
  5031. continue
  5032. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5033. continue
  5034. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5035. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5036. if obj.options['name'] not in self.objects_under_the_click_list:
  5037. if obj.options['plot']:
  5038. # add objects to the objects_under_the_click list only if the object is plotted
  5039. # (active and not disabled)
  5040. self.objects_under_the_click_list.append(obj.options['name'])
  5041. try:
  5042. if self.objects_under_the_click_list:
  5043. curr_sel_obj = self.collection.get_active()
  5044. # case when there is only an object under the click and we toggle it
  5045. if len(self.objects_under_the_click_list) == 1:
  5046. if curr_sel_obj is None:
  5047. self.collection.set_active(self.objects_under_the_click_list[0])
  5048. curr_sel_obj = self.collection.get_active()
  5049. # create the selection box around the selected object
  5050. if self.defaults['global_selection_shape'] is True:
  5051. self.draw_selection_shape(curr_sel_obj)
  5052. curr_sel_obj.selection_shape_drawn = True
  5053. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5054. self.collection.on_objects_selection(False)
  5055. self.delete_selection_shape()
  5056. curr_sel_obj.selection_shape_drawn = False
  5057. self.collection.set_active(self.objects_under_the_click_list[0])
  5058. curr_sel_obj = self.collection.get_active()
  5059. # create the selection box around the selected object
  5060. if self.defaults['global_selection_shape'] is True:
  5061. self.draw_selection_shape(curr_sel_obj)
  5062. curr_sel_obj.selection_shape_drawn = True
  5063. self.selected_message(curr_sel_obj=curr_sel_obj)
  5064. elif curr_sel_obj.selection_shape_drawn is False:
  5065. if self.defaults['global_selection_shape'] is True:
  5066. self.draw_selection_shape(curr_sel_obj)
  5067. curr_sel_obj.selection_shape_drawn = True
  5068. else:
  5069. self.collection.on_objects_selection(False)
  5070. self.delete_selection_shape()
  5071. if self.call_source != 'app':
  5072. self.call_source = 'app'
  5073. self.selected_message(curr_sel_obj=curr_sel_obj)
  5074. else:
  5075. # If there is no selected object
  5076. # make active the first element of the overlapped objects list
  5077. if self.collection.get_active() is None:
  5078. self.collection.set_active(self.objects_under_the_click_list[0])
  5079. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5080. name_sel_obj = self.collection.get_active().options['name']
  5081. # In case that there is a selected object but it is not in the overlapped object list
  5082. # make that object inactive and activate the first element in the overlapped object list
  5083. if name_sel_obj not in self.objects_under_the_click_list:
  5084. self.collection.set_inactive(name_sel_obj)
  5085. name_sel_obj = self.objects_under_the_click_list[0]
  5086. self.collection.set_active(name_sel_obj)
  5087. else:
  5088. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5089. self.collection.set_all_inactive()
  5090. self.collection.set_active(
  5091. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5092. curr_sel_obj = self.collection.get_active()
  5093. # delete the possible selection box around a possible selected object
  5094. self.delete_selection_shape()
  5095. curr_sel_obj.selection_shape_drawn = False
  5096. # create the selection box around the selected object
  5097. if self.defaults['global_selection_shape'] is True:
  5098. self.draw_selection_shape(curr_sel_obj)
  5099. curr_sel_obj.selection_shape_drawn = True
  5100. self.selected_message(curr_sel_obj=curr_sel_obj)
  5101. else:
  5102. # deselect everything
  5103. self.collection.on_objects_selection(False)
  5104. # delete the possible selection box around a possible selected object
  5105. self.delete_selection_shape()
  5106. for o in self.collection.get_list():
  5107. o.selection_shape_drawn = False
  5108. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5109. # only when working on App
  5110. if self.call_source == 'app':
  5111. if self.click_noproject is False:
  5112. # if the Tool Tab is in focus don't change focus to Project Tab
  5113. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5114. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5115. else:
  5116. # restore auto open the Project Tab
  5117. self.click_noproject = False
  5118. # delete any text in the status bar, implicitly the last object name that was selected
  5119. # self.inform.emit("")
  5120. else:
  5121. self.call_source = 'app'
  5122. except Exception as e:
  5123. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5124. def selected_message(self, curr_sel_obj):
  5125. if curr_sel_obj:
  5126. if curr_sel_obj.kind == 'gerber':
  5127. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5128. color='green',
  5129. name=str(curr_sel_obj.options['name']),
  5130. tx=_("selected"))
  5131. )
  5132. elif curr_sel_obj.kind == 'excellon':
  5133. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5134. color='brown',
  5135. name=str(curr_sel_obj.options['name']),
  5136. tx=_("selected"))
  5137. )
  5138. elif curr_sel_obj.kind == 'cncjob':
  5139. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5140. color='blue',
  5141. name=str(curr_sel_obj.options['name']),
  5142. tx=_("selected"))
  5143. )
  5144. elif curr_sel_obj.kind == 'geometry':
  5145. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5146. color='red',
  5147. name=str(curr_sel_obj.options['name']),
  5148. tx=_("selected"))
  5149. )
  5150. def delete_hover_shape(self):
  5151. self.hover_shapes.clear()
  5152. self.hover_shapes.redraw()
  5153. def draw_hover_shape(self, sel_obj, color=None):
  5154. """
  5155. :param sel_obj: The object for which the hover shape must be drawn
  5156. :param color: The color of the hover shape
  5157. :return: None
  5158. """
  5159. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5160. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5161. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5162. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5163. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5164. if self.defaults['units'].upper() == 'MM':
  5165. hover_rect = hover_rect.buffer(-0.1)
  5166. hover_rect = hover_rect.buffer(0.2)
  5167. else:
  5168. hover_rect = hover_rect.buffer(-0.00393)
  5169. hover_rect = hover_rect.buffer(0.00787)
  5170. # if color:
  5171. # face = Color(color)
  5172. # face.alpha = 0.2
  5173. # outline = Color(color, alpha=0.8)
  5174. # else:
  5175. # face = Color(self.defaults['global_sel_fill'])
  5176. # face.alpha = 0.2
  5177. # outline = self.defaults['global_sel_line']
  5178. if color:
  5179. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5180. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5181. else:
  5182. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5183. outline = self.defaults['global_sel_line']
  5184. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5185. if self.is_legacy is True:
  5186. self.hover_shapes.redraw()
  5187. def delete_selection_shape(self):
  5188. self.move_tool.sel_shapes.clear()
  5189. self.move_tool.sel_shapes.redraw()
  5190. def draw_selection_shape(self, sel_obj, color=None):
  5191. """
  5192. Will draw a selection shape around the selected object.
  5193. :param sel_obj: The object for which the selection shape must be drawn
  5194. :param color: The color for the selection shape.
  5195. :return: None
  5196. """
  5197. if sel_obj is None:
  5198. return
  5199. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5200. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5201. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5202. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5203. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5204. if self.defaults['units'].upper() == 'MM':
  5205. sel_rect = sel_rect.buffer(-0.1)
  5206. sel_rect = sel_rect.buffer(0.2)
  5207. else:
  5208. sel_rect = sel_rect.buffer(-0.00393)
  5209. sel_rect = sel_rect.buffer(0.00787)
  5210. if color:
  5211. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5212. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5213. else:
  5214. if self.is_legacy is False:
  5215. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5216. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5217. else:
  5218. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5219. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5220. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5221. color=outline,
  5222. face_color=face,
  5223. update=True,
  5224. layer=0,
  5225. tolerance=None))
  5226. if self.is_legacy is True:
  5227. self.move_tool.sel_shapes.redraw()
  5228. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5229. """
  5230. Will draw a selection shape when dragging mouse on canvas.
  5231. :param old_coords: Old coordinates
  5232. :param coords: New coordinates
  5233. :param kwargs: Keyword arguments
  5234. :return:
  5235. """
  5236. if 'color' in kwargs:
  5237. color = kwargs['color']
  5238. else:
  5239. color = self.defaults['global_sel_line']
  5240. if 'face_color' in kwargs:
  5241. face_color = kwargs['face_color']
  5242. else:
  5243. face_color = self.defaults['global_sel_fill']
  5244. if 'face_alpha' in kwargs:
  5245. face_alpha = kwargs['face_alpha']
  5246. else:
  5247. face_alpha = 0.3
  5248. x0, y0 = old_coords
  5249. x1, y1 = coords
  5250. pt1 = (x0, y0)
  5251. pt2 = (x1, y0)
  5252. pt3 = (x1, y1)
  5253. pt4 = (x0, y1)
  5254. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5255. # color_t = Color(face_color)
  5256. # color_t.alpha = face_alpha
  5257. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5258. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5259. layer=0, tolerance=None)
  5260. if self.is_legacy is True:
  5261. self.move_tool.sel_shapes.redraw()
  5262. def on_file_new_click(self):
  5263. """
  5264. Callback for menu item File -> New.
  5265. Executed on clicking the Menu -> File -> New Project
  5266. :return:
  5267. """
  5268. if self.collection.get_list() and self.should_we_save:
  5269. msgbox = QtWidgets.QMessageBox()
  5270. # msgbox.setText("<B>Save changes ...</B>")
  5271. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5272. "Creating a New project will delete them.\n"
  5273. "Do you want to Save the project?"))
  5274. msgbox.setWindowTitle(_("Save changes"))
  5275. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5276. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5277. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5278. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5279. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5280. msgbox.setDefaultButton(bt_yes)
  5281. msgbox.exec_()
  5282. response = msgbox.clickedButton()
  5283. if response == bt_yes:
  5284. self.on_file_saveprojectas()
  5285. elif response == bt_cancel:
  5286. return
  5287. elif response == bt_no:
  5288. self.on_file_new()
  5289. else:
  5290. self.on_file_new()
  5291. self.inform.emit('[success] %s...' % _("New Project created"))
  5292. def on_file_new(self, cli=None):
  5293. """
  5294. Returns the application to its startup state. This method is thread-safe.
  5295. :param cli: Boolean. If True this method was run from command line
  5296. :return: None
  5297. """
  5298. self.defaults.report_usage("on_file_new")
  5299. # Remove everything from memory
  5300. App.log.debug("on_file_new()")
  5301. # close any editor that might be open
  5302. if self.call_source != 'app':
  5303. self.editor2object(cleanup=True)
  5304. # ## EDITOR section
  5305. self.geo_editor = FlatCAMGeoEditor(self)
  5306. self.exc_editor = FlatCAMExcEditor(self)
  5307. self.grb_editor = FlatCAMGrbEditor(self)
  5308. # Clear pool
  5309. self.clear_pool()
  5310. for obj in self.collection.get_list():
  5311. # delete shapes left drawn from mark shape_collections, if any
  5312. if isinstance(obj, GerberObject):
  5313. try:
  5314. for el in obj.mark_shapes:
  5315. obj.mark_shapes[el].clear(update=True)
  5316. obj.mark_shapes[el].enabled = False
  5317. del el
  5318. except AttributeError:
  5319. pass
  5320. # also delete annotation shapes, if any
  5321. elif isinstance(obj, CNCJobObject):
  5322. try:
  5323. obj.text_col.enabled = False
  5324. del obj.text_col
  5325. obj.annotation.clear(update=True)
  5326. del obj.annotation
  5327. except AttributeError:
  5328. pass
  5329. # delete the exclusion areas
  5330. self.exc_areas.clear_shapes()
  5331. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5332. self.shell.init_tcl()
  5333. # delete any selection shape on canvas
  5334. self.delete_selection_shape()
  5335. # delete all FlatCAM objects
  5336. self.collection.delete_all()
  5337. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5338. self.setup_component_editor()
  5339. # Clear project filename
  5340. self.project_filename = None
  5341. # Load the application defaults
  5342. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5343. # Re-fresh project options
  5344. self.on_options_app2project()
  5345. # Init FlatCAMTools
  5346. self.init_tools()
  5347. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5348. if cli is None:
  5349. # we need to go in reverse because once we remove a tab then the index changes
  5350. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5351. # and so on. Therefore the deletion should be done in reverse
  5352. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5353. for index in range(wdg_count, -1, -1):
  5354. try:
  5355. self.ui.plot_tab_area.closeTab(index)
  5356. except Exception as e:
  5357. log.debug("App.on_file_new() --> %s" % str(e))
  5358. # # And then add again the Plot Area
  5359. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5360. self.ui.plot_tab_area.protectTab(0)
  5361. # take the focus of the Notebook on Project Tab.
  5362. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5363. self.set_ui_title(name=_("New Project - Not saved"))
  5364. def obj_properties(self):
  5365. """
  5366. Will launch the object Properties Tool
  5367. :return:
  5368. """
  5369. self.defaults.report_usage("obj_properties()")
  5370. self.properties_tool.run(toggle=False)
  5371. def on_project_context_save(self):
  5372. """
  5373. Wrapper, will save the object function of it's type
  5374. :return:
  5375. """
  5376. obj = self.collection.get_active()
  5377. if type(obj) == GeometryObject:
  5378. self.on_file_exportdxf()
  5379. elif type(obj) == ExcellonObject:
  5380. self.on_file_saveexcellon()
  5381. elif type(obj) == CNCJobObject:
  5382. obj.on_exportgcode_button_click()
  5383. elif type(obj) == GerberObject:
  5384. self.on_file_savegerber()
  5385. elif type(obj) == ScriptObject:
  5386. self.on_file_savescript()
  5387. elif type(obj) == DocumentObject:
  5388. self.on_file_savedocument()
  5389. def obj_move(self):
  5390. """
  5391. Callback for the Move menu entry in various Context Menu's.
  5392. :return:
  5393. """
  5394. self.defaults.report_usage("obj_move()")
  5395. self.move_tool.run(toggle=False)
  5396. def on_fileopengerber(self, signal, name=None):
  5397. """
  5398. File menu callback for opening a Gerber.
  5399. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5400. :param name:
  5401. :return: None
  5402. """
  5403. self.defaults.report_usage("on_fileopengerber")
  5404. App.log.debug("on_fileopengerber()")
  5405. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5406. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5407. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5408. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5409. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5410. "*.mil);;" \
  5411. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5412. "Allegro Files (*.art);;" \
  5413. "Mentor Files (*.pho *.gdo);;" \
  5414. "All Files (*.*)"
  5415. if name is None:
  5416. try:
  5417. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5418. directory=self.get_last_folder(),
  5419. filter=_filter_)
  5420. except TypeError:
  5421. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5422. filenames = [str(filename) for filename in filenames]
  5423. else:
  5424. filenames = [name]
  5425. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5426. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5427. _("Opening Gerber file.")),
  5428. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5429. color=QtGui.QColor("gray"))
  5430. if len(filenames) == 0:
  5431. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5432. else:
  5433. for filename in filenames:
  5434. if filename != '':
  5435. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5436. def on_fileopenexcellon(self, signal, name=None):
  5437. """
  5438. File menu callback for opening an Excellon file.
  5439. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5440. :param name:
  5441. :return: None
  5442. """
  5443. self.defaults.report_usage("on_fileopenexcellon")
  5444. App.log.debug("on_fileopenexcellon()")
  5445. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5446. "All Files (*.*)"
  5447. if name is None:
  5448. try:
  5449. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5450. directory=self.get_last_folder(),
  5451. filter=_filter_)
  5452. except TypeError:
  5453. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5454. filenames = [str(filename) for filename in filenames]
  5455. else:
  5456. filenames = [str(name)]
  5457. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5458. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5459. _("Opening Excellon file.")),
  5460. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5461. color=QtGui.QColor("gray"))
  5462. if len(filenames) == 0:
  5463. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5464. else:
  5465. for filename in filenames:
  5466. if filename != '':
  5467. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5468. def on_fileopengcode(self, signal, name=None):
  5469. """
  5470. File menu call back for opening gcode.
  5471. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5472. :param name:
  5473. :return:
  5474. """
  5475. self.defaults.report_usage("on_fileopengcode")
  5476. App.log.debug("on_fileopengcode()")
  5477. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5478. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5479. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5480. "All Files (*.*)"
  5481. if name is None:
  5482. try:
  5483. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5484. directory=self.get_last_folder(),
  5485. filter=_filter_)
  5486. except TypeError:
  5487. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5488. filenames = [str(filename) for filename in filenames]
  5489. else:
  5490. filenames = [name]
  5491. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5492. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5493. _("Opening G-Code file.")),
  5494. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5495. color=QtGui.QColor("gray"))
  5496. if len(filenames) == 0:
  5497. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5498. else:
  5499. for filename in filenames:
  5500. if filename != '':
  5501. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5502. def on_file_openproject(self, signal):
  5503. """
  5504. File menu callback for opening a project.
  5505. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5506. :return: None
  5507. """
  5508. self.defaults.report_usage("on_file_openproject")
  5509. App.log.debug("on_file_openproject()")
  5510. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5511. try:
  5512. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5513. directory=self.get_last_folder(), filter=_filter_)
  5514. except TypeError:
  5515. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5516. # The Qt methods above will return a QString which can cause problems later.
  5517. # So far json.dump() will fail to serialize it.
  5518. # TODO: Improve the serialization methods and remove this fix.
  5519. filename = str(filename)
  5520. if filename == "":
  5521. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5522. else:
  5523. # self.worker_task.emit({'fcn': self.open_project,
  5524. # 'params': [filename]})
  5525. # The above was failing because open_project() is not
  5526. # thread safe. The new_project()
  5527. self.open_project(filename)
  5528. def on_fileopenhpgl2(self, signal, name=None):
  5529. """
  5530. File menu callback for opening a HPGL2.
  5531. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5532. :param name:
  5533. :return: None
  5534. """
  5535. self.defaults.report_usage("on_fileopenhpgl2")
  5536. App.log.debug("on_fileopenhpgl2()")
  5537. _filter_ = "HPGL2 Files (*.plt);;" \
  5538. "All Files (*.*)"
  5539. if name is None:
  5540. try:
  5541. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5542. directory=self.get_last_folder(),
  5543. filter=_filter_)
  5544. except TypeError:
  5545. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5546. filenames = [str(filename) for filename in filenames]
  5547. else:
  5548. filenames = [name]
  5549. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5550. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5551. _("Opening HPGL2 file.")),
  5552. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5553. color=QtGui.QColor("gray"))
  5554. if len(filenames) == 0:
  5555. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5556. else:
  5557. for filename in filenames:
  5558. if filename != '':
  5559. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5560. def on_file_openconfig(self, signal):
  5561. """
  5562. File menu callback for opening a config file.
  5563. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5564. :return: None
  5565. """
  5566. self.defaults.report_usage("on_file_openconfig")
  5567. App.log.debug("on_file_openconfig()")
  5568. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5569. try:
  5570. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5571. directory=self.data_path, filter=_filter_)
  5572. except TypeError:
  5573. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5574. filter=_filter_)
  5575. if filename == "":
  5576. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5577. else:
  5578. self.open_config_file(filename)
  5579. def on_file_exportsvg(self):
  5580. """
  5581. Callback for menu item File->Export SVG.
  5582. :return: None
  5583. """
  5584. self.defaults.report_usage("on_file_exportsvg")
  5585. App.log.debug("on_file_exportsvg()")
  5586. obj = self.collection.get_active()
  5587. if obj is None:
  5588. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5589. msg = _("Please Select a Geometry object to export")
  5590. msgbox = QtWidgets.QMessageBox()
  5591. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5592. msgbox.setInformativeText(msg)
  5593. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5594. msgbox.setDefaultButton(bt_ok)
  5595. msgbox.exec_()
  5596. return
  5597. # Check for more compatible types and add as required
  5598. if (not isinstance(obj, GeometryObject)
  5599. and not isinstance(obj, GerberObject)
  5600. and not isinstance(obj, CNCJobObject)
  5601. and not isinstance(obj, ExcellonObject)):
  5602. msg = '[ERROR_NOTCL] %s' % \
  5603. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5604. msgbox = QtWidgets.QMessageBox()
  5605. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5606. msgbox.setInformativeText(msg)
  5607. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5608. msgbox.setDefaultButton(bt_ok)
  5609. msgbox.exec_()
  5610. return
  5611. name = obj.options["name"]
  5612. _filter = "SVG File (*.svg);;All Files (*.*)"
  5613. try:
  5614. filename, _f = FCFileSaveDialog.get_saved_filename(
  5615. caption=_("Export SVG"),
  5616. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5617. filter=_filter)
  5618. except TypeError:
  5619. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  5620. filename = str(filename)
  5621. if filename == "":
  5622. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5623. return
  5624. else:
  5625. self.export_svg(name, filename)
  5626. if self.defaults["global_open_style"] is False:
  5627. self.file_opened.emit("SVG", filename)
  5628. self.file_saved.emit("SVG", filename)
  5629. def on_file_exportpng(self):
  5630. self.defaults.report_usage("on_file_exportpng")
  5631. App.log.debug("on_file_exportpng()")
  5632. self.date = str(datetime.today()).rpartition('.')[0]
  5633. self.date = ''.join(c for c in self.date if c not in ':-')
  5634. self.date = self.date.replace(' ', '_')
  5635. if self.is_legacy is False:
  5636. image = _screenshot()
  5637. data = np.asarray(image)
  5638. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5639. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5640. return
  5641. filter_ = "PNG File (*.png);;All Files (*.*)"
  5642. try:
  5643. filename, _f = FCFileSaveDialog.get_saved_filename(
  5644. caption=_("Export PNG Image"),
  5645. directory=self.get_last_save_folder() + '/png_' + self.date,
  5646. filter=filter_)
  5647. except TypeError:
  5648. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  5649. filename = str(filename)
  5650. if filename == "":
  5651. self.inform.emit(_("Cancelled."))
  5652. return
  5653. else:
  5654. if self.is_legacy is False:
  5655. write_png(filename, data)
  5656. else:
  5657. self.plotcanvas.figure.savefig(filename)
  5658. if self.defaults["global_open_style"] is False:
  5659. self.file_opened.emit("png", filename)
  5660. self.file_saved.emit("png", filename)
  5661. def on_file_savegerber(self):
  5662. """
  5663. Callback for menu item in Project context menu.
  5664. :return: None
  5665. """
  5666. self.defaults.report_usage("on_file_savegerber")
  5667. App.log.debug("on_file_savegerber()")
  5668. obj = self.collection.get_active()
  5669. if obj is None:
  5670. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5671. return
  5672. # Check for more compatible types and add as required
  5673. if not isinstance(obj, GerberObject):
  5674. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5675. return
  5676. name = self.collection.get_active().options["name"]
  5677. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5678. try:
  5679. filename, _f = FCFileSaveDialog.get_saved_filename(
  5680. caption="Save Gerber source file",
  5681. directory=self.get_last_save_folder() + '/' + name,
  5682. filter=_filter)
  5683. except TypeError:
  5684. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  5685. filename = str(filename)
  5686. if filename == "":
  5687. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5688. return
  5689. else:
  5690. self.save_source_file(name, filename)
  5691. if self.defaults["global_open_style"] is False:
  5692. self.file_opened.emit("Gerber", filename)
  5693. self.file_saved.emit("Gerber", filename)
  5694. def on_file_savescript(self):
  5695. """
  5696. Callback for menu item in Project context menu.
  5697. :return: None
  5698. """
  5699. self.defaults.report_usage("on_file_savescript")
  5700. App.log.debug("on_file_savescript()")
  5701. obj = self.collection.get_active()
  5702. if obj is None:
  5703. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5704. return
  5705. # Check for more compatible types and add as required
  5706. if not isinstance(obj, ScriptObject):
  5707. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5708. return
  5709. name = self.collection.get_active().options["name"]
  5710. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5711. try:
  5712. filename, _f = FCFileSaveDialog.get_saved_filename(
  5713. caption="Save Script source file",
  5714. directory=self.get_last_save_folder() + '/' + name,
  5715. filter=_filter)
  5716. except TypeError:
  5717. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  5718. filename = str(filename)
  5719. if filename == "":
  5720. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5721. return
  5722. else:
  5723. self.save_source_file(name, filename)
  5724. if self.defaults["global_open_style"] is False:
  5725. self.file_opened.emit("Script", filename)
  5726. self.file_saved.emit("Script", filename)
  5727. def on_file_savedocument(self):
  5728. """
  5729. Callback for menu item in Project context menu.
  5730. :return: None
  5731. """
  5732. self.defaults.report_usage("on_file_savedocument")
  5733. App.log.debug("on_file_savedocument()")
  5734. obj = self.collection.get_active()
  5735. if obj is None:
  5736. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5737. return
  5738. # Check for more compatible types and add as required
  5739. if not isinstance(obj, ScriptObject):
  5740. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5741. return
  5742. name = self.collection.get_active().options["name"]
  5743. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5744. try:
  5745. filename, _f = FCFileSaveDialog.get_saved_filename(
  5746. caption="Save Document source file",
  5747. directory=self.get_last_save_folder() + '/' + name,
  5748. filter=_filter)
  5749. except TypeError:
  5750. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  5751. filename = str(filename)
  5752. if filename == "":
  5753. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5754. return
  5755. else:
  5756. self.save_source_file(name, filename)
  5757. if self.defaults["global_open_style"] is False:
  5758. self.file_opened.emit("Document", filename)
  5759. self.file_saved.emit("Document", filename)
  5760. def on_file_saveexcellon(self):
  5761. """
  5762. Callback for menu item in project context menu.
  5763. :return: None
  5764. """
  5765. self.defaults.report_usage("on_file_saveexcellon")
  5766. App.log.debug("on_file_saveexcellon()")
  5767. obj = self.collection.get_active()
  5768. if obj is None:
  5769. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5770. return
  5771. # Check for more compatible types and add as required
  5772. if not isinstance(obj, ExcellonObject):
  5773. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5774. return
  5775. name = self.collection.get_active().options["name"]
  5776. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5777. try:
  5778. filename, _f = FCFileSaveDialog.get_saved_filename(
  5779. caption=_("Save Excellon source file"),
  5780. directory=self.get_last_save_folder() + '/' + name,
  5781. filter=_filter)
  5782. except TypeError:
  5783. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  5784. filename = str(filename)
  5785. if filename == "":
  5786. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5787. return
  5788. else:
  5789. self.save_source_file(name, filename)
  5790. if self.defaults["global_open_style"] is False:
  5791. self.file_opened.emit("Excellon", filename)
  5792. self.file_saved.emit("Excellon", filename)
  5793. def on_file_exportexcellon(self):
  5794. """
  5795. Callback for menu item File->Export->Excellon.
  5796. :return: None
  5797. """
  5798. self.defaults.report_usage("on_file_exportexcellon")
  5799. App.log.debug("on_file_exportexcellon()")
  5800. obj = self.collection.get_active()
  5801. if obj is None:
  5802. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5803. return
  5804. # Check for more compatible types and add as required
  5805. if not isinstance(obj, ExcellonObject):
  5806. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5807. return
  5808. name = self.collection.get_active().options["name"]
  5809. _filter = self.defaults["excellon_save_filters"]
  5810. try:
  5811. filename, _f = FCFileSaveDialog.get_saved_filename(
  5812. caption=_("Export Excellon"),
  5813. directory=self.get_last_save_folder() + '/' + name,
  5814. filter=_filter)
  5815. except TypeError:
  5816. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  5817. filename = str(filename)
  5818. if filename == "":
  5819. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5820. return
  5821. else:
  5822. used_extension = filename.rpartition('.')[2]
  5823. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5824. self.export_excellon(name, filename)
  5825. if self.defaults["global_open_style"] is False:
  5826. self.file_opened.emit("Excellon", filename)
  5827. self.file_saved.emit("Excellon", filename)
  5828. def on_file_exportgerber(self):
  5829. """
  5830. Callback for menu item File->Export->Gerber.
  5831. :return: None
  5832. """
  5833. self.defaults.report_usage("on_file_exportgerber")
  5834. App.log.debug("on_file_exportgerber()")
  5835. obj = self.collection.get_active()
  5836. if obj is None:
  5837. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5838. return
  5839. # Check for more compatible types and add as required
  5840. if not isinstance(obj, GerberObject):
  5841. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5842. return
  5843. name = self.collection.get_active().options["name"]
  5844. _filter_ = self.defaults['gerber_save_filters']
  5845. try:
  5846. filename, _f = FCFileSaveDialog.get_saved_filename(
  5847. caption=_("Export Gerber"),
  5848. directory=self.get_last_save_folder() + '/' + name,
  5849. filter=_filter_)
  5850. except TypeError:
  5851. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  5852. filename = str(filename)
  5853. if filename == "":
  5854. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5855. return
  5856. else:
  5857. used_extension = filename.rpartition('.')[2]
  5858. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5859. self.export_gerber(name, filename)
  5860. if self.defaults["global_open_style"] is False:
  5861. self.file_opened.emit("Gerber", filename)
  5862. self.file_saved.emit("Gerber", filename)
  5863. def on_file_exportdxf(self):
  5864. """
  5865. Callback for menu item File->Export DXF.
  5866. :return: None
  5867. """
  5868. self.defaults.report_usage("on_file_exportdxf")
  5869. App.log.debug("on_file_exportdxf()")
  5870. obj = self.collection.get_active()
  5871. if obj is None:
  5872. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5873. msg = _("Please Select a Geometry object to export")
  5874. msgbox = QtWidgets.QMessageBox()
  5875. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5876. msgbox.setInformativeText(msg)
  5877. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5878. msgbox.setDefaultButton(bt_ok)
  5879. msgbox.exec_()
  5880. return
  5881. # Check for more compatible types and add as required
  5882. if not isinstance(obj, GeometryObject):
  5883. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5884. msgbox = QtWidgets.QMessageBox()
  5885. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5886. msgbox.setInformativeText(msg)
  5887. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5888. msgbox.setDefaultButton(bt_ok)
  5889. msgbox.exec_()
  5890. return
  5891. name = self.collection.get_active().options["name"]
  5892. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5893. try:
  5894. filename, _f = FCFileSaveDialog.get_saved_filename(
  5895. caption=_("Export DXF"),
  5896. directory=self.get_last_save_folder() + '/' + name,
  5897. filter=_filter_)
  5898. except TypeError:
  5899. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  5900. filename = str(filename)
  5901. if filename == "":
  5902. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5903. return
  5904. else:
  5905. self.export_dxf(name, filename)
  5906. if self.defaults["global_open_style"] is False:
  5907. self.file_opened.emit("DXF", filename)
  5908. self.file_saved.emit("DXF", filename)
  5909. def on_file_importsvg(self, type_of_obj):
  5910. """
  5911. Callback for menu item File->Import SVG.
  5912. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5913. :type type_of_obj: str
  5914. :return: None
  5915. """
  5916. self.defaults.report_usage("on_file_importsvg")
  5917. App.log.debug("on_file_importsvg()")
  5918. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  5919. try:
  5920. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5921. directory=self.get_last_folder(), filter=_filter_)
  5922. except TypeError:
  5923. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5924. filter=_filter_)
  5925. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5926. type_of_obj = "geometry"
  5927. filenames = [str(filename) for filename in filenames]
  5928. if len(filenames) == 0:
  5929. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5930. else:
  5931. for filename in filenames:
  5932. if filename != '':
  5933. self.worker_task.emit({'fcn': self.import_svg,
  5934. 'params': [filename, type_of_obj]})
  5935. def on_file_importdxf(self, type_of_obj):
  5936. """
  5937. Callback for menu item File->Import DXF.
  5938. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5939. :type type_of_obj: str
  5940. :return: None
  5941. """
  5942. self.defaults.report_usage("on_file_importdxf")
  5943. App.log.debug("on_file_importdxf()")
  5944. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5945. try:
  5946. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5947. directory=self.get_last_folder(),
  5948. filter=_filter_)
  5949. except TypeError:
  5950. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5951. filter=_filter_)
  5952. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5953. type_of_obj = "geometry"
  5954. filenames = [str(filename) for filename in filenames]
  5955. if len(filenames) == 0:
  5956. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5957. else:
  5958. for filename in filenames:
  5959. if filename != '':
  5960. self.worker_task.emit({'fcn': self.import_dxf,
  5961. 'params': [filename, type_of_obj]})
  5962. # ###############################################################################################################
  5963. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5964. # ###############################################################################################################
  5965. def init_code_editor(self, name):
  5966. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  5967. # add the tab if it was closed
  5968. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5969. self.text_editor_tab.setObjectName('text_editor_tab')
  5970. # delete the absolute and relative position and messages in the infobar
  5971. self.ui.position_label.setText("")
  5972. # self.ui.rel_position_label.setText("")
  5973. # first clear previous text in text editor (if any)
  5974. self.text_editor_tab.code_editor.clear()
  5975. self.text_editor_tab.code_editor.setReadOnly(False)
  5976. self.toggle_codeeditor = True
  5977. self.text_editor_tab.code_editor.completer_enable = False
  5978. self.text_editor_tab.buttonRun.hide()
  5979. # make sure to keep a reference to the code editor
  5980. self.reference_code_editor = self.text_editor_tab.code_editor
  5981. # Switch plot_area to CNCJob tab
  5982. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5983. def on_view_source(self):
  5984. """
  5985. Called when the user wants to see the source file of the selected object
  5986. :return:
  5987. """
  5988. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5989. self.proc_container.view.set_busy(_("Loading..."))
  5990. try:
  5991. obj = self.collection.get_active()
  5992. except Exception as e:
  5993. log.debug("App.on_view_source() --> %s" % str(e))
  5994. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5995. return 'fail'
  5996. if obj is None:
  5997. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5998. return 'fail'
  5999. flt = "All Files (*.*)"
  6000. if obj.kind == 'gerber':
  6001. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6002. elif obj.kind == 'excellon':
  6003. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6004. elif obj.kind == 'cncjob':
  6005. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6006. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6007. # add the tab if it was closed
  6008. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6009. self.source_editor_tab.setObjectName('source_editor_tab')
  6010. # delete the absolute and relative position and messages in the infobar
  6011. self.ui.position_label.setText("")
  6012. # self.ui.rel_position_label.setText("")
  6013. # first clear previous text in text editor (if any)
  6014. self.source_editor_tab.code_editor.clear()
  6015. self.source_editor_tab.code_editor.setReadOnly(False)
  6016. self.source_editor_tab.code_editor.completer_enable = False
  6017. self.source_editor_tab.buttonRun.hide()
  6018. # Switch plot_area to CNCJob tab
  6019. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6020. try:
  6021. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6022. except TypeError:
  6023. pass
  6024. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6025. try:
  6026. self.source_editor_tab.buttonSave.clicked.disconnect()
  6027. except TypeError:
  6028. pass
  6029. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6030. # then append the text from GCode to the text editor
  6031. if obj.kind == 'cncjob':
  6032. try:
  6033. file = obj.export_gcode(
  6034. preamble=self.defaults["cncjob_prepend"],
  6035. postamble=self.defaults["cncjob_append"],
  6036. to_file=True)
  6037. if file == 'fail':
  6038. return 'fail'
  6039. except AttributeError:
  6040. self.inform.emit('[WARNING_NOTCL] %s' %
  6041. _("There is no selected object for which to see it's source file code."))
  6042. return 'fail'
  6043. else:
  6044. try:
  6045. file = StringIO(obj.source_file)
  6046. except (AttributeError, TypeError):
  6047. self.inform.emit('[WARNING_NOTCL] %s' %
  6048. _("There is no selected object for which to see it's source file code."))
  6049. return 'fail'
  6050. self.source_editor_tab.t_frame.hide()
  6051. try:
  6052. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6053. # for line in file:
  6054. # QtWidgets.QApplication.processEvents()
  6055. # proc_line = str(line).strip('\n')
  6056. # self.source_editor_tab.code_editor.append(proc_line)
  6057. except Exception as e:
  6058. log.debug('App.on_view_source() -->%s' % str(e))
  6059. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6060. return
  6061. self.source_editor_tab.handleTextChanged()
  6062. self.source_editor_tab.t_frame.show()
  6063. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6064. self.proc_container.view.set_idle()
  6065. # self.ui.show()
  6066. def on_toggle_code_editor(self):
  6067. self.defaults.report_usage("on_toggle_code_editor()")
  6068. if self.toggle_codeeditor is False:
  6069. self.init_code_editor(name=_("Code Editor"))
  6070. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6071. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6072. self.text_editor_tab.buttonSave.clicked.disconnect()
  6073. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6074. else:
  6075. for idx in range(self.ui.plot_tab_area.count()):
  6076. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6077. self.ui.plot_tab_area.closeTab(idx)
  6078. break
  6079. self.toggle_codeeditor = False
  6080. def on_code_editor_close(self):
  6081. self.toggle_codeeditor = False
  6082. def goto_text_line(self):
  6083. """
  6084. Will scroll a text to the specified text line.
  6085. :return: None
  6086. """
  6087. dia_box = Dialog_box(title=_("Go to Line ..."),
  6088. label=_("Line:"),
  6089. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6090. initial_text='')
  6091. try:
  6092. line = int(dia_box.location) - 1
  6093. except (ValueError, TypeError):
  6094. line = 0
  6095. if dia_box.ok:
  6096. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6097. # at the top of the window
  6098. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6099. # get the document() of the TextEditor
  6100. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6101. # create a Text Cursor based on the searched line
  6102. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6103. # set cursor of the code editor with the cursor at the searcehd line
  6104. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6105. def on_filenewscript(self, silent=False):
  6106. """
  6107. Will create a new script file and open it in the Code Editor
  6108. :param silent: if True will not display status messages
  6109. :return: None
  6110. """
  6111. if silent is False:
  6112. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6113. # delete the absolute and relative position and messages in the infobar
  6114. self.ui.position_label.setText("")
  6115. # self.ui.rel_position_label.setText("")
  6116. self.app_obj.new_script_object()
  6117. # script_text = script_obj.source_file
  6118. #
  6119. # self.proc_container.view.set_busy(_("Loading..."))
  6120. # script_obj.script_editor_tab.t_frame.hide()
  6121. #
  6122. # script_obj.script_editor_tab.t_frame.show()
  6123. # self.proc_container.view.set_idle()
  6124. def on_fileopenscript(self, name=None, silent=False):
  6125. """
  6126. Will open a Tcl script file into the Code Editor
  6127. :param silent: if True will not display status messages
  6128. :param name: name of a Tcl script file to open
  6129. :return: None
  6130. """
  6131. self.defaults.report_usage("on_fileopenscript")
  6132. App.log.debug("on_fileopenscript()")
  6133. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6134. "All Files (*.*)"
  6135. if name:
  6136. filenames = [name]
  6137. else:
  6138. try:
  6139. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6140. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6141. except TypeError:
  6142. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6143. if len(filenames) == 0:
  6144. if silent is False:
  6145. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6146. else:
  6147. for filename in filenames:
  6148. if filename != '':
  6149. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6150. def on_fileopenscript_example(self, name=None, silent=False):
  6151. """
  6152. Will open a Tcl script file into the Code Editor
  6153. :param silent: if True will not display status messages
  6154. :param name: name of a Tcl script file to open
  6155. :return:
  6156. """
  6157. self.defaults.report_usage("on_fileopenscript_example")
  6158. log.debug("on_fileopenscript_example()")
  6159. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6160. "All Files (*.*)"
  6161. # test if the app was frozen and choose the path for the configuration file
  6162. if getattr(sys, "frozen", False) is True:
  6163. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6164. else:
  6165. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6166. if name:
  6167. filenames = [name]
  6168. else:
  6169. try:
  6170. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6171. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6172. except TypeError:
  6173. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6174. if len(filenames) == 0:
  6175. if silent is False:
  6176. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6177. else:
  6178. for filename in filenames:
  6179. if filename != '':
  6180. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6181. def on_filerunscript(self, name=None, silent=False):
  6182. """
  6183. File menu callback for loading and running a TCL script.
  6184. :param silent: if True will not display status messages
  6185. :param name: name of a Tcl script file to be run by FlatCAM
  6186. :return: None
  6187. """
  6188. self.defaults.report_usage("on_filerunscript")
  6189. App.log.debug("on_file_runscript()")
  6190. if name:
  6191. filename = name
  6192. if self.cmd_line_headless != 1:
  6193. self.splash.showMessage('%s: %ssec\n%s' %
  6194. (_("Canvas initialization started.\n"
  6195. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6196. _("Executing ScriptObject file.")
  6197. ),
  6198. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6199. color=QtGui.QColor("gray"))
  6200. else:
  6201. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6202. "All Files (*.*)"
  6203. try:
  6204. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6205. directory=self.get_last_folder(), filter=_filter_)
  6206. except TypeError:
  6207. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6208. # The Qt methods above will return a QString which can cause problems later.
  6209. # So far json.dump() will fail to serialize it.
  6210. filename = str(filename)
  6211. if filename == "":
  6212. if silent is False:
  6213. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6214. else:
  6215. if self.cmd_line_headless != 1:
  6216. if self.ui.shell_dock.isHidden():
  6217. self.ui.shell_dock.show()
  6218. try:
  6219. with open(filename, "r") as tcl_script:
  6220. cmd_line_shellfile_content = tcl_script.read()
  6221. if self.cmd_line_headless != 1:
  6222. self.shell.exec_command(cmd_line_shellfile_content)
  6223. else:
  6224. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6225. if silent is False:
  6226. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6227. except Exception as e:
  6228. log.debug("App.on_filerunscript() -> %s" % str(e))
  6229. sys.exit(2)
  6230. def on_file_saveproject(self, silent=False):
  6231. """
  6232. Callback for menu item File->Save Project. Saves the project to
  6233. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6234. if set to None. The project is saved by calling ``self.save_project()``.
  6235. :param silent: if True will not display status messages
  6236. :return: None
  6237. """
  6238. self.defaults.report_usage("on_file_saveproject")
  6239. if self.project_filename is None:
  6240. self.on_file_saveprojectas()
  6241. else:
  6242. self.worker_task.emit({'fcn': self.save_project,
  6243. 'params': [self.project_filename, silent]})
  6244. if self.defaults["global_open_style"] is False:
  6245. self.file_opened.emit("project", self.project_filename)
  6246. self.file_saved.emit("project", self.project_filename)
  6247. self.set_ui_title(name=self.project_filename)
  6248. self.should_we_save = False
  6249. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6250. """
  6251. Callback for menu item File->Save Project As... Opens a file
  6252. chooser and saves the project to the given file via
  6253. ``self.save_project()``.
  6254. :param make_copy if to be create a copy of the project; boolean
  6255. :param use_thread: if to be run in a separate thread; boolean
  6256. :param quit_action: if to be followed by quiting the application; boolean
  6257. :return: None
  6258. """
  6259. self.defaults.report_usage("on_file_saveprojectas")
  6260. self.date = str(datetime.today()).rpartition('.')[0]
  6261. self.date = ''.join(c for c in self.date if c not in ':-')
  6262. self.date = self.date.replace(' ', '_')
  6263. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6264. try:
  6265. filename, _f = FCFileSaveDialog.get_saved_filename(
  6266. caption=_("Save Project As ..."),
  6267. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6268. proj=_("Project")),
  6269. filter=filter_
  6270. )
  6271. except TypeError:
  6272. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6273. filename = str(filename)
  6274. if filename == '':
  6275. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6276. return
  6277. if use_thread is True:
  6278. self.worker_task.emit({'fcn': self.save_project,
  6279. 'params': [filename, quit_action]})
  6280. else:
  6281. self.save_project(filename, quit_action)
  6282. # self.save_project(filename)
  6283. if self.defaults["global_open_style"] is False:
  6284. self.file_opened.emit("project", filename)
  6285. self.file_saved.emit("project", filename)
  6286. if not make_copy:
  6287. self.project_filename = filename
  6288. self.set_ui_title(name=self.project_filename)
  6289. self.should_we_save = False
  6290. def on_file_save_objects_pdf(self, use_thread=True):
  6291. self.date = str(datetime.today()).rpartition('.')[0]
  6292. self.date = ''.join(c for c in self.date if c not in ':-')
  6293. self.date = self.date.replace(' ', '_')
  6294. try:
  6295. obj_selection = self.collection.get_selected()
  6296. if len(obj_selection) == 1:
  6297. obj_name = str(obj_selection[0].options['name'])
  6298. else:
  6299. obj_name = _("FlatCAM objects print")
  6300. except AttributeError as err:
  6301. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6302. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6303. return
  6304. if not obj_selection:
  6305. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6306. return
  6307. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6308. try:
  6309. filename, _f = FCFileSaveDialog.get_saved_filename(
  6310. caption=_("Save Object as PDF ..."),
  6311. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6312. obj_name=obj_name,
  6313. date=self.date),
  6314. filter=filter_
  6315. )
  6316. except TypeError:
  6317. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6318. filename = str(filename)
  6319. if filename == '':
  6320. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6321. return
  6322. if use_thread is True:
  6323. self.proc_container.new(_("Printing PDF ... Please wait."))
  6324. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6325. else:
  6326. self.save_pdf(filename, obj_selection)
  6327. # self.save_project(filename)
  6328. if self.defaults["global_open_style"] is False:
  6329. self.file_opened.emit("pdf", filename)
  6330. self.file_saved.emit("pdf", filename)
  6331. def save_pdf(self, file_name, obj_selection):
  6332. p_size = self.defaults['global_workspaceT']
  6333. orientation = self.defaults['global_workspace_orientation']
  6334. color = 'black'
  6335. transparency_level = 1.0
  6336. self.pagesize = {}
  6337. self.pagesize.update(
  6338. {
  6339. 'Bounds': None,
  6340. 'A0': (841 * mm, 1189 * mm),
  6341. 'A1': (594 * mm, 841 * mm),
  6342. 'A2': (420 * mm, 594 * mm),
  6343. 'A3': (297 * mm, 420 * mm),
  6344. 'A4': (210 * mm, 297 * mm),
  6345. 'A5': (148 * mm, 210 * mm),
  6346. 'A6': (105 * mm, 148 * mm),
  6347. 'A7': (74 * mm, 105 * mm),
  6348. 'A8': (52 * mm, 74 * mm),
  6349. 'A9': (37 * mm, 52 * mm),
  6350. 'A10': (26 * mm, 37 * mm),
  6351. 'B0': (1000 * mm, 1414 * mm),
  6352. 'B1': (707 * mm, 1000 * mm),
  6353. 'B2': (500 * mm, 707 * mm),
  6354. 'B3': (353 * mm, 500 * mm),
  6355. 'B4': (250 * mm, 353 * mm),
  6356. 'B5': (176 * mm, 250 * mm),
  6357. 'B6': (125 * mm, 176 * mm),
  6358. 'B7': (88 * mm, 125 * mm),
  6359. 'B8': (62 * mm, 88 * mm),
  6360. 'B9': (44 * mm, 62 * mm),
  6361. 'B10': (31 * mm, 44 * mm),
  6362. 'C0': (917 * mm, 1297 * mm),
  6363. 'C1': (648 * mm, 917 * mm),
  6364. 'C2': (458 * mm, 648 * mm),
  6365. 'C3': (324 * mm, 458 * mm),
  6366. 'C4': (229 * mm, 324 * mm),
  6367. 'C5': (162 * mm, 229 * mm),
  6368. 'C6': (114 * mm, 162 * mm),
  6369. 'C7': (81 * mm, 114 * mm),
  6370. 'C8': (57 * mm, 81 * mm),
  6371. 'C9': (40 * mm, 57 * mm),
  6372. 'C10': (28 * mm, 40 * mm),
  6373. # American paper sizes
  6374. 'LETTER': (8.5 * inch, 11 * inch),
  6375. 'LEGAL': (8.5 * inch, 14 * inch),
  6376. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6377. # From https://en.wikipedia.org/wiki/Paper_size
  6378. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6379. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6380. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6381. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6382. 'LEDGER': (17 * inch, 11 * inch),
  6383. }
  6384. )
  6385. exported_svg = []
  6386. for obj in obj_selection:
  6387. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6388. scale_factor_x=None, scale_factor_y=None,
  6389. skew_factor_x=None, skew_factor_y=None,
  6390. mirror=None)
  6391. if obj.kind.lower() == 'gerber':
  6392. # color = self.defaults["gerber_plot_fill"][:-2]
  6393. color = obj.fill_color[:-2]
  6394. elif obj.kind.lower() == 'excellon':
  6395. color = '#C40000'
  6396. elif obj.kind.lower() == 'geometry':
  6397. color = self.defaults["global_draw_color"]
  6398. # Change the attributes of the exported SVG
  6399. # We don't need stroke-width
  6400. # We set opacity to maximum
  6401. # We set the colour to WHITE
  6402. root = ET.fromstring(svg_obj)
  6403. for child in root:
  6404. child.set('fill', str(color))
  6405. child.set('opacity', str(transparency_level))
  6406. child.set('stroke', str(color))
  6407. exported_svg.append(ET.tostring(root))
  6408. xmin = Inf
  6409. ymin = Inf
  6410. xmax = -Inf
  6411. ymax = -Inf
  6412. for obj in obj_selection:
  6413. try:
  6414. gxmin, gymin, gxmax, gymax = obj.bounds()
  6415. xmin = min([xmin, gxmin])
  6416. ymin = min([ymin, gymin])
  6417. xmax = max([xmax, gxmax])
  6418. ymax = max([ymax, gymax])
  6419. except Exception as e:
  6420. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6421. # Determine bounding area for svg export
  6422. bounds = [xmin, ymin, xmax, ymax]
  6423. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6424. # This contain the measure units
  6425. uom = obj_selection[0].units.lower()
  6426. # Define a boundary around SVG of about 1.0mm (~39mils)
  6427. if uom in "mm":
  6428. boundary = 1.0
  6429. else:
  6430. boundary = 0.0393701
  6431. # Convert everything to strings for use in the xml doc
  6432. svgwidth = str(size[0] + (2 * boundary))
  6433. svgheight = str(size[1] + (2 * boundary))
  6434. minx = str(bounds[0] - boundary)
  6435. miny = str(bounds[1] + boundary + size[1])
  6436. # Add a SVG Header and footer to the svg output from shapely
  6437. # The transform flips the Y Axis so that everything renders
  6438. # properly within svg apps such as inkscape
  6439. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6440. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6441. svg_header += 'width="' + svgwidth + uom + '" '
  6442. svg_header += 'height="' + svgheight + uom + '" '
  6443. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6444. svg_header += '>'
  6445. svg_header += '<g transform="scale(1,-1)">'
  6446. svg_footer = '</g> </svg>'
  6447. svg_elem = str(svg_header)
  6448. for svg_item in exported_svg:
  6449. svg_elem += str(svg_item)
  6450. svg_elem += str(svg_footer)
  6451. # Parse the xml through a xml parser just to add line feeds
  6452. # and to make it look more pretty for the output
  6453. doc = parse_xml_string(svg_elem)
  6454. doc_final = doc.toprettyxml()
  6455. try:
  6456. if self.defaults['units'].upper() == 'IN':
  6457. unit = inch
  6458. else:
  6459. unit = mm
  6460. doc_final = StringIO(doc_final)
  6461. drawing = svg2rlg(doc_final)
  6462. if p_size == 'Bounds':
  6463. renderPDF.drawToFile(drawing, file_name)
  6464. else:
  6465. if orientation == 'p':
  6466. page_size = portrait(self.pagesize[p_size])
  6467. else:
  6468. page_size = landscape(self.pagesize[p_size])
  6469. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6470. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6471. renderPDF.draw(drawing, my_canvas, 0, 0)
  6472. my_canvas.save()
  6473. except Exception as e:
  6474. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6475. return 'fail'
  6476. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6477. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6478. """
  6479. Exports a Geometry Object to an SVG file.
  6480. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6481. :param filename: Path to the SVG file to save to.
  6482. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6483. :return:
  6484. """
  6485. self.defaults.report_usage("export_svg()")
  6486. if filename is None:
  6487. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6488. is not None else self.defaults["global_last_folder"]
  6489. self.log.debug("export_svg()")
  6490. try:
  6491. obj = self.collection.get_by_name(str(obj_name))
  6492. except Exception:
  6493. # TODO: The return behavior has not been established... should raise exception?
  6494. return "Could not retrieve object: %s" % obj_name
  6495. with self.proc_container.new(_("Exporting SVG")) as proc:
  6496. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6497. # Determine bounding area for svg export
  6498. bounds = obj.bounds()
  6499. size = obj.size()
  6500. # Convert everything to strings for use in the xml doc
  6501. svgwidth = str(size[0])
  6502. svgheight = str(size[1])
  6503. minx = str(bounds[0])
  6504. miny = str(bounds[1] - size[1])
  6505. uom = obj.units.lower()
  6506. # Add a SVG Header and footer to the svg output from shapely
  6507. # The transform flips the Y Axis so that everything renders
  6508. # properly within svg apps such as inkscape
  6509. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6510. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6511. svg_header += 'width="' + svgwidth + uom + '" '
  6512. svg_header += 'height="' + svgheight + uom + '" '
  6513. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6514. svg_header += '<g transform="scale(1,-1)">'
  6515. svg_footer = '</g> </svg>'
  6516. svg_elem = svg_header + exported_svg + svg_footer
  6517. # Parse the xml through a xml parser just to add line feeds
  6518. # and to make it look more pretty for the output
  6519. svgcode = parse_xml_string(svg_elem)
  6520. svgcode = svgcode.toprettyxml()
  6521. try:
  6522. with open(filename, 'w') as fp:
  6523. fp.write(svgcode)
  6524. except PermissionError:
  6525. self.inform.emit('[WARNING] %s' %
  6526. _("Permission denied, saving not possible.\n"
  6527. "Most likely another app is holding the file open and not accessible."))
  6528. return 'fail'
  6529. if self.defaults["global_open_style"] is False:
  6530. self.file_opened.emit("SVG", filename)
  6531. self.file_saved.emit("SVG", filename)
  6532. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6533. def save_source_file(self, obj_name, filename, use_thread=True):
  6534. """
  6535. Exports a FlatCAM Object to an Gerber/Excellon file.
  6536. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6537. :param filename: Path to the Gerber file to save to.
  6538. :param use_thread: if to be run in a separate thread
  6539. :return:
  6540. """
  6541. self.defaults.report_usage("save source file()")
  6542. if filename is None:
  6543. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6544. is not None else self.defaults["global_last_folder"]
  6545. self.log.debug("save source file()")
  6546. obj = self.collection.get_by_name(obj_name)
  6547. file_string = StringIO(obj.source_file)
  6548. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6549. if file_string.getvalue() == '':
  6550. self.inform.emit('[ERROR_NOTCL] %s' %
  6551. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6552. return 'fail'
  6553. try:
  6554. with open(filename, 'w') as file:
  6555. file.writelines('G04*\n')
  6556. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6557. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6558. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6559. file.writelines('G04 Created on : %s*\n' % time_string)
  6560. for line in file_string:
  6561. file.writelines(line)
  6562. except PermissionError:
  6563. self.inform.emit('[WARNING] %s' %
  6564. _("Permission denied, saving not possible.\n"
  6565. "Most likely another app is holding the file open and not accessible."))
  6566. return 'fail'
  6567. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6568. """
  6569. Exports a Excellon Object to an Excellon file.
  6570. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6571. :param filename: Path to the Excellon file to save to.
  6572. :param local_use:
  6573. :param use_thread: if to be run in a separate thread
  6574. :return:
  6575. """
  6576. self.defaults.report_usage("export_excellon()")
  6577. if filename is None:
  6578. if self.defaults["global_last_save_folder"]:
  6579. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6580. else:
  6581. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6582. self.log.debug("export_excellon()")
  6583. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6584. self.defaults["excellon_exp_decimals"]
  6585. )
  6586. if local_use is None:
  6587. try:
  6588. obj = self.collection.get_by_name(str(obj_name))
  6589. except Exception:
  6590. return "Could not retrieve object: %s" % obj_name
  6591. else:
  6592. obj = local_use
  6593. if not isinstance(obj, ExcellonObject):
  6594. self.inform.emit('[ERROR_NOTCL] %s' %
  6595. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6596. return
  6597. # updated units
  6598. eunits = self.defaults["excellon_exp_units"]
  6599. ewhole = self.defaults["excellon_exp_integer"]
  6600. efract = self.defaults["excellon_exp_decimals"]
  6601. ezeros = self.defaults["excellon_exp_zeros"]
  6602. eformat = self.defaults["excellon_exp_format"]
  6603. slot_type = self.defaults["excellon_exp_slot_type"]
  6604. fc_units = self.defaults['units'].upper()
  6605. if fc_units == 'MM':
  6606. factor = 1 if eunits == 'METRIC' else 0.03937
  6607. else:
  6608. factor = 25.4 if eunits == 'METRIC' else 1
  6609. def make_excellon():
  6610. try:
  6611. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6612. header = 'M48\n'
  6613. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6614. (str(self.version), str(self.version_date))
  6615. header += ';Filename: %s' % str(obj_name) + '\n'
  6616. header += ';Created on : %s' % time_str + '\n'
  6617. if eformat == 'dec':
  6618. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6619. header += eunits + '\n'
  6620. for tool in obj.tools:
  6621. if eunits == 'METRIC':
  6622. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6623. tool=str(tool),
  6624. dec=2)
  6625. else:
  6626. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6627. tool=str(tool),
  6628. dec=4)
  6629. else:
  6630. if ezeros == 'LZ':
  6631. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6632. form='ndec', e_zeros='LZ', factor=factor,
  6633. slot_type=slot_type)
  6634. header += '%s,%s\n' % (eunits, 'LZ')
  6635. header += format_exc
  6636. for tool in obj.tools:
  6637. if eunits == 'METRIC':
  6638. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6639. tool=str(tool),
  6640. dec=2)
  6641. else:
  6642. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6643. tool=str(tool),
  6644. dec=4)
  6645. else:
  6646. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6647. form='ndec', e_zeros='TZ', factor=factor,
  6648. slot_type=slot_type)
  6649. header += '%s,%s\n' % (eunits, 'TZ')
  6650. header += format_exc
  6651. for tool in obj.tools:
  6652. if eunits == 'METRIC':
  6653. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6654. tool=str(tool),
  6655. dec=2)
  6656. else:
  6657. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6658. tool=str(tool),
  6659. dec=4)
  6660. header += '%\n'
  6661. footer = 'M30\n'
  6662. exported_excellon = header
  6663. exported_excellon += excellon_code
  6664. exported_excellon += footer
  6665. if local_use is None:
  6666. try:
  6667. with open(filename, 'w') as fp:
  6668. fp.write(exported_excellon)
  6669. except PermissionError:
  6670. self.inform.emit('[WARNING] %s' %
  6671. _("Permission denied, saving not possible.\n"
  6672. "Most likely another app is holding the file open and not accessible."))
  6673. return 'fail'
  6674. if self.defaults["global_open_style"] is False:
  6675. self.file_opened.emit("Excellon", filename)
  6676. self.file_saved.emit("Excellon", filename)
  6677. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6678. else:
  6679. return exported_excellon
  6680. except Exception as e:
  6681. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6682. return 'fail'
  6683. if use_thread is True:
  6684. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6685. def job_thread_exc(app_obj):
  6686. ret = make_excellon()
  6687. if ret == 'fail':
  6688. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6689. return
  6690. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6691. else:
  6692. eret = make_excellon()
  6693. if eret == 'fail':
  6694. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6695. return 'fail'
  6696. if local_use is not None:
  6697. return eret
  6698. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6699. """
  6700. Exports a Gerber Object to an Gerber file.
  6701. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6702. :param filename: Path to the Gerber file to save to.
  6703. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6704. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6705. :param use_thread: if to be run in a separate thread
  6706. :return:
  6707. """
  6708. self.defaults.report_usage("export_gerber()")
  6709. if filename is None:
  6710. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6711. is not None else self.defaults["global_last_folder"]
  6712. self.log.debug("export_gerber()")
  6713. if local_use is None:
  6714. try:
  6715. obj = self.collection.get_by_name(str(obj_name))
  6716. except Exception:
  6717. return "Could not retrieve object: %s" % obj_name
  6718. else:
  6719. obj = local_use
  6720. # updated units
  6721. gunits = self.defaults["gerber_exp_units"]
  6722. gwhole = self.defaults["gerber_exp_integer"]
  6723. gfract = self.defaults["gerber_exp_decimals"]
  6724. gzeros = self.defaults["gerber_exp_zeros"]
  6725. fc_units = self.defaults['units'].upper()
  6726. if fc_units == 'MM':
  6727. factor = 1 if gunits == 'MM' else 0.03937
  6728. else:
  6729. factor = 25.4 if gunits == 'MM' else 1
  6730. def make_gerber():
  6731. try:
  6732. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6733. header = 'G04*\n'
  6734. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6735. (str(self.version), str(self.version_date))
  6736. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6737. header += 'G04 Created on : %s*' % time_str + '\n'
  6738. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6739. header += "%MO{units}*%\n".format(units=gunits)
  6740. for apid in obj.apertures:
  6741. if obj.apertures[apid]['type'] == 'C':
  6742. header += "%ADD{apid}{type},{size}*%\n".format(
  6743. apid=str(apid),
  6744. type='C',
  6745. size=(factor * obj.apertures[apid]['size'])
  6746. )
  6747. elif obj.apertures[apid]['type'] == 'R':
  6748. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6749. apid=str(apid),
  6750. type='R',
  6751. width=(factor * obj.apertures[apid]['width']),
  6752. height=(factor * obj.apertures[apid]['height'])
  6753. )
  6754. elif obj.apertures[apid]['type'] == 'O':
  6755. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6756. apid=str(apid),
  6757. type='O',
  6758. width=(factor * obj.apertures[apid]['width']),
  6759. height=(factor * obj.apertures[apid]['height'])
  6760. )
  6761. header += '\n'
  6762. # obsolete units but some software may need it
  6763. if gunits == 'IN':
  6764. header += 'G70*\n'
  6765. else:
  6766. header += 'G71*\n'
  6767. # Absolute Mode
  6768. header += 'G90*\n'
  6769. header += 'G01*\n'
  6770. # positive polarity
  6771. header += '%LPD*%\n'
  6772. footer = 'M02*\n'
  6773. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6774. exported_gerber = header
  6775. exported_gerber += gerber_code
  6776. exported_gerber += footer
  6777. if local_use is None:
  6778. try:
  6779. with open(filename, 'w') as fp:
  6780. fp.write(exported_gerber)
  6781. except PermissionError:
  6782. self.inform.emit('[WARNING] %s' %
  6783. _("Permission denied, saving not possible.\n"
  6784. "Most likely another app is holding the file open and not accessible."))
  6785. return 'fail'
  6786. if self.defaults["global_open_style"] is False:
  6787. self.file_opened.emit("Gerber", filename)
  6788. self.file_saved.emit("Gerber", filename)
  6789. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6790. else:
  6791. return exported_gerber
  6792. except Exception as e:
  6793. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6794. return 'fail'
  6795. if use_thread is True:
  6796. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6797. def job_thread_grb(app_obj):
  6798. ret = make_gerber()
  6799. if ret == 'fail':
  6800. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6801. return
  6802. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6803. else:
  6804. gret = make_gerber()
  6805. if gret == 'fail':
  6806. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6807. return 'fail'
  6808. if local_use is not None:
  6809. return gret
  6810. def export_dxf(self, obj_name, filename, use_thread=True):
  6811. """
  6812. Exports a Geometry Object to an DXF file.
  6813. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6814. :param filename: Path to the DXF file to save to.
  6815. :param use_thread: if to be run in a separate thread
  6816. :return:
  6817. """
  6818. self.defaults.report_usage("export_dxf()")
  6819. if filename is None:
  6820. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6821. is not None else self.defaults["global_last_folder"]
  6822. self.log.debug("export_dxf()")
  6823. try:
  6824. obj = self.collection.get_by_name(str(obj_name))
  6825. except Exception:
  6826. # TODO: The return behavior has not been established... should raise exception?
  6827. return "Could not retrieve object: %s" % obj_name
  6828. def make_dxf():
  6829. try:
  6830. dxf_code = obj.export_dxf()
  6831. dxf_code.saveas(filename)
  6832. if self.defaults["global_open_style"] is False:
  6833. self.file_opened.emit("DXF", filename)
  6834. self.file_saved.emit("DXF", filename)
  6835. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6836. except Exception:
  6837. return 'fail'
  6838. if use_thread is True:
  6839. with self.proc_container.new(_("Exporting DXF")) as proc:
  6840. def job_thread_exc(app_obj):
  6841. ret_dxf_val = make_dxf()
  6842. if ret_dxf_val == 'fail':
  6843. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6844. return
  6845. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6846. else:
  6847. ret = make_dxf()
  6848. if ret == 'fail':
  6849. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6850. return
  6851. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6852. """
  6853. Adds a new Geometry Object to the projects and populates
  6854. it with shapes extracted from the SVG file.
  6855. :param plot: If True then the resulting object will be plotted on canvas
  6856. :param filename: Path to the SVG file.
  6857. :param geo_type: Type of FlatCAM object that will be created from SVG
  6858. :param outname: The name given to the resulting FlatCAM object
  6859. :return:
  6860. """
  6861. self.defaults.report_usage("import_svg()")
  6862. log.debug("App.import_svg()")
  6863. obj_type = ""
  6864. if geo_type is None or geo_type == "geometry":
  6865. obj_type = "geometry"
  6866. elif geo_type == "gerber":
  6867. obj_type = "gerber"
  6868. else:
  6869. self.inform.emit('[ERROR_NOTCL] %s' %
  6870. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6871. return
  6872. units = self.defaults['units'].upper()
  6873. def obj_init(geo_obj, app_obj):
  6874. geo_obj.import_svg(filename, obj_type, units=units)
  6875. geo_obj.multigeo = False
  6876. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6877. with self.proc_container.new(_("Importing SVG")) as proc:
  6878. # Object name
  6879. name = outname or filename.split('/')[-1].split('\\')[-1]
  6880. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6881. if ret == 'fail':
  6882. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6883. return 'fail'
  6884. # Register recent file
  6885. self.file_opened.emit("svg", filename)
  6886. # AppGUI feedback
  6887. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6888. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  6889. """
  6890. Adds a new Geometry Object to the projects and populates
  6891. it with shapes extracted from the DXF file.
  6892. :param filename: Path to the DXF file.
  6893. :param geo_type: Type of FlatCAM object that will be created from DXF
  6894. :param outname: Name for the imported Geometry
  6895. :param plot: If True then the resulting object will be plotted on canvas
  6896. :return:
  6897. """
  6898. self.defaults.report_usage("import_dxf()")
  6899. obj_type = ""
  6900. if geo_type is None or geo_type == "geometry":
  6901. obj_type = "geometry"
  6902. elif geo_type == "gerber":
  6903. obj_type = geo_type
  6904. else:
  6905. self.inform.emit('[ERROR_NOTCL] %s' %
  6906. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6907. return
  6908. units = self.defaults['units'].upper()
  6909. def obj_init(geo_obj, app_obj):
  6910. geo_obj.import_dxf(filename, obj_type, units=units)
  6911. geo_obj.multigeo = False
  6912. with self.proc_container.new(_("Importing DXF")):
  6913. # Object name
  6914. name = outname or filename.split('/')[-1].split('\\')[-1]
  6915. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6916. if ret == 'fail':
  6917. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6918. return 'fail'
  6919. # Register recent file
  6920. self.file_opened.emit("dxf", filename)
  6921. # AppGUI feedback
  6922. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6923. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  6924. """
  6925. Opens a Gerber file, parses it and creates a new object for
  6926. it in the program. Thread-safe.
  6927. :param outname: Name of the resulting object. None causes the
  6928. name to be that of the file. Str.
  6929. :param filename: Gerber file filename
  6930. :type filename: str
  6931. :param plot: boolean, to plot or not the resulting object
  6932. :param from_tcl: True if run from Tcl Shell
  6933. :return: None
  6934. """
  6935. # How the object should be initialized
  6936. def obj_init(gerber_obj, app_obj):
  6937. assert isinstance(gerber_obj, GerberObject), \
  6938. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  6939. # Opening the file happens here
  6940. try:
  6941. gerber_obj.parse_file(filename)
  6942. except IOError:
  6943. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  6944. return "fail"
  6945. except ParseError as err:
  6946. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  6947. app_obj.log.error(str(err))
  6948. return "fail"
  6949. except Exception as e:
  6950. log.debug("App.open_gerber() --> %s" % str(e))
  6951. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  6952. msg += traceback.format_exc()
  6953. app_obj.inform.emit(msg)
  6954. return "fail"
  6955. if gerber_obj.is_empty():
  6956. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  6957. _("Object is not Gerber file or empty. Aborting object creation."))
  6958. return "fail"
  6959. App.log.debug("open_gerber()")
  6960. with self.proc_container.new(_("Opening Gerber")):
  6961. # Object name
  6962. name = outname or filename.split('/')[-1].split('\\')[-1]
  6963. # # ## Object creation # ##
  6964. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6965. if ret_val == 'fail':
  6966. if from_tcl:
  6967. filename = self.defaults['global_tcl_path'] + '/' + name
  6968. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6969. if ret_val == 'fail':
  6970. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  6971. return 'fail'
  6972. # Register recent file
  6973. self.file_opened.emit("gerber", filename)
  6974. # AppGUI feedback
  6975. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6976. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  6977. """
  6978. Opens an Excellon file, parses it and creates a new object for
  6979. it in the program. Thread-safe.
  6980. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6981. :param filename: Excellon file filename
  6982. :type filename: str
  6983. :param plot: boolean, to plot or not the resulting object
  6984. :param from_tcl: True if run from Tcl Shell
  6985. :return: None
  6986. """
  6987. App.log.debug("open_excellon()")
  6988. # How the object should be initialized
  6989. def obj_init(excellon_obj, app_obj):
  6990. try:
  6991. ret = excellon_obj.parse_file(filename=filename)
  6992. if ret == "fail":
  6993. log.debug("Excellon parsing failed.")
  6994. self.inform.emit('[ERROR_NOTCL] %s' %
  6995. _("This is not Excellon file."))
  6996. return "fail"
  6997. except IOError:
  6998. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  6999. (_("Cannot open file"), filename))
  7000. log.debug("Could not open Excellon object.")
  7001. return "fail"
  7002. except Exception:
  7003. msg = '[ERROR_NOTCL] %s' % \
  7004. _("An internal error has occurred. See shell.\n")
  7005. msg += traceback.format_exc()
  7006. app_obj.inform.emit(msg)
  7007. return "fail"
  7008. ret = excellon_obj.create_geometry()
  7009. if ret == 'fail':
  7010. log.debug("Could not create geometry for Excellon object.")
  7011. return "fail"
  7012. for tool in excellon_obj.tools:
  7013. if excellon_obj.tools[tool]['solid_geometry']:
  7014. return
  7015. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7016. return "fail"
  7017. with self.proc_container.new(_("Opening Excellon.")):
  7018. # Object name
  7019. name = outname or filename.split('/')[-1].split('\\')[-1]
  7020. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7021. if ret_val == 'fail':
  7022. if from_tcl:
  7023. filename = self.defaults['global_tcl_path'] + '/' + name
  7024. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7025. if ret_val == 'fail':
  7026. self.inform.emit('[ERROR_NOTCL] %s' %
  7027. _('Open Excellon file failed. Probable not an Excellon file.'))
  7028. return
  7029. # Register recent file
  7030. self.file_opened.emit("excellon", filename)
  7031. # AppGUI feedback
  7032. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7033. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7034. """
  7035. Opens a G-gcode file, parses it and creates a new object for
  7036. it in the program. Thread-safe.
  7037. :param filename: G-code file filename
  7038. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7039. :param force_parsing:
  7040. :param plot: If True plot the object on canvas
  7041. :param from_tcl: True if run from Tcl Shell
  7042. :return: None
  7043. """
  7044. App.log.debug("open_gcode()")
  7045. # How the object should be initialized
  7046. def obj_init(job_obj, app_obj_):
  7047. """
  7048. :param job_obj: the resulting object
  7049. :type app_obj_: App
  7050. """
  7051. assert isinstance(app_obj_, App), \
  7052. "Initializer expected App, got %s" % type(app_obj_)
  7053. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7054. try:
  7055. f = open(filename)
  7056. gcode = f.read()
  7057. f.close()
  7058. except IOError:
  7059. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7060. return "fail"
  7061. job_obj.gcode = gcode
  7062. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7063. if gcode_ret == "fail":
  7064. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7065. return "fail"
  7066. job_obj.create_geometry()
  7067. with self.proc_container.new(_("Opening G-Code.")):
  7068. # Object name
  7069. name = outname or filename.split('/')[-1].split('\\')[-1]
  7070. # New object creation and file processing
  7071. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7072. if ret_val == 'fail':
  7073. if from_tcl:
  7074. filename = self.defaults['global_tcl_path'] + '/' + name
  7075. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7076. if ret_val == 'fail':
  7077. self.inform.emit('[ERROR_NOTCL] %s' %
  7078. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7079. "Try to load it from File menu.\n "
  7080. "Attempting to create a FlatCAM CNCJob Object from "
  7081. "G-Code file failed during processing"))
  7082. return "fail"
  7083. # Register recent file
  7084. self.file_opened.emit("cncjob", filename)
  7085. # AppGUI feedback
  7086. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7087. def open_hpgl2(self, filename, outname=None):
  7088. """
  7089. Opens a HPGL2 file, parses it and creates a new object for
  7090. it in the program. Thread-safe.
  7091. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7092. :param filename: HPGL2 file filename
  7093. :return: None
  7094. """
  7095. filename = filename
  7096. # How the object should be initialized
  7097. def obj_init(geo_obj, app_obj):
  7098. assert isinstance(geo_obj, GeometryObject), \
  7099. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7100. # Opening the file happens here
  7101. obj = HPGL2(self)
  7102. try:
  7103. HPGL2.parse_file(obj, filename)
  7104. except IOError:
  7105. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7106. return "fail"
  7107. except ParseError as err:
  7108. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7109. app_obj.log.error(str(err))
  7110. return "fail"
  7111. except Exception as e:
  7112. log.debug("App.open_hpgl2() --> %s" % str(e))
  7113. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7114. msg += traceback.format_exc()
  7115. app_obj.inform.emit(msg)
  7116. return "fail"
  7117. geo_obj.multigeo = True
  7118. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7119. geo_obj.tools = deepcopy(obj.tools)
  7120. geo_obj.source_file = deepcopy(obj.source_file)
  7121. del obj
  7122. if not geo_obj.solid_geometry:
  7123. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7124. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7125. return "fail"
  7126. App.log.debug("open_hpgl2()")
  7127. with self.proc_container.new(_("Opening HPGL2")):
  7128. # Object name
  7129. name = outname or filename.split('/')[-1].split('\\')[-1]
  7130. # # ## Object creation # ##
  7131. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7132. if ret == 'fail':
  7133. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7134. return 'fail'
  7135. # Register recent file
  7136. self.file_opened.emit("geometry", filename)
  7137. # AppGUI feedback
  7138. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7139. def open_script(self, filename, outname=None, silent=False):
  7140. """
  7141. Opens a Script file, parses it and creates a new object for
  7142. it in the program. Thread-safe.
  7143. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7144. :param filename: Script file filename
  7145. :param silent: If True there will be no messages printed to StatusBar
  7146. :return: None
  7147. """
  7148. def obj_init(script_obj, app_obj):
  7149. assert isinstance(script_obj, ScriptObject), \
  7150. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7151. if silent is False:
  7152. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7153. try:
  7154. script_obj.parse_file(filename)
  7155. except IOError:
  7156. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7157. return "fail"
  7158. except ParseError as err:
  7159. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7160. app_obj.log.error(str(err))
  7161. return "fail"
  7162. except Exception as e:
  7163. log.debug("App.open_script() -> %s" % str(e))
  7164. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7165. msg += traceback.format_exc()
  7166. app_obj.inform.emit(msg)
  7167. return "fail"
  7168. App.log.debug("open_script()")
  7169. with self.proc_container.new(_("Opening TCL Script...")):
  7170. # Object name
  7171. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7172. # Object creation
  7173. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7174. if ret_val == 'fail':
  7175. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7176. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7177. if ret_val == 'fail':
  7178. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7179. return 'fail'
  7180. # Register recent file
  7181. self.file_opened.emit("script", filename)
  7182. # AppGUI feedback
  7183. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7184. def open_config_file(self, filename, run_from_arg=None):
  7185. """
  7186. Loads a config file from the specified file.
  7187. :param filename: Name of the file from which to load.
  7188. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7189. :return: None
  7190. """
  7191. App.log.debug("Opening config file: " + filename)
  7192. if run_from_arg:
  7193. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7194. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7195. _("Opening FlatCAM Config file.")),
  7196. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7197. color=QtGui.QColor("gray"))
  7198. # # add the tab if it was closed
  7199. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7200. # # first clear previous text in text editor (if any)
  7201. # self.ui.text_editor_tab.code_editor.clear()
  7202. #
  7203. # # Switch plot_area to CNCJob tab
  7204. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7205. # close the Code editor if already open
  7206. if self.toggle_codeeditor:
  7207. self.on_toggle_code_editor()
  7208. self.on_toggle_code_editor()
  7209. try:
  7210. if filename:
  7211. f = QtCore.QFile(filename)
  7212. if f.open(QtCore.QIODevice.ReadOnly):
  7213. stream = QtCore.QTextStream(f)
  7214. code_edited = stream.readAll()
  7215. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7216. f.close()
  7217. except IOError:
  7218. App.log.error("Failed to open config file: %s" % filename)
  7219. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7220. (_("Failed to open config file"), filename))
  7221. return
  7222. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7223. """
  7224. Loads a project from the specified file.
  7225. 1) Loads and parses file
  7226. 2) Registers the file as recently opened.
  7227. 3) Calls on_file_new()
  7228. 4) Updates options
  7229. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7230. 6) Calls plot_all() if plot=True
  7231. :param filename: Name of the file from which to load.
  7232. :param run_from_arg: True if run for arguments
  7233. :param plot: If True plot all objects in the project
  7234. :param cli: Run from command line
  7235. :param from_tcl: True if run from Tcl Sehll
  7236. :return: None
  7237. """
  7238. App.log.debug("Opening project: " + filename)
  7239. # block autosaving while a project is loaded
  7240. self.block_autosave = True
  7241. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7242. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7243. if cli is None:
  7244. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7245. if run_from_arg:
  7246. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7247. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7248. _("Opening FlatCAM Project file.")),
  7249. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7250. color=QtGui.QColor("gray"))
  7251. # Open and parse an uncompressed Project file
  7252. try:
  7253. f = open(filename, 'r')
  7254. except IOError:
  7255. if from_tcl:
  7256. name = filename.split('/')[-1].split('\\')[-1]
  7257. filename = self.defaults['global_tcl_path'] + '/' + name
  7258. try:
  7259. f = open(filename, 'r')
  7260. except IOError:
  7261. log.error("Failed to open project file: %s" % filename)
  7262. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7263. return
  7264. else:
  7265. log.error("Failed to open project file: %s" % filename)
  7266. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7267. return
  7268. try:
  7269. d = json.load(f, object_hook=dict2obj)
  7270. except Exception as e:
  7271. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7272. (filename, str(e)))
  7273. f.close()
  7274. # Open and parse a compressed Project file
  7275. try:
  7276. with lzma.open(filename) as f:
  7277. file_content = f.read().decode('utf-8')
  7278. d = json.loads(file_content, object_hook=dict2obj)
  7279. except Exception as e:
  7280. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7281. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7282. return
  7283. # Clear the current project
  7284. # # NOT THREAD SAFE # ##
  7285. if run_from_arg is True:
  7286. pass
  7287. elif cli is True:
  7288. self.delete_selection_shape()
  7289. else:
  7290. self.on_file_new()
  7291. # Project options
  7292. self.options.update(d['options'])
  7293. self.project_filename = filename
  7294. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7295. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7296. if cli is None:
  7297. self.set_screen_units(self.options["units"])
  7298. # Re create objects
  7299. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7300. for obj in d['objs']:
  7301. try:
  7302. def obj_init(obj_inst, app_inst):
  7303. obj_inst.from_dict(obj)
  7304. App.log.debug("Recreating from opened project an %s object: %s" %
  7305. (obj['kind'].capitalize(), obj['options']['name']))
  7306. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7307. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7308. if cli is None:
  7309. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7310. obj['kind'].upper(),
  7311. obj['options']['name']
  7312. )
  7313. )
  7314. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7315. except Exception as e:
  7316. print('App.open_project() --> ' + str(e))
  7317. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7318. self.should_we_save = False
  7319. self.file_opened.emit("project", filename)
  7320. # restore autosaving after a project was loaded
  7321. self.block_autosave = False
  7322. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7323. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7324. if cli is None:
  7325. self.set_ui_title(name=self.project_filename)
  7326. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7327. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7328. """
  7329. Re-generates all plots from all objects.
  7330. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7331. :param muted: if True don't print messages
  7332. :param use_thread: if True will use threading for plotting the objects
  7333. :return: None
  7334. """
  7335. self.log.debug("Plot_all()")
  7336. if muted is not True:
  7337. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7338. for plot_obj in self.collection.get_list():
  7339. def worker_task(obj):
  7340. with self.proc_container.new("Plotting"):
  7341. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7342. if fit_view is True:
  7343. self.app_obj.object_plotted.emit(obj)
  7344. if use_thread is True:
  7345. # Send to worker
  7346. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7347. else:
  7348. worker_task(plot_obj)
  7349. def register_folder(self, filename):
  7350. """
  7351. Register the last folder used by the app to open something
  7352. :param filename: the last folder is extracted from the filename
  7353. :return: None
  7354. """
  7355. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7356. def register_save_folder(self, filename):
  7357. """
  7358. Register the last folder used by the app to save something
  7359. :param filename: the last folder is extracted from the filename
  7360. :return: None
  7361. """
  7362. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7363. # def set_progress_bar(self, percentage, text=""):
  7364. # """
  7365. # Set a progress bar to a value (percentage)
  7366. #
  7367. # :param percentage: Value set to the progressbar
  7368. # :param text: Not used
  7369. # :return: None
  7370. # """
  7371. # self.ui.progress_bar.setValue(int(percentage))
  7372. def setup_recent_items(self):
  7373. """
  7374. Setup a dictionary with the recent files accessed, organized by type
  7375. :return:
  7376. """
  7377. icons = {
  7378. "gerber": self.resource_location + "/flatcam_icon16.png",
  7379. "excellon": self.resource_location + "/drill16.png",
  7380. 'geometry': self.resource_location + "/geometry16.png",
  7381. "cncjob": self.resource_location + "/cnc16.png",
  7382. "script": self.resource_location + "/script_new24.png",
  7383. "document": self.resource_location + "/notes16_1.png",
  7384. "project": self.resource_location + "/project16.png",
  7385. "svg": self.resource_location + "/geometry16.png",
  7386. "dxf": self.resource_location + "/dxf16.png",
  7387. "pdf": self.resource_location + "/pdf32.png",
  7388. "image": self.resource_location + "/image16.png"
  7389. }
  7390. try:
  7391. image_opener = self.image_tool.import_image
  7392. except AttributeError:
  7393. image_opener = None
  7394. openers = {
  7395. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7396. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7397. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7398. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7399. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7400. "document": None,
  7401. 'project': self.open_project,
  7402. 'svg': self.import_svg,
  7403. 'dxf': self.import_dxf,
  7404. 'image': image_opener,
  7405. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7406. }
  7407. # Open recent file for files
  7408. try:
  7409. f = open(self.data_path + '/recent.json')
  7410. except IOError:
  7411. App.log.error("Failed to load recent item list.")
  7412. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7413. return
  7414. try:
  7415. self.recent = json.load(f)
  7416. except json.errors.JSONDecodeError:
  7417. App.log.error("Failed to parse recent item list.")
  7418. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7419. f.close()
  7420. return
  7421. f.close()
  7422. # Open recent file for projects
  7423. try:
  7424. fp = open(self.data_path + '/recent_projects.json')
  7425. except IOError:
  7426. App.log.error("Failed to load recent project item list.")
  7427. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7428. return
  7429. try:
  7430. self.recent_projects = json.load(fp)
  7431. except json.errors.JSONDecodeError:
  7432. App.log.error("Failed to parse recent project item list.")
  7433. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7434. fp.close()
  7435. return
  7436. fp.close()
  7437. # Closure needed to create callbacks in a loop.
  7438. # Otherwise late binding occurs.
  7439. def make_callback(func, fname):
  7440. def opener():
  7441. func(fname)
  7442. return opener
  7443. def reset_recent_files():
  7444. # Reset menu
  7445. self.ui.recent.clear()
  7446. self.recent = []
  7447. try:
  7448. ff = open(self.data_path + '/recent.json', 'w')
  7449. except IOError:
  7450. App.log.error("Failed to open recent items file for writing.")
  7451. return
  7452. json.dump(self.recent, ff)
  7453. def reset_recent_projects():
  7454. # Reset menu
  7455. self.ui.recent_projects.clear()
  7456. self.recent_projects = []
  7457. try:
  7458. frp = open(self.data_path + '/recent_projects.json', 'w')
  7459. except IOError:
  7460. App.log.error("Failed to open recent projects items file for writing.")
  7461. return
  7462. json.dump(self.recent, frp)
  7463. # Reset menu
  7464. self.ui.recent.clear()
  7465. self.ui.recent_projects.clear()
  7466. # Create menu items for projects
  7467. for recent in self.recent_projects:
  7468. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7469. if recent['kind'] == 'project':
  7470. try:
  7471. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7472. # Attach callback
  7473. o = make_callback(openers[recent["kind"]], recent['filename'])
  7474. action.triggered.connect(o)
  7475. self.ui.recent_projects.addAction(action)
  7476. except KeyError:
  7477. App.log.error("Unsupported file type: %s" % recent["kind"])
  7478. # Last action in Recent Files menu is one that Clear the content
  7479. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7480. (_("Clear Recent projects")), self)
  7481. clear_action_proj.triggered.connect(reset_recent_projects)
  7482. self.ui.recent_projects.addSeparator()
  7483. self.ui.recent_projects.addAction(clear_action_proj)
  7484. # Create menu items for files
  7485. for recent in self.recent:
  7486. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7487. if recent['kind'] != 'project':
  7488. try:
  7489. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7490. # Attach callback
  7491. o = make_callback(openers[recent["kind"]], recent['filename'])
  7492. action.triggered.connect(o)
  7493. self.ui.recent.addAction(action)
  7494. except KeyError:
  7495. App.log.error("Unsupported file type: %s" % recent["kind"])
  7496. # Last action in Recent Files menu is one that Clear the content
  7497. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7498. (_("Clear Recent files")), self)
  7499. clear_action.triggered.connect(reset_recent_files)
  7500. self.ui.recent.addSeparator()
  7501. self.ui.recent.addAction(clear_action)
  7502. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7503. # self.ui.menufilerecent.set_submenu(recent_menu)
  7504. # recent_menu.show_all()
  7505. # self.ui.recent.show()
  7506. self.log.debug("Recent items list has been populated.")
  7507. def setup_component_editor(self):
  7508. """
  7509. Default text for the Selected tab when is not taken by the Object UI.
  7510. :return:
  7511. """
  7512. # label = QtWidgets.QLabel("Choose an item from Project")
  7513. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7514. sel_title = QtWidgets.QTextEdit(
  7515. _('<b>Shortcut Key List</b>'))
  7516. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7517. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7518. f_settings = QSettings("Open Source", "FlatCAM")
  7519. if f_settings.contains("notebook_font_size"):
  7520. fsize = f_settings.value('notebook_font_size', type=int)
  7521. else:
  7522. fsize = 12
  7523. tsize = fsize + int(fsize / 2)
  7524. # selected_text = (_('''
  7525. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7526. # </p>
  7527. #
  7528. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7529. # The normal flow when working in FlatCAM is the following:</span></p>
  7530. #
  7531. # <ol>
  7532. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7533. # file into
  7534. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7535. # even dragging and dropping the files on the AppGUI.<br />
  7536. # <br />
  7537. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7538. # drop of the
  7539. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7540. # &nbsp;</li>
  7541. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7542. # and then
  7543. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7544. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7545. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7546. # <br />
  7547. # If the selection of the object is done on the canvas by single click instead, and the
  7548. # <strong>SELECTED TAB</strong>
  7549. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7550. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7551. # it even if it was out of focus.<br />
  7552. # <br />
  7553. # You can change the parameters in this screen and the flow direction is like this:<br />
  7554. # <br />
  7555. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7556. # <strong> Geometry Object
  7557. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7558. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7559. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7560. # </ol>
  7561. #
  7562. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7563. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7564. # <strong>F3</strong>.</span></p>
  7565. #
  7566. # ''').format(fsize=fsize, tsize=tsize))
  7567. selected_text = '''
  7568. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7569. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7570. {s1}</span></p>
  7571. <ol>
  7572. <li><span style="font-size:{fsize}px">{s2}<br />
  7573. <br />
  7574. {s3}</span><br />
  7575. &nbsp;</li>
  7576. <li><span style="font-size:{fsize}px">{s4}<br />
  7577. &nbsp;</li>
  7578. <br />
  7579. <li><span style="font-size:{fsize}px">{s5}<br />
  7580. &nbsp;</li>
  7581. <br />
  7582. <li><span style="font-size:{fsize}px">{s6}<br />
  7583. <br />
  7584. {s7}</span></li>
  7585. </ol>
  7586. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7587. '''.format(
  7588. title=_("Selected Tab - Choose an Item from Project Tab"),
  7589. subtitle=_("Details"),
  7590. s1=_("The normal flow when working in FlatCAM is the following:"),
  7591. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  7592. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7593. "files on the AppGUI."),
  7594. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  7595. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  7596. "actions offered within the app."),
  7597. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7598. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7599. "SELECTED TAB will be updated with the object properties according to its kind: "
  7600. "Gerber, Excellon, Geometry or CNCJob object."),
  7601. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7602. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7603. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7604. "the SELECTED TAB and populate it even if it was out of focus."),
  7605. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7606. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7607. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7608. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7609. "(again, done in SELECTED TAB) --> Save GCode."),
  7610. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7611. "or through its own key shortcut: <b>F3</b>."),
  7612. tsize=tsize,
  7613. fsize=fsize
  7614. )
  7615. sel_title.setText(selected_text)
  7616. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7617. self.ui.selected_scroll_area.setWidget(sel_title)
  7618. def setup_obj_classes(self):
  7619. """
  7620. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7621. class.
  7622. :return: None
  7623. """
  7624. FlatCAMObj.app = self
  7625. ObjectCollection.app = self
  7626. Gerber.app = self
  7627. Excellon.app = self
  7628. Geometry.app = self
  7629. CNCjob.app = self
  7630. FCProcess.app = self
  7631. FCProcessContainer.app = self
  7632. OptionsGroupUI.app = self
  7633. def version_check(self):
  7634. """
  7635. Checks for the latest version of the program. Alerts the
  7636. user if theirs is outdated. This method is meant to be run
  7637. in a separate thread.
  7638. :return: None
  7639. """
  7640. self.log.debug("version_check()")
  7641. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7642. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7643. App.version_url,
  7644. str(self.defaults['global_serial']),
  7645. str(self.version),
  7646. str(self.os),
  7647. urllib.parse.urlencode(self.defaults["global_stats"])
  7648. )
  7649. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7650. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7651. # urllib.parse.urlencode(self.defaults["global_stats"])
  7652. else:
  7653. # no_stats dict; just so it won't break things on website
  7654. no_ststs_dict = {}
  7655. no_ststs_dict["global_ststs"] = {}
  7656. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7657. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7658. App.log.debug("Checking for updates @ %s" % full_url)
  7659. # ## Get the data
  7660. try:
  7661. f = urllib.request.urlopen(full_url)
  7662. except Exception:
  7663. # App.log.warning("Failed checking for latest version. Could not connect.")
  7664. self.log.warning("Failed checking for latest version. Could not connect.")
  7665. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7666. return
  7667. try:
  7668. data = json.load(f)
  7669. except Exception as e:
  7670. App.log.error("Could not parse information about latest version.")
  7671. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7672. App.log.debug("json.load(): %s" % str(e))
  7673. f.close()
  7674. return
  7675. f.close()
  7676. # ## Latest version?
  7677. if self.version >= data["version"]:
  7678. App.log.debug("FlatCAM is up to date!")
  7679. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7680. return
  7681. App.log.debug("Newer version available.")
  7682. self.message.emit(
  7683. _("Newer Version Available"),
  7684. '%s<br><br>><b>%s</b><br>%s' % (
  7685. _("There is a newer version of FlatCAM available for download:"),
  7686. str(data["name"]),
  7687. str(data["message"])
  7688. ),
  7689. _("info")
  7690. )
  7691. def on_plotcanvas_setup(self, container=None):
  7692. """
  7693. This is doing the setup for the plot area (canvas).
  7694. :param container: QT Widget where to install the canvas
  7695. :return: None
  7696. """
  7697. if container:
  7698. plot_container = container
  7699. else:
  7700. plot_container = self.ui.right_layout
  7701. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7702. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7703. self.is_legacy = True
  7704. self.defaults["global_graphic_engine"] = "2D"
  7705. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7706. else:
  7707. try:
  7708. self.plotcanvas = PlotCanvas(plot_container, self)
  7709. except Exception as er:
  7710. msg_txt = traceback.format_exc()
  7711. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7712. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7713. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7714. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7715. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7716. msg += msg_txt
  7717. self.inform.emit(msg)
  7718. return 'fail'
  7719. # So it can receive key presses
  7720. self.plotcanvas.native.setFocus()
  7721. if self.is_legacy is False:
  7722. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7723. # Set the mouse button for panning
  7724. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7725. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7726. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7727. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7728. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7729. # Keys over plot enabled
  7730. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7731. if self.defaults['global_cursor_type'] == 'small':
  7732. self.app_cursor = self.plotcanvas.new_cursor()
  7733. else:
  7734. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7735. if self.ui.grid_snap_btn.isChecked():
  7736. self.app_cursor.enabled = True
  7737. else:
  7738. self.app_cursor.enabled = False
  7739. if self.is_legacy is False:
  7740. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7741. else:
  7742. # will use the default Matplotlib axes
  7743. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7744. def on_zoom_fit(self):
  7745. """
  7746. Callback for zoom-fit request. This can be either from the corresponding
  7747. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7748. with axes limits from the geometry bounds of all objects.
  7749. :return: None
  7750. """
  7751. if self.is_legacy is False:
  7752. self.plotcanvas.fit_view()
  7753. else:
  7754. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7755. width = xmax - xmin
  7756. height = ymax - ymin
  7757. xmin -= 0.05 * width
  7758. xmax += 0.05 * width
  7759. ymin -= 0.05 * height
  7760. ymax += 0.05 * height
  7761. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7762. def on_zoom_in(self):
  7763. """
  7764. Callback for zoom-in request.
  7765. :return:
  7766. """
  7767. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7768. def on_zoom_out(self):
  7769. """
  7770. Callback for zoom-out request.
  7771. :return:
  7772. """
  7773. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7774. def disable_all_plots(self):
  7775. self.defaults.report_usage("disable_all_plots()")
  7776. self.disable_plots(self.collection.get_list())
  7777. self.inform.emit('[success] %s' %
  7778. _("All plots disabled."))
  7779. def disable_other_plots(self):
  7780. self.defaults.report_usage("disable_other_plots()")
  7781. self.disable_plots(self.collection.get_non_selected())
  7782. self.inform.emit('[success] %s' %
  7783. _("All non selected plots disabled."))
  7784. def enable_all_plots(self):
  7785. self.defaults.report_usage("enable_all_plots()")
  7786. self.enable_plots(self.collection.get_list())
  7787. self.inform.emit('[success] %s' %
  7788. _("All plots enabled."))
  7789. def on_enable_sel_plots(self):
  7790. log.debug("App.on_enable_sel_plot()")
  7791. object_list = self.collection.get_selected()
  7792. self.enable_plots(objects=object_list)
  7793. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7794. def on_disable_sel_plots(self):
  7795. log.debug("App.on_disable_sel_plot()")
  7796. # self.inform.emit(_("Disabling plots ..."))
  7797. object_list = self.collection.get_selected()
  7798. self.disable_plots(objects=object_list)
  7799. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7800. def enable_plots(self, objects):
  7801. """
  7802. Enable plots
  7803. :param objects: list of Objects to be enabled
  7804. :return:
  7805. """
  7806. log.debug("Enabling plots ...")
  7807. # self.inform.emit(_("Working ..."))
  7808. for obj in objects:
  7809. if obj.options['plot'] is False:
  7810. obj.options.set_change_callback(lambda x: None)
  7811. obj.options['plot'] = True
  7812. try:
  7813. # only the Gerber obj has on_plot_cb_click() method
  7814. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7815. # disable this cb while disconnected,
  7816. # in case the operation takes time the user is not allowed to change it
  7817. obj.ui.plot_cb.setDisabled(True)
  7818. except AttributeError:
  7819. pass
  7820. obj.set_form_item("plot")
  7821. try:
  7822. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7823. obj.ui.plot_cb.setDisabled(False)
  7824. except AttributeError:
  7825. pass
  7826. obj.options.set_change_callback(obj.on_options_change)
  7827. def worker_task(objs):
  7828. with self.proc_container.new(_("Enabling plots ...")):
  7829. for plot_obj in objs:
  7830. # obj.options['plot'] = True
  7831. if isinstance(plot_obj, CNCJobObject):
  7832. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7833. else:
  7834. plot_obj.plot(visible=True)
  7835. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7836. def disable_plots(self, objects):
  7837. """
  7838. Disables plots
  7839. :param objects: list of Objects to be disabled
  7840. :return:
  7841. """
  7842. # if no objects selected then do nothing
  7843. if not self.collection.get_selected():
  7844. return
  7845. log.debug("Disabling plots ...")
  7846. # self.inform.emit(_("Working ..."))
  7847. for obj in objects:
  7848. if obj.options['plot'] is True:
  7849. obj.options.set_change_callback(lambda x: None)
  7850. obj.options['plot'] = False
  7851. try:
  7852. # only the Gerber obj has on_plot_cb_click() method
  7853. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7854. obj.ui.plot_cb.setDisabled(True)
  7855. except AttributeError:
  7856. pass
  7857. obj.set_form_item("plot")
  7858. try:
  7859. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7860. obj.ui.plot_cb.setDisabled(False)
  7861. except AttributeError:
  7862. pass
  7863. obj.options.set_change_callback(obj.on_options_change)
  7864. try:
  7865. self.delete_selection_shape()
  7866. except Exception as e:
  7867. log.debug("App.disable_plots() --> %s" % str(e))
  7868. def worker_task(objs):
  7869. with self.proc_container.new(_("Disabling plots ...")):
  7870. for plot_obj in objs:
  7871. # obj.options['plot'] = True
  7872. if isinstance(plot_obj, CNCJobObject):
  7873. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7874. else:
  7875. plot_obj.plot(visible=False)
  7876. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7877. def toggle_plots(self, objects):
  7878. """
  7879. Toggle plots visibility
  7880. :param objects: list of Objects for which to be toggled the visibility
  7881. :return: None
  7882. """
  7883. # if no objects selected then do nothing
  7884. if not self.collection.get_selected():
  7885. return
  7886. log.debug("Toggling plots ...")
  7887. self.inform.emit(_("Working ..."))
  7888. for obj in objects:
  7889. if obj.options['plot'] is False:
  7890. obj.options['plot'] = True
  7891. else:
  7892. obj.options['plot'] = False
  7893. self.app_obj.plots_updated.emit()
  7894. def clear_plots(self):
  7895. """
  7896. Clear the plots
  7897. :return: None
  7898. """
  7899. objects = self.collection.get_list()
  7900. for obj in objects:
  7901. obj.clear(obj == objects[-1])
  7902. # Clear pool to free memory
  7903. self.clear_pool()
  7904. def on_set_color_action_triggered(self):
  7905. """
  7906. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  7907. :return:
  7908. """
  7909. new_color = self.defaults['gerber_plot_fill']
  7910. clicked_action = self.sender()
  7911. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  7912. act_name = clicked_action.text()
  7913. sel_obj_list = self.collection.get_selected()
  7914. if not sel_obj_list:
  7915. return
  7916. # a default value, I just chose this one
  7917. alpha_level = 'BF'
  7918. for sel_obj in sel_obj_list:
  7919. if sel_obj.kind == 'excellon':
  7920. alpha_level = str(hex(
  7921. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  7922. elif sel_obj.kind == 'gerber':
  7923. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  7924. elif sel_obj.kind == 'geometry':
  7925. alpha_level = 'FF'
  7926. else:
  7927. log.debug(
  7928. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  7929. continue
  7930. sel_obj.alpha_level = alpha_level
  7931. if act_name == _('Red'):
  7932. new_color = '#FF0000' + alpha_level
  7933. if act_name == _('Blue'):
  7934. new_color = '#0000FF' + alpha_level
  7935. if act_name == _('Yellow'):
  7936. new_color = '#FFDF00' + alpha_level
  7937. if act_name == _('Green'):
  7938. new_color = '#00FF00' + alpha_level
  7939. if act_name == _('Purple'):
  7940. new_color = '#FF00FF' + alpha_level
  7941. if act_name == _('Brown'):
  7942. new_color = '#A52A2A' + alpha_level
  7943. if act_name == _('White'):
  7944. new_color = '#FFFFFF' + alpha_level
  7945. if act_name == _('Black'):
  7946. new_color = '#000000' + alpha_level
  7947. if act_name == _('Custom'):
  7948. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  7949. c_dialog = QtWidgets.QColorDialog()
  7950. plot_fill_color = c_dialog.getColor(initial=new_color)
  7951. if plot_fill_color.isValid() is False:
  7952. return
  7953. new_color = str(plot_fill_color.name()) + alpha_level
  7954. if act_name == _("Default"):
  7955. for sel_obj in sel_obj_list:
  7956. if sel_obj.kind == 'excellon':
  7957. new_color = self.defaults['excellon_plot_fill']
  7958. new_line_color = self.defaults['excellon_plot_line']
  7959. elif sel_obj.kind == 'gerber':
  7960. new_color = self.defaults['gerber_plot_fill']
  7961. new_line_color = self.defaults['gerber_plot_line']
  7962. elif sel_obj.kind == 'geometry':
  7963. new_color = self.defaults['geometry_plot_line']
  7964. new_line_color = self.defaults['geometry_plot_line']
  7965. else:
  7966. log.debug(
  7967. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  7968. continue
  7969. sel_obj.fill_color = new_color
  7970. sel_obj.outline_color = new_line_color
  7971. sel_obj.shapes.redraw(
  7972. update_colors=(new_color, new_line_color)
  7973. )
  7974. return
  7975. if act_name == _("Opacity"):
  7976. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  7977. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  7978. if ok_button:
  7979. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  7980. for sel_obj in sel_obj_list:
  7981. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  7982. sel_obj.shapes.redraw(
  7983. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  7984. )
  7985. return
  7986. new_line_color = color_variant(new_color[:7], 0.7)
  7987. if act_name == _("White"):
  7988. new_line_color = color_variant("#dedede", 0.7)
  7989. for sel_obj in sel_obj_list:
  7990. sel_obj.fill_color = new_color
  7991. sel_obj.outline_color = new_line_color
  7992. sel_obj.shapes.redraw(
  7993. update_colors=(new_color, new_line_color)
  7994. )
  7995. def generate_cnc_job(self, objects):
  7996. """
  7997. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  7998. :param objects: Selected objects in the Project Tab
  7999. :return:
  8000. """
  8001. self.defaults.report_usage("generate_cnc_job()")
  8002. # for obj in objects:
  8003. # obj.generatecncjob()
  8004. for obj in objects:
  8005. obj.on_generatecnc_button_click()
  8006. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8007. """
  8008. Saves the current project to the specified file.
  8009. :param filename: Name of the file in which to save.
  8010. :type filename: str
  8011. :param quit_action: if the project saving will be followed by an app quit; boolean
  8012. :param silent: if True will not display status messages
  8013. :param from_tcl True is run from Tcl Shell
  8014. :return: None
  8015. """
  8016. self.log.debug("save_project()")
  8017. self.save_in_progress = True
  8018. with self.proc_container.new(_("Saving FlatCAM Project")):
  8019. # Capture the latest changes
  8020. # Current object
  8021. try:
  8022. current_object = self.collection.get_active()
  8023. if current_object:
  8024. current_object.read_form()
  8025. except Exception as e:
  8026. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8027. pass
  8028. # Serialize the whole project
  8029. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8030. "options": self.options,
  8031. "version": self.version}
  8032. if self.defaults["global_save_compressed"] is True:
  8033. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8034. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8035. # # Write
  8036. f.write(g)
  8037. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8038. else:
  8039. # Open file
  8040. try:
  8041. f = open(filename, 'w')
  8042. except IOError:
  8043. App.log.error("Failed to open file for saving: %s", filename)
  8044. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8045. return
  8046. # Write
  8047. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8048. f.close()
  8049. # verification of the saved project
  8050. # Open and parse
  8051. try:
  8052. saved_f = open(filename, 'r')
  8053. except IOError:
  8054. if silent is False:
  8055. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8056. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8057. return
  8058. try:
  8059. saved_d = json.load(saved_f, object_hook=dict2obj)
  8060. except Exception:
  8061. if silent is False:
  8062. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8063. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8064. f.close()
  8065. return
  8066. saved_f.close()
  8067. if silent is False:
  8068. if 'version' in saved_d:
  8069. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8070. else:
  8071. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8072. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8073. tb_settings = QSettings("Open Source", "FlatCAM")
  8074. lock_state = self.ui.lock_action.isChecked()
  8075. tb_settings.setValue('toolbar_lock', lock_state)
  8076. # This will write the setting to the platform specific storage.
  8077. del tb_settings
  8078. # if quit:
  8079. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8080. # t.start()
  8081. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8082. def start_delayed_quit(self, delay, filename, should_quit=None):
  8083. """
  8084. :param delay: period of checking if project file size is more than zero; in seconds
  8085. :param filename: the name of the project file to be checked periodically for size more than zero
  8086. :param should_quit: if the task finished will be followed by an app quit; boolean
  8087. :return:
  8088. """
  8089. to_quit = should_quit
  8090. self.save_timer = QtCore.QTimer()
  8091. self.save_timer.setInterval(delay)
  8092. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8093. self.save_timer.start()
  8094. def check_project_file_size(self, filename, should_quit=None):
  8095. """
  8096. :param filename: the name of the project file to be checked periodically for size more than zero
  8097. :param should_quit: will quit the app if True; boolean
  8098. :return:
  8099. """
  8100. try:
  8101. if os.stat(filename).st_size > 0:
  8102. self.save_in_progress = False
  8103. self.save_timer.stop()
  8104. if should_quit:
  8105. self.app_quit.emit()
  8106. except Exception:
  8107. traceback.print_exc()
  8108. def save_project_auto(self):
  8109. """
  8110. Called periodically to save the project.
  8111. 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
  8112. # progress.
  8113. :return:
  8114. """
  8115. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8116. self.on_file_saveproject()
  8117. def save_project_auto_update(self):
  8118. """
  8119. Update the auto save time interval value.
  8120. :return:
  8121. """
  8122. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8123. try:
  8124. if self.autosave_timer.isActive():
  8125. self.autosave_timer.stop()
  8126. except Exception:
  8127. pass
  8128. if self.defaults['global_autosave'] is True:
  8129. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8130. self.autosave_timer.start()
  8131. def on_options_app2project(self):
  8132. """
  8133. Callback for Options->Transfer Options->App=>Project. Copies options
  8134. from application defaults to project defaults.
  8135. :return: None
  8136. """
  8137. self.defaults.report_usage("on_options_app2project")
  8138. self.preferencesUiManager.defaults_read_form()
  8139. self.options.update(self.defaults)
  8140. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8141. """
  8142. Shows a message on the FlatCAM Shell
  8143. :param msg: Message to display.
  8144. :param show: Opens the shell.
  8145. :param error: Shows the message as an error.
  8146. :param warning: Shows the message as an warning.
  8147. :param success: Shows the message as an success.
  8148. :param selected: Indicate that something was selected on canvas
  8149. :return: None
  8150. """
  8151. if show:
  8152. self.ui.shell_dock.show()
  8153. try:
  8154. if error:
  8155. self.shell.append_error(msg + "\n")
  8156. elif warning:
  8157. self.shell.append_warning(msg + "\n")
  8158. elif success:
  8159. self.shell.append_success(msg + "\n")
  8160. elif selected:
  8161. self.shell.append_selected(msg + "\n")
  8162. else:
  8163. self.shell.append_output(msg + "\n")
  8164. except AttributeError:
  8165. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8166. class ArgsThread(QtCore.QObject):
  8167. open_signal = pyqtSignal(list)
  8168. start = pyqtSignal()
  8169. stop = pyqtSignal()
  8170. if sys.platform == 'win32':
  8171. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8172. else:
  8173. address = ('/tmp/testipc', 'AF_UNIX')
  8174. def __init__(self):
  8175. super(ArgsThread, self).__init__()
  8176. self.listener = None
  8177. self.thread_exit = False
  8178. self.start.connect(self.run)
  8179. self.stop.connect(self.close_listener)
  8180. def my_loop(self, address):
  8181. try:
  8182. self.listener = Listener(*address)
  8183. while self.thread_exit is False:
  8184. conn = self.listener.accept()
  8185. self.serve(conn)
  8186. except socket.error:
  8187. try:
  8188. conn = Client(*address)
  8189. conn.send(sys.argv)
  8190. conn.send('close')
  8191. # close the current instance only if there are args
  8192. if len(sys.argv) > 1:
  8193. try:
  8194. self.listener.close()
  8195. except Exception:
  8196. pass
  8197. sys.exit()
  8198. except ConnectionRefusedError:
  8199. if sys.platform == 'win32':
  8200. pass
  8201. else:
  8202. os.system('rm /tmp/testipc')
  8203. self.listener = Listener(*address)
  8204. while True:
  8205. conn = self.listener.accept()
  8206. self.serve(conn)
  8207. def serve(self, conn):
  8208. while self.thread_exit is False:
  8209. msg = conn.recv()
  8210. if msg == 'close':
  8211. break
  8212. self.open_signal.emit(msg)
  8213. conn.close()
  8214. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8215. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8216. @pyqtSlot()
  8217. def run(self):
  8218. self.my_loop(self.address)
  8219. @pyqtSlot()
  8220. def close_listener(self):
  8221. self.thread_exit = True
  8222. self.listener.close()
  8223. # end of file